Compare commits

..

48 Commits

Author SHA1 Message Date
SlimusMinus
13d09d0073 Merge pull request #57 from SlimusMinus/fix-posts_api_contract
All checks were successful
deploy-backend / deploy (push) Successful in 1m32s
Posts API: user posts page, 201 on create, userLogin, deprecate old r…
2026-10-20 22:58:32 +03:00
SlimusMinus
ee5fb4e0e0 Posts API: user posts page, 201 on create, userLogin, deprecate old routes
- GET /api/v1/users/{userId}/posts returns Page<PostResponse> (owner sees unpublished)
- POST /api/v1/posts returns 201 with the created PostResponse and Location
- PostResponse.userLogin; userEmail kept with the same value as deprecated
- GET /api/v1/posts/{userId} and /search?city= marked deprecated; search is paged
- CORS exposes Retry-After and Location to the frontend

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:50:05 +03:00
SlimusMinus
248b4de752 Merge pull request #56 from SlimusMinus/claude/backend-review-80c5df
Claude/backend review 80c5df
2026-10-20 01:50:51 +03:00
SlimusMinus
ba6935bb1f Document multi-instance setup, rate limits and the new ad flow
README: new environment variables, ShedLock jobs and the multi-instance
section, rate limits and login lockout, profile privacy and token reissue,
WebSocket fan-out, 429 errors, tests and the updated limitations.
docs/advertising.md: serve -> impression -> click with signed tokens,
per-campaign daily caps, stats endpoint, campaign auto-finish, ads.* settings.
docs/redis.md: all new keys, pub/sub, locks, rate limiting, failure modes.
docs/images-storage.md: uploads outside transactions and orphan cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:46:18 +03:00
SlimusMinus
4ff61d8eda Delete orphan files from the image bucket nightly
OrphanFileCleanupService (03:30, ShedLock) lists the bucket and deletes objects
older than 24 hours that no images.url or users.avatar_url points to (full
URLs in legacy rows are normalised to keys), at most 5000 per run. Such files
appear when an upload via POST /api/v1/files is never attached or a request
fails between upload and save. Deleted files stay recoverable for 30 days as
noncurrent versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:42:39 +03:00
SlimusMinus
3dcd27d08a Keep network calls out of post transactions; cache and throttle geocoding
- PostService.create/update geocode and upload photos before opening the DB
  transaction (TransactionTemplate); uploaded files are removed if the
  transaction fails, so a DB connection is no longer held while waiting for
  Nominatim or MinIO.
- GeocodingService: configurable URL and User-Agent (geocoding.*), results
  cached in Redis for 30 days by coordinates rounded to ~11 m, and a
  cluster-wide 1 request/s slot (geo:throttle) as the public Nominatim policy
  requires; city/district are cut to the column sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:41:03 +03:00
SlimusMinus
85a2773f60 Build the chat list with batch queries instead of five queries per chat
Interlocutors, posts, last messages (one subquery by max id) and unread counts
(one GROUP BY) are loaded per list. The last message is now picked by id:
createdAt is written in the sender's time zone and is not monotonic between
users in different zones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:38:33 +03:00
SlimusMinus
2f52e6df70 Rework ad serving: signed impression tokens, per-campaign daily caps, stats
Follows the usual ad-server flow (serve -> impression -> click):
- GET /api/ads/next returns an impressionToken: HMAC-signed (ads.tracking.secret,
  defaults to jwt.secret) ad id, campaign id, subject and nonce, valid 1 hour.
  /impression and /click accept it, verify the signature, count each nonce once
  (Redis SET NX) and take the user/session from the token, so impressions
  cannot be forged or replayed. Requests without a token keep working until
  ads.tracking.require-token is switched on after the frontend update.
- The frequency cap is per campaign and calendar day (ads.timezone) and grows
  on real impressions, not on serving: ad:cap:<subject>:<campaign>:<yyyyMMdd>.
- Selection reads a 30-second in-memory snapshot of eligible ads (projection,
  invalidated locally on admin changes), filters capped campaigns with one
  MGET, picks by weight and then sets the cooldown atomically. The weighted
  sort drew random numbers inside the comparator, breaking its contract.
- Campaigns past endDate are finished every 10 minutes (ShedLock).
- GET /api/v1/admin/campaigns/{id}/stats: impressions, clicks and CTR per ad
  for a date range; composite indexes on impression/click (changelog 021).
- Removed unused cascade collections on Campaign/Advertising, the unused
  FullscreenAdActivateRequestDto and the /api/ads/impression/beacon rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:37:32 +03:00
SlimusMinus
477737c161 Hide private profile data and reissue tokens when users change their login
- GET /api/v1/users/{id} returns email and phone only to the user themself
  and to admins.
- When a user changes their own login, the PUT response carries a new token
  pair (login is the JWT subject, so the old tokens stop matching); old
  refresh tokens fail on their own because the stored login differs.
- The old avatar is deleted only after the profile is saved; login length is
  checked against the column size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:32:13 +03:00
SlimusMinus
48351398b5 Add Redis rate limiting, login lockout, password policy and health probes
- RateLimitFilter: fixed-window counters in Redis (Lua INCR+PEXPIRE) per
  client IP for login, registration, refresh, check-login, post creation,
  uploads, chat start and public ad endpoints; 429 with Retry-After; fails
  open when Redis is down. Rules live in rate-limit.* in application.yaml.
- Login is blocked for an account after 10 failed attempts in 15 minutes,
  independent of the client IP.
- Registration requires a password of at least 8 characters.
- server.forward-headers-strategy=native so the client IP survives a reverse
  proxy; graceful shutdown.
- /actuator/health with liveness/readiness probes is public (no details).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:31:12 +03:00
SlimusMinus
a696a21a1f Run safely with several instances: ShedLock jobs, Redis WebSocket fan-out
- Scheduled jobs (nightly cleanup, moderation, search dictionary rebuild) take
  a ShedLock lock in Redis, so only one instance runs each; the moderation run
  stops before its lock can expire.
- STOMP events (chat messages, unread counters, transcoding status) are
  published to the Redis channel ws:broadcast and every instance hands them to
  its local simple broker, so subscribers on other instances receive them.
  Falls back to local delivery if Redis is down; app.websocket.cluster-broadcast
  switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:31:12 +03:00
SlimusMinus
83270a8ece Rewrite README and add docs for advertising, Redis and image storage
README described Spring Boot 3.2.5/Java 21, an open /api/v1/test, the removed
MapCacheService and a single smoke test. It now matches the code: setup,
environment variables, architecture, packages, security rules, API, WebSocket
topics, post lifecycle, errors, tests, deploy and known limitations.

docs/advertising.md, docs/redis.md and docs/images-storage.md describe the
subsystems with references to the classes. .env.example lists the remaining
optional variables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:15:37 +03:00
SlimusMinus
7b81c18614 Give STOMP sessions a principal so /user/queue/errors is delivered
ChatWebSocketController reports send errors with convertAndSendToUser, but
CONNECT never set a user on the session, so those messages had no recipient.
The interceptor now sets a principal named after the user id on the message's
own accessor and allows subscriptions to /user/queue/** (resolved per session
by Spring, so it cannot reach another user's queue).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:09:57 +03:00
SlimusMinus
6b647e0bbf Add tests for the review fixes and make the context test runnable
- ReFoundApplicationTests runs on PostgreSQL via Testcontainers with a test
  profile holding test-only JWT/Redis/MinIO values; it previously failed
  without JWT_SECRET. The test also checks Liquibase + ddl validate.
- Unit tests: JWT access/refresh separation, refresh rotation, admin
  authority, exception mapping, image signature checks, ad media Range
  responses, post deletion after commit, moderation races, campaign status,
  ad selection without HttpSession and with Redis down, target URL rules.
- resolveRange rejects ranges that start past the end of the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:08:29 +03:00
SlimusMinus
3fd045131c Use ai.retry settings, add AI connect timeout, stop logging post text
AiRetryProperties was bound but @Retryable had hard-coded values, so
ai.retry.* in application.yaml had no effect. WebClient had no connect
timeout (Netty default 30 s per attempt). TextModerationProcessor logged the
whole moderation context, including post text, at INFO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:04:30 +03:00
SlimusMinus
a909b1f08b Fix advertising admin flows, tracking endpoints and ffmpeg timeout
- createAdvertising saved an IMAGE ad without mediaKey and only then answered
  400; validation now happens first. Target URLs must be absolute http(s)
  (they end up in href on the client), DTOs get @NotNull/@NotBlank.
- confirm-upload accepted any sourceKey; the transcoder deletes the source
  afterwards, so another ad's finished video could be deleted. Keys must now
  belong to the ad's own sources/ prefix.
- Activating a fullscreen ad could hit uq_fullscreen_ad_single_active because
  Hibernate may flush the new ACTIVE row first; the old one is flushed first.
- Campaign status change answered with the previous status (bulk UPDATE vs
  stale entity).
- Impression/click used getReferenceById, so unknown ids failed with 500 on
  the FK at commit; session ids are trimmed to the 64-char column.
- /api/ads/next created a Tomcat HttpSession for every client without
  X-Session-Id and failed with 500 when Redis was down; it now falls back to
  the client IP and returns 204 on Redis errors.
- ffmpeg output was read before waitFor, so the 5-minute timeout never fired;
  output goes to a temp log and its tail is logged on failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:04:10 +03:00
SlimusMinus
6e001fbc41 Fix post deletion, moderation races and cache leftovers
- PostService.delete did not remove favorites (FK without cascade -> 500 once a
  post was favorited) or chat links; owner, admin and nightly cleanup now share
  PostDeletionService, which deletes MinIO files only after commit. The nightly
  job also removes the images of expired posts.
- Moderation reads a snapshot in a short transaction, calls AI outside of it and
  applies the verdict only if the post is still in MODERATION and unchanged, so
  an edit made during a check can no longer go live unmoderated. Storage/AI
  outages keep the post in MODERATION instead of rejecting it.
- Posts without a category broke PostMapper with an NPE; title/phone/reward and
  address are checked against column sizes; a long address no longer overflows
  posts.city; Nominatim outages fall back to the address instead of 503.
- Favorites list hides posts that are back in moderation or rejected.
- Statistics counters use atomic UPDATEs instead of read-modify-write.
- Removed MapCacheService: its version key was bumped but never read.
- hibernate.default_batch_fetch_size=50 removes N+1 on images/users; show-sql
  is off by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 01:02:12 +03:00
SlimusMinus
98e6789b7e Validate image signatures, stream ad media with Range, keep live files in MinIO
- Uploaded images are checked by magic bytes; the key extension and stored
  Content-Type come from the detected format, not from the client's filename
  (an .html file sent as image/png was stored as <uuid>.html).
- /api/v1/ads-media streams from MinIO instead of loading whole videos into
  the heap, answers Range requests with 206 (iOS Safari needs it for video)
  and sets a long public Cache-Control for immutable keys.
- The bucket lifecycle rule expired every object after 180 days, including
  avatars and images of live posts; now only noncurrent versions expire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:58:56 +03:00
SlimusMinus
5cd60b6318 Harden auth: separate access/refresh JWT, atomic refresh rotation, admin checks
- Refresh JWT carried no role but was accepted by JwtAuthenticationFilter and
  the STOMP CONNECT as an access token; tokens now carry a typ claim and the
  filters accept only access tokens (legacy tokens are told apart by role).
- Refresh rotation uses GETDEL, so one refresh token cannot be spent twice;
  refresh tokens are no longer written to logs.
- isCurrentUserAdmin and file deletion compared authorities with "ADMIN"
  instead of "ROLE_ADMIN", so admins were never recognised.
- getCurrentUser answers 401 for anonymous requests; profile update keeps the
  login when the field is not sent; registration rejects empty login/password.
- GlobalExceptionHandler turned AccessDenied, BadCredentials, EntityNotFound,
  Spring MVC 4xx errors and upload limits into 500.
- Presigned URL TTL is capped at 7 days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:56:38 +03:00
SlimusMinus
71e69c4af8 Merge pull request #55 from SlimusMinus/fix/ai-moderation-mapping
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s
fix AI moderation response mapping and long post text
2026-10-20 00:35:17 +03:00
SlimusMinus
a68b89981c fix AI moderation response mapping and long post text
The AI service returns snake_case JSON, so detectedLabels was always null
and blocked posts carried no labels. Map it with @JsonProperty("detected_labels").

Post text longer than the service limit (5000 chars) got 422, which became
AiBadRequestException and the post was rejected. Text is now sent in
overlapping chunks within ai.text-max-length; blank text is skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:33:31 +03:00
SlimusMinus
d63a3309fa Merge pull request #54 from SlimusMinus/image-optimization
All checks were successful
deploy-backend / deploy (push) Successful in 1m30s
compress uploaded images and cache proxied files
2026-10-19 23:45:03 +03:00
SlimusMinus
a564e6f97d compress uploaded images and cache proxied files
Photos from iPhone (3-10 MB, 12-24 MP) were stored and served as-is, so the
feed loaded slowly on first open. Images are now downscaled to 1600px,
rotated by EXIF and re-encoded as progressive JPEG on upload. The
/api/v1/files proxy now sends Cache-Control instead of Spring Security's
no-store, so images are not re-downloaded on every app open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:43:07 +03:00
SlimusMinus
91ceafe75b Merge pull request #53 from SlimusMinus/fix-empty_advert
All checks were successful
deploy-backend / deploy (push) Successful in 1m17s
fixed empty advertising
2026-10-19 01:22:52 +03:00
SlimusMinus
057cdddff6 fixed empty advertising 2026-10-19 01:22:08 +03:00
SlimusMinus
72486a54f7 Merge pull request #52 from SlimusMinus/full-text-search
All checks were successful
deploy-backend / deploy (push) Successful in 2m18s
fixed search and add hints
2026-10-18 23:48:33 +03:00
SlimusMinus
96b4be5e6f fixed search and add hints 2026-10-18 23:46:13 +03:00
SlimusMinus
c1b14da7b9 Merge pull request #51 from SlimusMinus/image-caching
All checks were successful
deploy-backend / deploy (push) Successful in 1m28s
fixed image caching
2026-10-15 01:32:56 +03:00
SlimusMinus
307c4ae432 fixed image caching 2026-10-15 01:32:17 +03:00
SlimusMinus
4d9cb9946d Merge pull request #50 from SlimusMinus/fix-ai_timeout
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s
fixed ai image timeout
2026-10-15 00:49:40 +03:00
SlimusMinus
c83d41a036 fixed ai image timeout 2026-10-15 00:48:58 +03:00
SlimusMinus
13bb0c8503 Merge pull request #49 from SlimusMinus/add-adr_post
All checks were successful
deploy-backend / deploy (push) Successful in 2m9s
fixed address for map
2026-10-15 00:14:02 +03:00
SlimusMinus
03e2b36c8d fixed address for map 2026-10-15 00:13:19 +03:00
SlimusMinus
f8ccb15185 Merge pull request #48 from SlimusMinus/fix-address
All checks were successful
deploy-backend / deploy (push) Successful in 1m57s
fixed address for map
2026-10-15 00:02:58 +03:00
SlimusMinus
01ac227bdb fixed address for map 2026-10-15 00:02:10 +03:00
SlimusMinus
9eae82f6df Merge pull request #47 from SlimusMinus/chat-on-first-message
All checks were successful
deploy-backend / deploy (push) Successful in 1m23s
create chats only together with the first message
2026-10-13 01:50:06 +03:00
SlimusMinus
cd0d2a4081 create chats only together with the first message
- GET /api/v1/chats/with/{otherUserId}?postId= finds an existing chat
  (404 if there is none) and never creates one
- POST /api/v1/chats/with/{otherUserId}/messages?postId= with {content}
  finds or creates the chat and saves the first message in one
  transaction; same participant/post checks as before, WebSocket events
  still sent after commit
- the old POST /with/{otherUserId} that created empty chats is removed
- chat list hides chats without messages (existing empty rows stay in DB)
- empty messages are rejected with 400

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:45:18 +03:00
SlimusMinus
73463f6c5b Merge pull request #46 from SlimusMinus/fix-chat-per-post
All checks were successful
deploy-backend / deploy (push) Successful in 1m21s
Fix chat per post
2026-10-13 01:34:17 +03:00
SlimusMinus
da7d68c31a add ChatService tests for creating a chat about an ad
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:31:33 +03:00
SlimusMinus
45c4273ea8 fix chats: one chat per ad, ordering, delivery after commit, errors
A chat was unique per user pair, so contacting the same author about a
second ad returned the old chat with the old post_id, and the chat list
showed the other ad's title and image.

- chats are unique per (user_one_id, user_two_id, post_id); migration 015
  drops the old pair constraint whatever its name and adds the new one
- getOrCreateChat looks the chat up by users and post, and checks that the
  other user exists and the post belongs to one of the participants
- chat list is sorted by last message time (chat creation as fallback)
- WebSocket message and unread events are sent only after commit
- chat errors are ApiException: 404 not found, 403 not a participant,
  400 validation; messages are limited to 4000 characters
- Post.images ordered by id so the cover image is stable everywhere

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:23:09 +03:00
SlimusMinus
008852c781 Merge pull request #45 from SlimusMinus/fix-feed-pagination
All checks were successful
deploy-backend / deploy (push) Successful in 1m23s
fix feed pagination order, moderation reject and cache invalidation
2026-10-13 01:10:47 +03:00
SlimusMinus
d19f03d412 fix feed pagination order, moderation reject and cache invalidation
- getFeed: add id DESC as tie-breaker so posts with equal createdAt
  are not duplicated or lost between pages
- moderation: AI verdict false now sets REJECTED instead of ACTIVE
- nightly cleanup: invalidate feed and map caches after deleting posts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:07:26 +03:00
SlimusMinus
5ea7b438f5 Merge pull request #44 from SlimusMinus/fix-get_image
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
fixed getting image from minio
2026-10-13 00:43:45 +03:00
SlimusMinus
9dbf2dd043 fixed getting image from minio 2026-10-13 00:43:06 +03:00
SlimusMinus
e321fa4c60 Merge pull request #43 from SlimusMinus/add-timezone
All checks were successful
deploy-backend / deploy (push) Successful in 1m27s
added timezone for all create date
2026-10-11 23:26:58 +03:00
SlimusMinus
4119b767c3 added timezone for all create date 2026-10-11 23:26:11 +03:00
SlimusMinus
68d53fadf3 Merge pull request #42 from SlimusMinus/go-to_test
Add Docker build and deploy pipeline
2026-10-08 01:23:01 +03:00
SlimusMinus
818c8f6a11 Add Docker build and deploy pipeline
All checks were successful
deploy-backend / deploy (push) Successful in 8m24s
2026-10-07 22:56:56 +03:00
162 changed files with 9043 additions and 2436 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
.git
.gradle
build
target
.idea

55
.env.example Normal file
View File

@@ -0,0 +1,55 @@
# Шаблон переменных окружения. Скопируй в .env и заполни значениями.
# Сам .env добавлен в .gitignore и не должен попадать в репозиторий.
#
# Как приложение их получает:
# docker compose читает .env автоматически;
# Spring Boot — нет. Нужно экспортировать переменные в терминал
# или прописать их в Environment variables в настройках запуска IDE.
# --- Обязательные: без них приложение не стартует ---
# Ключи доступа к MinIO (S3-совместимое хранилище).
# ВНИМАНИЕ: они должны совпадать с MINIO_ACCESS_KEY / MINIO_SECRET_KEY
# в docker-compose.yaml, иначе приложение не подключится к MinIO.
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
# Пароль Redis. Тот же, что в docker-compose.yaml.
# docker-compose падает с понятной ошибкой, если переменная пустая.
REDIS_PASSWORD=
# Секрет подписи JWT (HMAC-SHA): строка не короче 32 байт. Значения
# по умолчанию нет — без переменной приложение не стартует.
# Сгенерировать, например, так:
# openssl rand -base64 48
JWT_SECRET=
# --- Необязательно: есть значения по умолчанию ---
# REDIS_HOST=localhost
# MINIO_ENDPOINT=http://localhost:9010
# MINIO_BUCKET=refound-images
# 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

View File

@@ -0,0 +1,16 @@
name: deploy-backend
on:
push:
branches: [main]
jobs:
deploy:
runs-on: host
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t nakhodka-backend:latest -t nakhodka-backend:${{ github.sha }} .
- name: Restart backend
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d backend
- name: Cleanup
run: docker image prune -f

18
Dockerfile Normal file
View File

@@ -0,0 +1,18 @@
FROM eclipse-temurin:25-jdk AS build
WORKDIR /app
COPY . .
RUN sed -i 's/\r$//' gradlew \
&& chmod +x gradlew \
&& ./gradlew bootJar --no-daemon -x test \
&& cp "$(ls build/libs/*.jar | grep -v plain | head -n1)" /app/app.jar
FROM eclipse-temurin:25-jre
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -r -u 1001 app
WORKDIR /app
COPY --from=build /app/app.jar app.jar
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-Xmx768m", "-jar", "app.jar"]

2104
README.MD

File diff suppressed because it is too large Load Diff

View File

@@ -52,6 +52,11 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.minio:minio:8.6.0'
// Сжатие картинок при загрузке: ресайз + поворот по EXIF, чтение WebP/CMYK-JPEG
implementation 'net.coobird:thumbnailator:0.4.20'
implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.12.0'
implementation 'com.twelvemonkeys.imageio:imageio-webp:3.12.0'
// JWT
implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5'
@@ -60,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'
@@ -70,6 +80,10 @@ dependencies {
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// Поиск опирается на возможности PostgreSQL (стемминг, tsvector, pg_trgm) — тестируем на настоящей БД
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

389
docs/advertising.md Normal file
View 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
View 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
View 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 не вешает
запросы надолго.

View File

@@ -3,6 +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;
@@ -15,7 +18,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
scanBasePackages = "com.krylov.refound",
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
)@EnableScheduling
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class})
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
SearchProperties.class, RateLimitProperties.class, AdsProperties.class})
@EnableRetry
public class ReFoundApplication {

View File

@@ -0,0 +1,38 @@
package com.krylov.refound.ai.client;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import java.util.concurrent.TimeoutException;
/**
* Перевод ошибок WebClient в исключения AI-клиента.
*/
final class AiClientErrors {
private AiClientErrors() {
}
/**
* Ошибки статуса (onStatus) уже пришли как AiException — их не трогаем.
* Таймаут ответа → AiTimeoutException, прочие сетевые ошибки → AiUnavailableException.
*/
static AiException translate(Exception ex) {
if (ex instanceof AiException aiException) {
return aiException;
}
if (isTimeout(ex)) {
return new AiTimeoutException(ex);
}
return new AiUnavailableException(ex);
}
static boolean isTimeout(Throwable ex) {
for (Throwable t = ex; t != null; t = t.getCause()) {
if (t instanceof io.netty.handler.timeout.TimeoutException || t instanceof TimeoutException) {
return true;
}
}
return false;
}
}

View File

@@ -1,14 +1,15 @@
package com.krylov.refound.ai.client;
import com.krylov.refound.ai.exception.AiBadRequestException;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
@Slf4j
@Component
@@ -39,13 +40,16 @@ public class AiHttpClient {
log.info("AI response received");
return response;
} catch (WebClientRequestException ex) {
log.error("AI connection failed", ex);
throw new AiUnavailableException(ex);
} catch (Exception ex) {
log.error("AI request failed", ex);
throw new AiUnavailableException(ex);
AiException error = AiClientErrors.translate(ex);
if (error instanceof AiTimeoutException) {
log.warn("AI text moderation did not respond in time");
} else if (error instanceof AiUnavailableException) {
log.warn("AI text moderation is unavailable: {}", ex.getMessage());
} else {
log.warn("AI text moderation returned an error: {}", error.getMessage());
}
throw error;
}
}
}

View File

@@ -1,8 +1,13 @@
package com.krylov.refound.ai.client;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.exception.AiBadRequestException;
import com.krylov.refound.ai.exception.AiException;
import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import java.io.IOException;
import java.time.Duration;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
@@ -12,19 +17,28 @@ import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import reactor.netty.http.client.HttpClientRequest;
@Slf4j
@Component
@RequiredArgsConstructor
public class AiMultipartHttpClient {
private final WebClient aiWebClient;
private final AiProperties properties;
public <R> R post(String uri, MultipartFile file, Class<R> responseType) {
log.info("AI IMAGE POST {}", uri);
byte[] bytes;
try {
bytes = file.getBytes();
} catch (IOException ex) {
throw new IllegalStateException("Cannot read image for AI moderation", ex);
}
Duration timeout = Duration.ofSeconds(properties.getImageTimeout());
try {
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("file", new ByteArrayResource(file.getBytes()) {
builder.part("file", new ByteArrayResource(bytes) {
@Override
public String getFilename() {
return file.getOriginalFilename();
@@ -36,6 +50,8 @@ public class AiMultipartHttpClient {
.uri(uri)
.contentType(MediaType.MULTIPART_FORM_DATA)
.bodyValue(builder.build())
// Картинки обрабатываются дольше текста — свой таймаут ответа
.httpRequest(req -> ((HttpClientRequest) req.getNativeRequest()).responseTimeout(timeout))
.retrieve()
.onStatus(
HttpStatusCode::is4xxClientError,
@@ -51,12 +67,16 @@ public class AiMultipartHttpClient {
.block();
log.info("AI image response received");
return response;
} catch (WebClientRequestException ex) {
log.error("WebClientRequestException in AiMultipartHttpClient {}", ex.getMessage(), ex);
throw new AiUnavailableException(ex);
} catch (Exception ex) {
log.error("Exception in AiMultipartHttpClient {}", ex.getMessage(), ex);
throw new RuntimeException("Cannot send image to AI", ex);
AiException error = AiClientErrors.translate(ex);
if (error instanceof AiTimeoutException) {
log.warn("AI image moderation did not respond within {}s", timeout.toSeconds());
} else if (error instanceof AiUnavailableException) {
log.warn("AI image moderation is unavailable: {}", ex.getMessage());
} else {
log.warn("AI image moderation returned an error: {}", error.getMessage());
}
throw error;
}
}
}

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.ai.client;
import com.krylov.refound.ai.dto.ImageModerationResponse;
import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -18,25 +19,36 @@ public class ImageModerationClient {
private final AiMultipartHttpClient client;
@Retryable(
retryFor = {AiUnavailableException.class, AiServerException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 500, multiplier = 2)
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
// Параметры из 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");
return client.post("/api/v1/moderation/image", file, ImageModerationResponse.class);
}
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
// проверяется снова при следующем запуске планировщика.
@Recover
public ImageModerationResponse recover(AiUnavailableException e, MultipartFile file) {
log.error("AI ImageModeration unavailable after retries", e);
log.error("AI ImageModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
return null;
}
@Recover
public ImageModerationResponse recover(AiTimeoutException e, MultipartFile file) {
log.error("AI ImageModeration timed out after retries");
return null;
}
@Recover
public ImageModerationResponse recover(AiServerException e, MultipartFile file) {
log.error("AI ImageModeration server error after retries", e);
log.error("AI ImageModeration server error after retries: {}", e.getMessage());
return null;
}

View File

@@ -3,6 +3,7 @@ package com.krylov.refound.ai.client;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.dto.TextModerationRequest;
import com.krylov.refound.ai.exception.AiServerException;
import com.krylov.refound.ai.exception.AiTimeoutException;
import com.krylov.refound.ai.exception.AiUnavailableException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -19,25 +20,36 @@ public class TextModerationClient {
private final AiHttpClient client;
@Retryable(
retryFor = {AiUnavailableException.class, AiServerException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 500, multiplier = 2)
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
// Параметры из 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");
return client.post("/api/v1/moderation/text", new TextModerationRequest(text), ModerationResponse.class);
}
// После исчерпания попыток возвращаем null: пост остаётся на модерации и
// проверяется снова при следующем запуске планировщика.
@Recover
public ModerationResponse recover(AiUnavailableException e, String text) {
log.error("AI TextModeration unavailable after retries", e);
log.error("AI TextModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
return null;
}
@Recover
public ModerationResponse recover(AiTimeoutException e, String text) {
log.error("AI TextModeration timed out after retries");
return null;
}
@Recover
public ModerationResponse recover(AiServerException e, String text) {
log.error("AI TextModeration server error after retries", e);
log.error("AI TextModeration server error after retries: {}", e.getMessage());
return null;
}

View File

@@ -19,4 +19,17 @@ public class AiProperties {
* 10 seconds
*/
private int timeout;
/**
* Таймаут ответа для модерации изображений, секунды. Картинки AI-сервис
* обрабатывает заметно дольше текста, особенно первую после простоя.
*/
private int imageTimeout = 30;
/**
* Максимальная длина текста в одном запросе к AI-сервису (TEXT_MAX_LENGTH
* на его стороне). Более длинный текст отправляется частями — иначе сервис
* отвечает 422, и пост ошибочно отклоняется.
*/
private int textMaxLength = 5000;
}

View File

@@ -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())
);

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;
@@ -11,5 +12,7 @@ public class ImageModerationResponse {
private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels;
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Builder;
import lombok.Data;
@@ -14,6 +15,8 @@ public class ModerationResponse {
private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels;
}

View File

@@ -1,8 +1,11 @@
package com.krylov.refound.ai.pipeline;
import com.krylov.refound.ai.client.TextModerationClient;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.exception.ContentBlockedException;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
@@ -14,31 +17,93 @@ import org.springframework.stereotype.Component;
@Order(10)
public class TextModerationProcessor implements ModerationProcessor {
/**
* Перекрытие соседних частей: фраза на стыке целиком попадает хотя бы в одну.
*/
static final int CHUNK_OVERLAP = 200;
private final TextModerationClient client;
private final AiProperties properties;
@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()
);
ModerationResponse response = client.moderate(text);
if (response == null) {
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
return null;
// Пустой текст AI-сервис отклоняет как невалидный запрос (400/422) —
// проверять нечего, это не повод отклонять пост
if (text.isBlank()) {
log.info("Текст поста пустой, пропускаем модерацию текста");
return Boolean.TRUE;
}
log.info("AI moderation result approved={}, score={}, reason={}", response.getApproved(), response.getScore(), response.getReason());
List<String> chunks = splitText(text, properties.getTextMaxLength(), CHUNK_OVERLAP);
if (chunks.size() > 1) {
log.info("Текст длиной {} отправляется на модерацию частями: {}", text.length(), chunks.size());
}
if (!Boolean.TRUE.equals(response.getApproved())) {
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
for (String chunk : chunks) {
if (chunk.isBlank()) {
continue;
}
ModerationResponse response = client.moderate(chunk);
if (response == null) {
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
return null;
}
log.info("AI moderation result approved={}, score={}, reason={}", response.getApproved(), response.getScore(), response.getReason());
if (!Boolean.TRUE.equals(response.getApproved())) {
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
}
}
return Boolean.TRUE;
}
/**
* Режет текст на части не длиннее maxLength с перекрытием overlap.
* Граница по возможности ставится на пробел, чтобы не разрезать слово.
*/
static List<String> splitText(String text, int maxLength, int overlap) {
if (text.length() <= maxLength) {
return List.of(text);
}
int safeOverlap = Math.min(overlap, maxLength / 4);
List<String> chunks = new ArrayList<>();
int start = 0;
while (start < text.length()) {
int end = Math.min(start + maxLength, text.length());
if (end < text.length()) {
int space = lastWhitespace(text, start + maxLength / 2, end);
if (space > 0) {
end = space;
}
}
chunks.add(text.substring(start, end));
if (end == text.length()) {
break;
}
start = Math.max(end - safeOverlap, start + 1);
}
return chunks;
}
private static int lastWhitespace(String text, int from, int to) {
for (int i = to - 1; i >= from; i--) {
if (Character.isWhitespace(text.charAt(i))) {
return i;
}
}
return -1;
}
private String buildText(String title, String description) {
StringBuilder builder = new StringBuilder();

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,32 @@
package com.krylov.refound.config;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Кладёт таймзону из заголовка {@code X-Timezone} в {@link TimeZoneContext} на
* время обработки запроса. Благодаря этому время создания сущностей
* (createdAt и т.п.) ставится по зоне клиента, а не по зоне сервера.
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TimeZoneFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
TimeZoneContext.set(request.getHeader(TimeZoneContext.HEADER));
filterChain.doFilter(request, response);
} finally {
TimeZoneContext.clear();
}
}
}

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.dto.StartChatRequest;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import java.util.List;
@@ -11,11 +12,13 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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;
@@ -29,12 +32,21 @@ public class ChatController {
private final UserService userService;
private final ChatService chatService;
// Создать чат с пользователем или получить существующий
@PostMapping("/with/{otherUserId}")
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
@GetMapping("/with/{otherUserId}")
public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.getOrCreateChat(currentUserId, otherUserId, postId);
log.info("findChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return ResponseEntity.of(chatService.findChat(currentUserId, otherUserId, postId));
}
// Первое сообщение: чат создаётся (или находится) вместе с сообщением — пустых чатов не бывает
@PostMapping("/with/{otherUserId}/messages")
public ChatDto startChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId,
@RequestBody StartChatRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("startChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
}
// Список всех чатов текущего пользователя

View File

@@ -1,7 +1,9 @@
package com.krylov.refound.controller;
import com.krylov.refound.dto.SendMessageRequest;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.util.TimeZoneContext;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
@@ -43,10 +45,14 @@ public class ChatWebSocketController {
}
try {
Object timezone = sessionAttributes.get(TimeZoneContext.SESSION_ATTRIBUTE);
TimeZoneContext.set(timezone instanceof String tz ? tz : null);
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
} catch (SecurityException | IllegalArgumentException e) {
} catch (ApiException | IllegalArgumentException e) {
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage()
);
} finally {
TimeZoneContext.clear();
}
}
}

View File

@@ -1,8 +1,12 @@
package com.krylov.refound.controller;
import com.krylov.refound.service.FileStorageService;
import java.time.Duration;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@@ -18,6 +22,13 @@ import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileStorageController {
/**
* Сколько браузер помнит редирект на presigned URL и не ходит за ним на бэк.
* Вместе с кэшем ссылки (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;
@PostMapping
@@ -34,6 +45,36 @@ public class FileStorageController {
return fileStorageService.downloadFile(key);
}
/**
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
* Ссылка стабильна (кэшируется) и сам редирект кэшируется браузером — повторный
* показ картинки не требует ни запроса на бэк, ни повторной загрузки.
*/
@GetMapping(value = "/{*objectName}", params = "presigned=true")
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
return ResponseEntity.status(302)
.header(HttpHeaders.LOCATION, url)
.cacheControl(CacheControl.maxAge(REDIRECT_CACHE_MAX_AGE).cachePrivate())
.build();
}
/**
* Возвращает presigned URL в JSON.
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
*/
@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;
// 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));
}
@DeleteMapping("/{*objectName}")
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
log.info("deleteFile {}", objectName);
@@ -42,4 +83,4 @@ public class FileStorageController {
fileStorageService.deleteFileAsCurrentUser(key);
return ResponseEntity.noContent().build();
}
}
}

View File

@@ -3,7 +3,12 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.PostRequest;
import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.dto.StatusUpdateRequest;
import com.krylov.refound.enums.ErrorCode;
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;
@@ -11,7 +16,11 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.net.URI;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
@@ -32,19 +41,48 @@ import org.springframework.web.multipart.MultipartFile;
public class PostController {
private final PostService service;
private final SearchSuggestService searchSuggestService;
/** 201 с созданным объявлением и Location на него (раньше — эхо PostRequest). */
@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());
return service.create(request, images);
public ResponseEntity<PostResponse> create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
PostResponse created = service.create(request, images);
// Одно объявление пока отдаёт /detail/{id}; /posts/{id} поменяет смысл вторым этапом
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/detail/{id}").buildAndExpand(created.getId()).toUri();
return ResponseEntity.created(location).body(created);
}
@GetMapping
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get all feed");
return service.getFeed(search, pageable);
public Page<PostResponse> getFeed(@RequestParam(required = false) String search,
@RequestParam(required = false) String type,
@RequestParam(name = "category", required = false) List<String> categories,
@RequestParam(name = "city", required = false) List<String> cities,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get feed: search='{}', type={}, categories={}, cities={}", search, type, categories, cities);
PostFeedFilter filter;
try {
filter = PostFeedFilter.of(type, categories, cities);
} catch (IllegalArgumentException e) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Некорректный фильтр ленты: " + e.getMessage(),
HttpStatus.BAD_REQUEST);
}
return service.getFeed(search, filter, pageable);
}
/** Подсказки для последнего слова строки поиска: «потерян барс» → [барсетка, барсик]. */
@GetMapping("/search/suggest")
public List<String> suggest(@RequestParam(name = "q", defaultValue = "") String query) {
return searchSuggestService.suggest(query);
}
/**
* Объявления ПОЛЬЗОВАТЕЛЯ с id {@code id} (историческое имя маршрута).
* Новый маршрут — GET /api/v1/users/{userId}/posts (постранично). Этот
* останется до деплоя фронта, затем /posts/{id} станет одним объявлением.
*/
@Deprecated
@GetMapping("/{id:\\d+}")
public List<PostResponse> getById(@PathVariable Long id) {
log.info("get feed by id {}", id);
@@ -73,10 +111,13 @@ public class PostController {
return service.updateStatus(id, request.getStatus());
}
/** Устарело: используйте GET /api/v1/posts?city= (лента с тем же фильтром). */
@Deprecated
@GetMapping("/search")
public List<PostResponse> search(@RequestParam(required = false) String city) {
public Page<PostResponse> search(@RequestParam(required = false) String city,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("search posts by city {}", city);
return service.searchByCity(city);
return service.searchByCity(city, pageable);
}
@GetMapping("/cities")

View File

@@ -0,0 +1,32 @@
package com.krylov.refound.controller;
import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.service.PostService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* Объявления пользователя: GET /api/v1/users/{userId}/posts. Публичный —
* владельцу (с токеном) отдаются и неопубликованные (MODERATION, REJECTED).
*/
@Slf4j
@RestController
@RequiredArgsConstructor
public class UserPostController {
private final PostService postService;
@GetMapping("/api/v1/users/{userId:\\d+}/posts")
public Page<PostResponse> getUserPosts(@PathVariable Long userId,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get posts of user {}", userId);
return postService.getPostsByUser(userId, pageable);
}
}

View File

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

View File

@@ -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,37 +29,40 @@ 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()) {
log.warn("failed get advertising");
// Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
log.debug("No advertising to show, returning 204");
return ResponseEntity.noContent().build();
}
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();
}

View File

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

View File

@@ -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')")

View File

@@ -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"));

View File

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

View File

@@ -16,6 +16,7 @@ public class PostResponse {
private String category;
private String city;
private String district;
private String address;
// Координаты нужны фронту, чтобы кнопка «место на карте» открывала точку
// объявления, а не общий вид карты. Без этих полей /detail/{id} отдавал
// null, и MapView падал на дефолтный центр.
@@ -24,6 +25,13 @@ public class PostResponse {
private PostType type;
private PostStatus status;
private LocalDateTime createdAt;
/** Логин автора. */
private String userLogin;
/**
* Тот же логин под старым (ошибочным) именем — для клиентов, которые ещё
* читают userEmail. Удалить после перехода фронта на userLogin.
*/
@Deprecated
private String userEmail;
private String phone;
private List<String> images;

View File

@@ -0,0 +1,9 @@
package com.krylov.refound.dto;
import lombok.Data;
/** Первое сообщение, с которым создаётся чат. */
@Data
public class StartChatRequest {
private String content;
}

View File

@@ -27,6 +27,7 @@ public class AdminPostResponse {
private String category;
private String city;
private String district;
private String address;
private Double latitude;
private Double longitude;
private String phone;

View File

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

View File

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

View File

@@ -0,0 +1,10 @@
package com.krylov.refound.dto.advertising;
/** Показы, клики и CTR (в процентах) одного объявления за период отчёта. */
public record AdvertisingStatsDto(
Long advertisingId,
long impressions,
long clicks,
double ctr
) {
}

View File

@@ -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
) {

View File

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

View File

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

View File

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

View File

@@ -2,7 +2,9 @@ package com.krylov.refound.dto.advertising;
public record ClickRequestDto(
Long advertisingId,
String sessionId
String sessionId,
/** Тот же токен показа, что и для /api/ads/impression. */
String token
) {
}

View File

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

View File

@@ -1,5 +0,0 @@
package com.krylov.refound.dto.advertising;
public record FullscreenAdActivateRequestDto(boolean active) {
}

View File

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

View File

@@ -4,7 +4,8 @@ public record SelectedAdvertisingDto(
Long advertisingId,
String type,
String mediaKey,
String targetUrl
String targetUrl,
String impressionToken
) {
}

View File

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

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -18,7 +19,7 @@ import lombok.ToString;
import org.hibernate.proxy.HibernateProxy;
@Entity
@Table(name = "chats", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_one_id", "user_two_id"})})
@Table(name = "chats", uniqueConstraints = {@UniqueConstraint(name = "uq_chat_users_post", columnNames = {"user_one_id", "user_two_id", "post_id"})})
@Getter
@Setter
@ToString
@@ -42,7 +43,7 @@ public class Chat {
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
@Override

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -38,6 +39,6 @@ public class Message {
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
}

View File

@@ -14,6 +14,7 @@ import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -37,6 +38,9 @@ public class Post {
private PostCategory category;
private String city;
private String district;
// Полный адрес из формы; city/district — нормализованные данные геокодера
@Column(length = 500)
private String address;
private Double latitude;
private Double longitude;
private LocalDateTime createdAt;
@@ -58,7 +62,9 @@ public class Post {
@JsonIgnore
private User user;
// Порядок загрузки: первая картинка (обложка в ленте, чатах, на карте) должна быть стабильной
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private List<Image> images = new ArrayList<>();
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -34,6 +35,6 @@ public class Review {
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
}

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.entity;
import com.krylov.refound.enums.Role;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
@@ -36,6 +37,6 @@ public class User {
@PrePersist
public void prePersist() {
this.createdAt = LocalDateTime.now();
this.createdAt = TimeZoneContext.now();
}
}

View File

@@ -2,13 +2,12 @@ package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.AdvertisingType;
import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "advertising")
@@ -27,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)
@@ -43,24 +43,10 @@ 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) {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
}
}

View File

@@ -1,13 +1,12 @@
package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.CampaignStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "campaign")
@@ -38,17 +37,10 @@ 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) {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
}
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity.advertising;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@@ -32,7 +33,7 @@ public class Click {
@PrePersist
protected void onCreate() {
if (clickedAt == null) {
clickedAt = LocalDateTime.now();
clickedAt = TimeZoneContext.now();
}
}
}

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.entity.advertising;
import com.krylov.refound.enums.advertising.FullscreenAdStatus;
import com.krylov.refound.enums.advertising.TranscodingStatus;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@@ -38,7 +39,7 @@ public class FullscreenAdvertising {
@PrePersist
protected void onCreate() {
if (createdAt == null) {
createdAt = LocalDateTime.now();
createdAt = TimeZoneContext.now();
}
}
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.entity.advertising;
import com.krylov.refound.util.TimeZoneContext;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@@ -32,7 +33,7 @@ public class Impression {
@PrePersist
protected void onCreate() {
if (shownAt == null) {
shownAt = LocalDateTime.now();
shownAt = TimeZoneContext.now();
}
}
}

View File

@@ -8,5 +8,6 @@ public enum ErrorCode {
UNAUTHORIZED,
FORBIDDEN,
CONTENT_BLOCKED,
INVALID_STATUS_TRANSITION
INVALID_STATUS_TRANSITION,
TOO_MANY_REQUESTS
}

View File

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

View File

@@ -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()

View File

@@ -19,9 +19,11 @@ public interface PostMapper {
Post toEntity(PostRequest request);
@Mapping(source = "user.id", target = "userId")
@Mapping(source = "user.login", target = "userLogin")
@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")

View 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);
}
}

View File

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

View File

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

View File

@@ -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;
@@ -10,22 +11,26 @@ import org.springframework.data.repository.query.Param;
public interface ChatRepository extends JpaRepository<Chat, Long> {
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2")
Optional<Chat> findByUsers(Long u1, Long u2);
/** Чат пары пользователей по конкретному объявлению (postId == null — чат без объявления). */
@Query("SELECT c FROM Chat c WHERE c.userOneId = :u1 AND c.userTwoId = :u2 "
+ "AND ((:postId IS NULL AND c.postId IS NULL) OR c.postId = :postId)")
List<Chat> findByUsersAndPost(Long u1, Long u2, Long postId);
/** Есть ли пользователь среди участников чата. Имя не следует конвенции Spring Data, потому что запрос задан явно. */
@Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END FROM Chat c "
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
boolean isParticipantOfChat(Long chatId, Long userId);
@Query("SELECT c FROM Chat c WHERE c.userOneId = :userId OR c.userTwoId = :userId ORDER BY c.createdAt DESC")
List<Chat> findAllByUserId(Long userId); // Changed from Optional to List
/** Чаты пользователя, в которых есть хотя бы одно сообщение (пустые в списке не показываем). */
@Query("SELECT c FROM Chat c WHERE (c.userOneId = :userId OR c.userTwoId = :userId) "
+ "AND EXISTS (SELECT 1 FROM Message m WHERE m.chatId = c.id) ORDER BY c.createdAt DESC")
List<Chat> findAllByUserId(Long userId);
/**
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.
* У 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);
}

View File

@@ -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();
}

View File

@@ -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);

View File

@@ -10,15 +10,19 @@ 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;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
List<Post> findByUserId(Long userId);
Page<Post> findByUserId(Long userId, Pageable pageable);
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);
List<Post> findByStatus(PostStatus status);
List<Post> findByCreatedAtBefore(LocalDateTime date);
@@ -26,11 +30,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);

View File

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

View File

@@ -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();
}

View File

@@ -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("""

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,77 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostCategory;
import com.krylov.refound.enums.PostType;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;
/**
* Фильтры публичной ленты: тип объявления, категории, города.
* Пустые значения означают «без ограничения».
*
* @param cities названия городов/районов в нижнем регистре
*/
public record PostFeedFilter(PostType type, Set<PostCategory> categories, Set<String> cities) {
public static final PostFeedFilter NONE = new PostFeedFilter(null, Set.of(), Set.of());
public PostFeedFilter {
categories = categories == null ? Set.of() : Set.copyOf(categories);
cities = cities == null ? Set.of() : Set.copyOf(cities);
}
/**
* Собирает фильтр из параметров запроса. Тип принимается в любом регистре
* ("loss"/"LOSS"), категории — именем enum (ANIMAL) или как на фронте («Питомец»).
* Неизвестные значения — 400 через IllegalArgumentException.
*/
public static PostFeedFilter of(String type, Collection<String> categories, Collection<String> cities) {
PostType postType = StringUtils.hasText(type) ? PostType.from(type.trim()) : null;
Set<PostCategory> postCategories = categories == null ? Set.of() : categories.stream()
.filter(StringUtils::hasText)
.flatMap(value -> Arrays.stream(value.split(",")))
.map(String::trim)
.filter(StringUtils::hasText)
.map(PostFeedFilter::parseCategory)
.collect(Collectors.toCollection(LinkedHashSet::new));
Set<String> cityNames = cities == null ? Set.of() : cities.stream()
.filter(StringUtils::hasText)
.map(city -> city.trim().toLowerCase(Locale.ROOT))
.collect(Collectors.toCollection(LinkedHashSet::new));
return new PostFeedFilter(postType, postCategories, cityNames);
}
public boolean isEmpty() {
return type == null && categories.isEmpty() && cities.isEmpty();
}
/** Стабильное представление для ключа кэша. */
public String cacheKeyPart() {
return "type=" + Objects.toString(type, "")
+ ":cat=" + categories.stream().map(Enum::name).sorted().collect(Collectors.joining(","))
+ ":city=" + cities.stream().sorted().collect(Collectors.joining(","));
}
private static PostCategory parseCategory(String value) {
for (PostCategory category : PostCategory.values()) {
if (category.name().equalsIgnoreCase(value)) {
return category;
}
}
return PostCategory.fromDisplayName(value);
}
public List<String> categoryNames() {
return categories.stream().map(Enum::name).toList();
}
}

View File

@@ -0,0 +1,129 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* Нативные запросы полнотекстового поиска по объявлениям (PostgreSQL).
* Возвращает только id в нужном порядке — сами посты грузит JPA.
*/
@Repository
@RequiredArgsConstructor
public class PostSearchRepository {
/** Должно совпадать с выражением индекса idx_posts_title_trgm (changelog 019). */
private static final String TITLE_TRGM = "translate(lower(p.title), 'ё', 'е')";
private final NamedParameterJdbcTemplate jdbc;
/** Разобранный пользовательский ввод в виде текста tsquery ("" — нет значимых слов). */
public record ParsedQuery(String full, String rest, String prefix, String titlePrefix) {
}
/**
* websearch_to_tsquery не падает на спецсимволах и понимает "кавычки", -минус и or.
* rest — запрос без последнего слова, prefix — последнее слово как префикс ('кош':*),
* titlePrefix — тот же префикс, но только среди слов заголовка ('кош':*A, вес A — заголовок).
*/
public ParsedQuery parse(String text, String rest, String prefixWord) {
MapSqlParameterSource params = new MapSqlParameterSource()
.addValue("text", text)
.addValue("rest", rest == null ? "" : rest)
// prefixWord заранее очищен до букв и цифр — to_tsquery на нём не упадёт
.addValue("prefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*")
.addValue("titlePrefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*A");
return jdbc.queryForObject("""
select websearch_to_tsquery('russian', :text)::text as full_q,
websearch_to_tsquery('russian', :rest)::text as rest_q,
case when :prefix = '' then '' else to_tsquery('russian', :prefix)::text end as prefix_q,
case when :titlePrefix = '' then '' else to_tsquery('russian', :titlePrefix)::text end as title_prefix_q
""", params, (rs, i) -> new ParsedQuery(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4)));
}
/** Слово → его лексемы по русскому стеммеру (для синонимов). */
public List<String> lexemes(String word) {
return jdbc.queryForList(
"select lexeme from unnest(to_tsvector('russian', :word)) order by lexeme",
new MapSqlParameterSource("word", word), String.class);
}
public long countFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter) {
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", tsquery);
return jdbc.queryForObject("select count(*) from posts p where p.search_vector @@ cast(:q as tsquery)"
+ filters(filter), params, Long.class);
}
/** Совпадения в заголовке (вес A) ранжируются выше, чем в описании (вес B). */
public List<Long> findFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter,
long offset, int limit) {
MapSqlParameterSource params = baseParams(statuses, filter)
.addValue("q", tsquery)
.addValue("offset", offset)
.addValue("limit", limit);
return jdbc.queryForList("select p.id from posts p where p.search_vector @@ cast(:q as tsquery)"
+ filters(filter)
+ " order by ts_rank_cd(p.search_vector, cast(:q as tsquery)) desc, p.created_at desc, p.id desc"
+ " limit :limit offset :offset", params, Long.class);
}
/**
* Поиск с опечатками по заголовку. Порог задаётся на транзакцию, поэтому
* методы *Typo вызываются внутри @Transactional — иначе set_config не
* действует на следующий запрос. Оператор &lt;% использует GIN-индекс.
*/
public void setTypoThreshold(double threshold) {
jdbc.queryForObject("select set_config('pg_trgm.word_similarity_threshold', :t, true)",
new MapSqlParameterSource("t", Double.toString(threshold)), String.class);
}
public long countTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter) {
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", normalizeForTrgm(text));
return jdbc.queryForObject("select count(*) from posts p where :q <% " + TITLE_TRGM
+ filters(filter), params, Long.class);
}
public List<Long> findTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter,
long offset, int limit) {
MapSqlParameterSource params = baseParams(statuses, filter)
.addValue("q", normalizeForTrgm(text))
.addValue("offset", offset)
.addValue("limit", limit);
return jdbc.queryForList("select p.id from posts p where :q <% " + TITLE_TRGM
+ filters(filter)
+ " order by word_similarity(:q, " + TITLE_TRGM + ") desc, p.created_at desc, p.id desc"
+ " limit :limit offset :offset", params, Long.class);
}
static String normalizeForTrgm(String text) {
return text.toLowerCase(Locale.ROOT).replace('ё', 'е').trim();
}
private static MapSqlParameterSource baseParams(Collection<PostStatus> statuses, PostFeedFilter filter) {
return new MapSqlParameterSource()
.addValue("statuses", statuses.stream().map(Enum::name).toList())
.addValue("type", filter.type() == null ? null : filter.type().name())
.addValue("categories", filter.categoryNames())
.addValue("cities", List.copyOf(filter.cities()));
}
private static String filters(PostFeedFilter filter) {
StringBuilder sql = new StringBuilder(" and p.status in (:statuses)");
if (filter.type() != null) {
sql.append(" and p.type = :type");
}
if (!filter.categories().isEmpty()) {
sql.append(" and p.category in (:categories)");
}
if (!filter.cities().isEmpty()) {
sql.append(" and (lower(p.city) in (:cities) or lower(p.district) in (:cities))");
}
return sql.toString();
}
}

View File

@@ -0,0 +1,158 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Поиск объявлений по тексту. Этапы идут по очереди, пока какой-то не найдёт
* хоть что-то:
* <ol>
* <li>полнотекстовый поиск (стемминг + синонимы): «кот» → коты, кошка, но не «который»;</li>
* <li>последнее слово как префикс — поиск по мере ввода: «кош» → «кошка».
* Только если первый этап пуст: иначе «кот:*» подтянул бы «который».
* Сначала префикс ищется только в заголовках: заголовок говорит, что
* потеряли, а в описании полно случайных слов — «барс» должен найти
* «Потеряна барсетка», а не кота, который «откликается на Барсик».
* Описания подключаются, только если в заголовках ничего нет;</li>
* <li>опечатки: похожесть триграмм по заголовку («кошька» → «кошка»).</li>
* </ol>
* Этап выбирается по наличию результатов вообще, а не на странице, поэтому
* все страницы одного запроса берутся из одного этапа — пагинация не скачет.
*/
@Slf4j
@Service
public class PostSearchService {
/** Длиннее этого ввод обрезаем — защищает БД от гигантских запросов. */
static final int MAX_QUERY_LENGTH = 200;
private static final Pattern HAS_WORD = Pattern.compile("[\\p{L}\\p{N}]");
private static final Pattern PLAIN_WORD = Pattern.compile("[\\p{L}\\p{N}]+");
enum Stage { FULL_TEXT, TITLE_PREFIX, PREFIX, TYPO, NONE }
private final PostSearchRepository repository;
private final SearchProperties properties;
private volatile SynonymExpander synonyms;
public PostSearchService(PostSearchRepository repository, SearchProperties properties) {
this.repository = repository;
this.properties = properties;
}
/** Есть ли в строке, что искать (хоть одна буква или цифра). */
public static boolean hasSearchText(String text) {
return text != null && HAS_WORD.matcher(text).find();
}
/** Страница id объявлений в порядке релевантности. */
@Transactional(readOnly = true)
public Page<Long> search(String rawText, PostFeedFilter filter, Collection<PostStatus> statuses,
Pageable pageable) {
String text = normalize(rawText);
long offset = pageable.getOffset();
int limit = pageable.getPageSize();
String lastWord = lastPlainWord(text);
String rest = lastWord == null ? "" : text.substring(0, text.length() - lastWord.length()).trim();
PostSearchRepository.ParsedQuery parsed = repository.parse(text, rest, lastWord);
// 1. Полнотекстовый поиск с синонимами
String fullQuery = expander().expand(parsed.full());
if (!fullQuery.isBlank()) {
long total = repository.countFullText(fullQuery, statuses, filter);
if (total > 0) {
return page(Stage.FULL_TEXT, text, repository.findFullText(fullQuery, statuses, filter, offset, limit),
pageable, total);
}
}
// 2. Последнее слово как начало слова — поиск по мере ввода: сначала в заголовках, потом везде
if (!parsed.prefix().isBlank()) {
String restQuery = expander().expand(parsed.rest());
Page<Long> byTitle = prefixStage(Stage.TITLE_PREFIX, text, restQuery, parsed.titlePrefix(), statuses,
filter, pageable);
if (byTitle != null) {
return byTitle;
}
Page<Long> anywhere = prefixStage(Stage.PREFIX, text, restQuery, parsed.prefix(), statuses, filter,
pageable);
if (anywhere != null) {
return anywhere;
}
}
// 3. Опечатки — похожесть по заголовку
repository.setTypoThreshold(properties.getTypoThreshold());
long total = repository.countTypo(text, statuses, filter);
if (total > 0) {
return page(Stage.TYPO, text, repository.findTypo(text, statuses, filter, offset, limit), pageable, total);
}
return page(Stage.NONE, text, List.of(), pageable, 0);
}
/** Страница этапа с префиксом или null, если этап ничего не нашёл. */
private Page<Long> prefixStage(Stage stage, String text, String restQuery, String prefix,
Collection<PostStatus> statuses, PostFeedFilter filter, Pageable pageable) {
String query = restQuery.isBlank() ? prefix : "( " + restQuery + " ) & " + prefix;
long total = repository.countFullText(query, statuses, filter);
if (total == 0) {
return null;
}
return page(stage, text, repository.findFullText(query, statuses, filter, pageable.getOffset(),
pageable.getPageSize()), pageable, total);
}
static String normalize(String text) {
String collapsed = text.strip().replaceAll("\\s+", " ");
return collapsed.length() > MAX_QUERY_LENGTH ? collapsed.substring(0, MAX_QUERY_LENGTH) : collapsed;
}
/**
* Последнее слово, если его можно искать как префикс: обычное слово
* (не в кавычках, не минус-слово, не «or») не короче minPrefixLength.
*/
String lastPlainWord(String text) {
// Нечётное число кавычек — пользователь ещё печатает фразу в кавычках
if (text.chars().filter(c -> c == '"').count() % 2 != 0) {
return null;
}
int space = text.lastIndexOf(' ');
String last = text.substring(space + 1);
if (!PLAIN_WORD.matcher(last).matches()
|| last.length() < properties.getMinPrefixLength()
|| last.equalsIgnoreCase("or")) {
return null;
}
return last;
}
private Page<Long> page(Stage stage, String text, List<Long> ids, Pageable pageable, long total) {
log.debug("Post search '{}': stage={}, total={}", text, stage, total);
return new PageImpl<>(ids, pageable, total);
}
/** Синонимы приводятся к лексемам через стеммер Postgres — один раз, при первом поиске. */
private SynonymExpander expander() {
SynonymExpander current = synonyms;
if (current == null) {
synchronized (this) {
current = synonyms;
if (current == null) {
current = new SynonymExpander(properties.getSynonyms(), repository::lexemes);
synonyms = current;
}
}
}
return current;
}
}

View File

@@ -0,0 +1,59 @@
package com.krylov.refound.search;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Настройки поиска по объявлениям (prefix "search" в application.yaml).
*/
@Getter
@Setter
@ToString
@ConfigurationProperties(prefix = "search")
public class SearchProperties {
/**
* Группы синонимов: слово из любой группы ищется вместе со всеми словами
* этой группы («кот» → кот | кошка | котёнок). Слова можно писать в любой
* форме — к основе их приводит тот же русский стеммер Postgres, что и при
* индексации. Добавить синоним = дописать слово сюда и перезапустить сервис.
*/
private List<List<String>> synonyms = new ArrayList<>();
/**
* Порог pg_trgm word_similarity для поиска с опечатками (0..1). Ниже —
* больше «похожих» результатов, но и больше мусора.
*/
private double typoThreshold = 0.3;
/**
* Минимальная длина последнего слова, чтобы искать его как начало слова
* («кош» → «кошка»). Совсем короткие префиксы находят почти всё подряд.
*/
private int minPrefixLength = 3;
/** Подсказки при вводе (SearchSuggestService). */
private Suggest suggest = new Suggest();
@Getter
@Setter
@ToString
public static class Suggest {
/** Сколько подсказок отдавать. */
private int limit = 8;
/** С какой длины слова начинать подсказывать. */
private int minLength = 2;
/** С какой длины слова искать похожие, если по началу ничего нет. */
private int typoMinLength = 4;
/** Порог pg_trgm word_similarity для подсказок с опечаткой (0..1). */
private double typoThreshold = 0.5;
}
}

View File

@@ -0,0 +1,126 @@
package com.krylov.refound.search;
import com.krylov.refound.util.PostVisibility;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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;
/**
* Подсказки при вводе поиска: дописывает последнее слово по словарю
* search_words («барс» → «барсетка», «барсик»). В словаре только слова из
* заголовков текущих объявлений, поэтому любая подсказка что-то находит.
*
* <p>Порядок подсказок — по популярности: в скольких объявлениях есть слово
* и как часто его ищут. Поиски копятся в памяти и пишутся в БД раз в
* flush-interval, чтобы не делать запись на каждое нажатие клавиши.
*/
@Slf4j
@Service
public class SearchSuggestService {
private static final Pattern WORD = Pattern.compile("[\\p{L}\\p{N}]+");
/** Предел буфера счётчиков: мусорный ввод не должен съесть память между сбросами. */
static final int MAX_PENDING_WORDS = 10_000;
private final SearchWordRepository repository;
private final SearchProperties.Suggest properties;
private volatile ConcurrentHashMap<String, LongAdder> pending = new ConcurrentHashMap<>();
public SearchSuggestService(SearchWordRepository repository, SearchProperties properties) {
this.repository = repository;
this.properties = properties.getSuggest();
}
/** Подсказки для последнего слова ввода. Пустой список, если слово слишком короткое. */
@Transactional(readOnly = true)
public List<String> suggest(String text) {
String last = lastWord(text);
if (last == null || last.length() < properties.getMinLength()) {
return List.of();
}
// +1: само введённое слово тоже может прийти, но его не подсказываем
Map<String, String> completions = repository.findByPrefix(last, properties.getLimit() + 1);
boolean exactWord = completions.remove(last) != null;
if (completions.isEmpty() && !exactWord && last.length() >= properties.getTypoMinLength()) {
return repository.findSimilar(last, properties.getTypoThreshold(), properties.getLimit());
}
return completions.values().stream().limit(properties.getLimit()).toList();
}
/**
* Учитывает поиск, который что-то нашёл. Считаются все слова запроса, но в
* БД попадут только те, что есть в словаре, — опечатки и обрывки слов отсеются.
*/
public void recordSearch(String text) {
if (text == null) {
return;
}
Map<String, LongAdder> buffer = pending;
Matcher m = WORD.matcher(text);
while (m.find()) {
String word = normalize(m.group());
if (word.length() < 3) {
continue;
}
LongAdder counter = buffer.get(word);
if (counter == null) {
if (buffer.size() >= MAX_PENDING_WORDS) {
continue;
}
counter = buffer.computeIfAbsent(word, w -> new LongAdder());
}
counter.increment();
}
}
@Scheduled(fixedDelayString = "${search.suggest.flush-interval:PT1M}")
public void flushSearchCounts() {
ConcurrentHashMap<String, LongAdder> buffer = pending;
if (buffer.isEmpty()) {
return;
}
pending = new ConcurrentHashMap<>();
Map<String, Long> counts = new HashMap<>();
buffer.forEach((word, counter) -> counts.put(word, counter.sum()));
repository.addSearchCounts(counts);
log.debug("Search suggest: flushed {} searched words", counts.size());
}
@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();
repository.rebuild(PostVisibility.FEED_VISIBLE_STATUSES);
log.debug("Search suggest: dictionary rebuilt in {} ms", System.currentTimeMillis() - start);
}
/** Последнее слово, если ввод им заканчивается (после пробела подсказывать нечего). */
static String lastWord(String text) {
if (text == null || text.isEmpty() || !Character.isLetterOrDigit(text.charAt(text.length() - 1))) {
return null;
}
Matcher m = WORD.matcher(text);
String last = null;
while (m.find()) {
last = m.group();
}
return last == null ? null : normalize(last);
}
static String normalize(String word) {
return word.toLowerCase(Locale.ROOT).replace('ё', 'е');
}
}

View File

@@ -0,0 +1,93 @@
package com.krylov.refound.search;
import com.krylov.refound.enums.PostStatus;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
/**
* Словарь подсказок search_words (changelog 020).
*/
@Repository
@RequiredArgsConstructor
public class SearchWordRepository {
private final NamedParameterJdbcTemplate jdbc;
/**
* Пересобирает doc_count по заголовкам видимых объявлений. Строки с
* неизменившимися значениями не трогаем, исчезнувшие слова обнуляем,
* а слова без объявлений и без поисков удаляем. search_count не меняется.
* Стоп-слова («для», «без») отсекает русский словарь Postgres.
*/
public void rebuild(Collection<PostStatus> statuses) {
MapSqlParameterSource params = new MapSqlParameterSource("statuses",
statuses.stream().map(Enum::name).toList());
jdbc.update("""
with fresh as (
select translate(w, 'ё', 'е') as norm, max(w) as word, count(distinct p.id) as cnt
from posts p, regexp_split_to_table(lower(p.title), '[^а-яёa-z0-9]+') w
where p.status in (:statuses)
and length(w) >= 3
and w !~ '^[0-9]+$'
and length(to_tsvector('russian', w)) > 0
group by 1
), upserted as (
insert into search_words (norm, word, doc_count)
select norm, word, cnt from fresh
on conflict (norm) do update set word = excluded.word, doc_count = excluded.doc_count
where (search_words.word, search_words.doc_count) is distinct from (excluded.word, excluded.doc_count)
)
update search_words set doc_count = 0
where doc_count > 0 and norm not in (select norm from fresh)
""", params);
jdbc.update("delete from search_words where doc_count = 0 and search_count = 0", Map.of());
}
/** Прибавляет счётчики поисков. Слова, которых нет в словаре, игнорируются. */
public void addSearchCounts(Map<String, Long> counts) {
SqlParameterSource[] batch = counts.entrySet().stream()
.map(e -> new MapSqlParameterSource().addValue("norm", e.getKey()).addValue("count", e.getValue()))
.toArray(SqlParameterSource[]::new);
jdbc.batchUpdate("update search_words set search_count = search_count + :count where norm = :norm", batch);
}
/**
* Слова (norm → word), начинающиеся с prefix, включая само слово prefix, если оно есть
* (prefix уже нормализован: нижний регистр, ё → е, только буквы и цифры).
* Популярность — и сколько объявлений со словом есть, и как часто его ищут;
* логарифм не даёт накрутить слово одними поисками.
*/
public Map<String, String> findByPrefix(String prefix, int limit) {
Map<String, String> words = new LinkedHashMap<>();
jdbc.query("""
select norm, word from search_words
where doc_count > 0 and norm like :prefix || '%'
order by ln(1 + doc_count) + ln(1 + search_count) desc, norm
limit :limit
""", new MapSqlParameterSource().addValue("prefix", prefix).addValue("limit", limit),
rs -> {
words.put(rs.getString("norm"), rs.getString("word"));
});
return words;
}
/** Похожие слова для ввода с опечаткой («барст» → «барсетка»). Словарь небольшой — без индекса. */
public List<String> findSimilar(String text, double threshold, int limit) {
return jdbc.queryForList("""
select word from search_words
where doc_count > 0 and word_similarity(:text, norm) >= :threshold
order by word_similarity(:text, norm) desc, ln(1 + doc_count) + ln(1 + search_count) desc, norm
limit :limit
""", new MapSqlParameterSource()
.addValue("text", text)
.addValue("threshold", threshold)
.addValue("limit", limit), String.class);
}
}

View File

@@ -0,0 +1,85 @@
package com.krylov.refound.search;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Расширяет tsquery синонимами: лексема 'кот' превращается в
* ( 'кот' | 'кошк' | 'котенок' ).
*
* <p>Работает с текстовым видом tsquery, который вернул websearch_to_tsquery,
* поэтому кавычки, минус-слова и OR из пользовательского ввода сохраняются:
* «-собака» исключит и собак, и щенков. Лексемы с префиксом или весом
* ('кош':*) не трогаем.
*
* <p>Почему синонимы на стороне Java, а не thesaurus-словарь Postgres:
* словарь — это файл в каталоге tsearch_data внутри контейнера БД, своя
* text search configuration и пересборка search_vector при каждой правке.
* Здесь синонимы — список в application.yaml, индекс от них не зависит.
*/
public class SynonymExpander {
// 'лексема' с необязательным суффиксом :* / :A и т.п.; '' внутри — экранированная кавычка
private static final Pattern LEXEME = Pattern.compile("'((?:[^']|'')*)'(:[*A-Da-d]+)?");
/** лексема → все лексемы её группы (в стабильном порядке) */
private final Map<String, List<String>> groupByLexeme;
/**
* @param groups группы синонимов в виде слов
* @param toLexemes слово → его лексемы по стеммеру Postgres
*/
public SynonymExpander(List<List<String>> groups, Function<String, List<String>> toLexemes) {
Map<String, List<String>> map = new HashMap<>();
for (List<String> group : groups) {
Set<String> lexemes = new LinkedHashSet<>();
for (String word : group) {
List<String> wordLexemes = toLexemes.apply(word);
// Синоним из нескольких слов одной лексемой не заменить — пропускаем
if (wordLexemes.size() == 1) {
lexemes.add(wordLexemes.get(0));
}
}
if (lexemes.size() < 2) {
continue;
}
List<String> alternatives = List.copyOf(lexemes);
for (String lexeme : lexemes) {
map.merge(lexeme, alternatives, (a, b) -> List.copyOf(new LinkedHashSet<>(
Stream.concat(a.stream(), b.stream()).toList())));
}
}
this.groupByLexeme = Map.copyOf(map);
}
/** Подставляет группы синонимов в текст tsquery. Пустую строку возвращает как есть. */
public String expand(String tsquery) {
if (tsquery == null || tsquery.isBlank() || groupByLexeme.isEmpty()) {
return tsquery;
}
Matcher m = LEXEME.matcher(tsquery);
StringBuilder out = new StringBuilder();
while (m.find()) {
String lexeme = m.group(1).replace("''", "'");
List<String> group = m.group(2) == null ? groupByLexeme.get(lexeme) : null;
String replacement = group == null
? m.group()
: group.stream().map(SynonymExpander::quote).collect(Collectors.joining(" | ", "( ", " )"));
m.appendReplacement(out, Matcher.quoteReplacement(replacement));
}
m.appendTail(out);
return out.toString();
}
private static String quote(String lexeme) {
return "'" + lexeme.replace("'", "''") + "'";
}
}

View File

@@ -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);

View File

@@ -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) {

View File

@@ -49,11 +49,13 @@ 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/users/*/posts").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
.requestMatchers("/files/**", "/uploads/**").permitAll()
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
// изменяющие операции — только для авторизованных
@@ -69,7 +71,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()
@@ -115,6 +116,10 @@ public class SecurityConfig {
config.setAllowedOrigins(origins);
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
// Без expose браузер прячет эти заголовки от кросс-доменного фронта:
// Retry-After нужен для сообщения «повторите через N мин» на 429,
// Location — ссылка на созданный ресурс (201 у POST /api/v1/posts)
config.setExposedHeaders(List.of("Retry-After", "Location"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);

View File

@@ -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(),

View File

@@ -1,48 +1,96 @@
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;
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;
import com.krylov.refound.repository.MessageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.repository.UserRepository;
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.messaging.simp.SimpMessagingTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatService {
/** Максимальная длина сообщения в символах. */
public static final int MAX_MESSAGE_LENGTH = 4000;
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;
// Создать чат с пользователем (или вернуть существующий)
/**
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
*/
@Transactional(readOnly = true)
public Optional<ChatDto> findChat(Long currentUserId, Long otherUserId, Long postId) {
Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId);
return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream()
.findFirst()
.map(chat -> toDto(chat, currentUserId));
}
/**
* Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт
* чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений.
*/
@Transactional
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) {
public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
validateContent(content);
if (currentUserId.equals(otherUserId)) {
throw new IllegalArgumentException("Нельзя создать чат с самим собой");
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
}
if (!userRepository.existsById(otherUserId)) {
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
}
if (postId != null) {
// Иначе клиент мог прикрепить к чату любое чужое объявление
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
Long ownerId = post.getUser().getId();
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
}
}
Long userId1 = Math.min(currentUserId, otherUserId);
Long userId2 = Math.max(currentUserId, otherUserId);
Chat chat = chatRepository.findByUsers(userId1, userId2).orElseGet(() -> {
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
Chat newChat = new Chat();
newChat.setUserOneId(userId1);
newChat.setUserTwoId(userId2);
@@ -50,14 +98,25 @@ public class ChatService {
return chatRepository.save(newChat);
});
saveAndBroadcast(chat, currentUserId, content);
return toDto(chat, currentUserId);
}
// Все чаты пользователя
// Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
@Transactional(readOnly = true)
public List<ChatDto> getUserChats(Long userId) {
return chatRepository.findAllByUserId(userId).stream()
.map(c -> toDto(c, userId))
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
}
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)
.collect(Collectors.toList());
}
@@ -73,9 +132,26 @@ public class ChatService {
// Отправка сообщения (вызывается из WebSocket контроллера)
@Transactional
public void sendMessage(Long senderId, Long chatId, String content) {
validateContent(content);
Chat chat = getChatOrThrow(chatId);
checkParticipant(chat, senderId);
saveAndBroadcast(chat, senderId, content);
}
private void validateContent(String content) {
if (content == null || content.isBlank()) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST);
}
if (content.length() > MAX_MESSAGE_LENGTH) {
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
}
}
private void saveAndBroadcast(Chat chat, Long senderId, String content) {
Long chatId = chat.getId();
Message message = new Message();
message.setChatId(chatId);
message.setSenderId(senderId);
@@ -84,8 +160,6 @@ public class ChatService {
MessageDto dto = toMessageDto(message);
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
// Уведомляем получателя об непрочитанных
Long recipientId = chat.getUserOneId().equals(senderId)
? chat.getUserTwoId()
@@ -93,11 +167,28 @@ public class ChatService {
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
messagingTemplate.convertAndSend(
"/topic/user/" + recipientId + "/unread",
Map.of("chatId", chatId, "unreadCount", unreadCount)
);
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
// историю, мог не увидеть ещё не закоммиченное сообщение
afterCommit(() -> {
messaging.convertAndSend("/topic/chat/" + chatId, dto);
messaging.convertAndSend(
"/topic/user/" + recipientId + "/unread",
Map.of("chatId", chatId, "unreadCount", unreadCount)
);
});
}
private static void afterCommit(Runnable action) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
action.run();
}
});
} else {
action.run();
}
}
@Transactional
@@ -128,50 +219,76 @@ public class ChatService {
}
private Chat getChatOrThrow(Long chatId) {
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден"));
return chatRepository.findById(chatId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
}
private void checkParticipant(Chat chat, Long userId) {
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
throw new SecurityException("Вы не участник этого чата");
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
}
}
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) {

View File

@@ -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());
}
}

View File

@@ -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;
@@ -12,6 +12,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
@@ -38,27 +39,47 @@ import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
@Service
@Slf4j
@RequiredArgsConstructor
public class FileStorageService {
private final S3Client s3Client;
private final S3Presigner s3Presigner;
private final MinioProperties properties;
private final StringRedisTemplate redisTemplate;
private final ImageOptimizer imageOptimizer;
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of("image/jpeg", "image/png", "image/webp");
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:";
/**
* Presigned-ссылка для показа картинок. Ссылка живёт PRESIGNED_URL_TTL, но
* отдаём одну и ту же ссылку PRESIGNED_URL_CACHE_TTL: пока URL не меняется,
* браузер берёт картинку из своего кэша, а не скачивает заново при каждом
* открытии ленты. Запас (24ч - 12ч) покрывает время, пока ссылка лежит в
* кэше браузера (см. FileStorageController#REDIRECT_CACHE_MAX_AGE).
*/
public static final Duration PRESIGNED_URL_TTL = Duration.ofHours(24);
private static final Duration PRESIGNED_URL_CACHE_TTL = Duration.ofHours(12);
private static final String PRESIGNED_KEY_PREFIX = "files:presigned:";
/**
* Файлы неизменяемы (имя — UUID), поэтому браузеру можно хранить их долго.
* MinIO отдаёт этот заголовок по параметру response-cache-control в ссылке.
*/
private static final String IMAGE_CACHE_CONTROL = "private, max-age=31536000, immutable";
/**
* Загружает файл в MinIO в корень бакета.
*/
@@ -75,24 +96,39 @@ public class FileStorageService {
// validateFile гарантирует, что originalFilename не null и не blank
String originalFilename = file.getOriginalFilename();
String extension = extractExtension(originalFilename);
String prefix = (folder != null && !folder.isBlank()) ? folder.replaceAll("/+$", "") + "/" : "";
String objectName = prefix + UUID.randomUUID() + extension;
log.info("Загрузка файла '{}'. Новое имя: {}", originalFilename, objectName);
try {
byte[] content = file.getBytes();
// Тип и расширение берём из содержимого файла, а не из запроса клиента
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()) {
content = optimized.get().content();
contentType = optimized.get().contentType();
extension = optimized.get().extension();
}
String objectName = prefix + UUID.randomUUID() + extension;
log.info("Загрузка файла '{}'. Новое имя: {}", originalFilename, objectName);
Map<String, String> metadata = new HashMap<>();
metadata.put(ORIGINAL_FILENAME_METADATA_KEY, URLEncoder.encode(originalFilename, StandardCharsets.UTF_8));
PutObjectRequest request = PutObjectRequest.builder()
.bucket(properties.bucket())
.key(objectName)
.contentType(file.getContentType())
.contentType(contentType)
.metadata(metadata)
.build();
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
s3Client.putObject(request, RequestBody.fromBytes(content));
registerOwner(objectName);
log.info("Файл '{}' успешно загружен.", objectName);
return objectName;
@@ -119,6 +155,11 @@ public class FileStorageService {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, disposition + "; filename*=UTF-8''" + encodedFilename);
if (file.contentType().startsWith("image/")) {
// Без явного заголовка Spring Security ставит no-store, и при каждом
// открытии приложения все картинки ленты скачиваются заново.
headers.add(HttpHeaders.CACHE_CONTROL, IMAGE_CACHE_CONTROL);
}
return ResponseEntity.ok()
.headers(headers)
@@ -126,6 +167,64 @@ public class FileStorageService {
.body(file.content());
}
/**
* Генерирует presigned URL для скачивания файла напрямую из MinIO/S3.
* Браузер будет загружать картинку по этому URL, минуя backend (меньше нагрузки).
*/
public String generatePresignedDownloadUrl(String objectName, Duration ttl) {
try {
GetObjectRequest getRequest = GetObjectRequest.builder()
.bucket(properties.bucket())
.key(objectName)
.responseCacheControl(IMAGE_CACHE_CONTROL)
.build();
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
.signatureDuration(ttl)
.getObjectRequest(getRequest)
.build();
String url = s3Presigner.presignGetObject(presignRequest).url().toString();
log.debug("Сгенерирован presigned URL для файла '{}', TTL={}", objectName, ttl);
return url;
} catch (S3Exception | SdkClientException e) {
log.error("Ошибка при генерации presigned URL для файла '{}': {}", objectName, e.getMessage(), e);
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при формировании ссылки на файл.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Генерирует presigned URL со стандартным TTL.
*/
public String generatePresignedDownloadUrl(String objectName) {
return generatePresignedDownloadUrl(objectName, PRESIGNED_URL_TTL);
}
/**
* Presigned URL со стандартным TTL, одинаковый для повторных запросов в
* течение PRESIGNED_URL_CACHE_TTL — чтобы браузер мог кэшировать картинку.
* Если Redis недоступен, просто генерируем новую ссылку.
*/
public String getCachedPresignedDownloadUrl(String objectName) {
String cacheKey = PRESIGNED_KEY_PREFIX + objectName;
try {
String cached = redisTemplate.opsForValue().get(cacheKey);
if (cached != null) {
return cached;
}
} catch (RuntimeException e) {
log.warn("Не удалось прочитать presigned URL из кэша для '{}': {}", objectName, e.getMessage());
}
String url = generatePresignedDownloadUrl(objectName, PRESIGNED_URL_TTL);
try {
redisTemplate.opsForValue().set(cacheKey, url, PRESIGNED_URL_CACHE_TTL);
} catch (RuntimeException e) {
log.warn("Не удалось сохранить presigned URL в кэш для '{}': {}", objectName, e.getMessage());
}
return url;
}
/**
* Скачивает файл из MinIO без HTTP-обёртки — оригинальное имя, content-type и байты.
* Используется там, где нет HTTP-контекста (например, в PostModerationScheduler,
@@ -150,6 +249,7 @@ public class FileStorageService {
s3Client.deleteObject(request);
forgetOwner(objectName);
forgetPresignedUrl(objectName);
log.info("Файл '{}' успешно удален.", objectName);
} catch (S3Exception | SdkClientException e) {
log.error("Ошибка при удалении файла '{}': {}", objectName, e.getMessage(), e);
@@ -174,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;
}
@@ -214,6 +314,14 @@ public class FileStorageService {
}
}
private void forgetPresignedUrl(String objectName) {
try {
redisTemplate.delete(PRESIGNED_KEY_PREFIX + objectName);
} catch (RuntimeException e) {
log.warn("Не удалось удалить presigned URL из кэша для '{}': {}", objectName, e.getMessage());
}
}
private String readOwner(String objectName) {
try {
return redisTemplate.opsForValue().get(OWNER_KEY_PREFIX + objectName);
@@ -297,10 +405,4 @@ public class FileStorageService {
}
}
private String extractExtension(String originalFilename) {
if (originalFilename != null && originalFilename.contains(".")) {
return originalFilename.substring(originalFilename.lastIndexOf("."));
}
return "";
}
}

View File

@@ -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);
}
/**

View File

@@ -0,0 +1,147 @@
package com.krylov.refound.service;
import jakarta.annotation.PostConstruct;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Optional;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Component;
/**
* Готовит загруженные фото к показу в ленте. Снимки с телефона (особенно iPhone)
* весят 3–10 МБ при 12–24 Мп, и при первом открытии приложения браузер долго
* скачивает и декодирует такие оригиналы. Здесь картинка уменьшается до
* MAX_DIMENSION по большей стороне, поворачивается по EXIF (сами EXIF, включая
* геометку, при этом отбрасываются) и пережимается в progressive JPEG.
*/
@Slf4j
@Component
public class ImageOptimizer {
/** Больше на экране телефона/ноутбука не нужно даже с retina. */
static final int MAX_DIMENSION = 1600;
/** Такие файлы уже достаточно лёгкие — пережимать их нет смысла. */
static final long SKIP_BELOW_BYTES = 300 * 1024;
private static final float JPEG_QUALITY = 0.82f;
public record OptimizedImage(byte[] content, String contentType, String extension) {
}
@PostConstruct
void registerImageIoPlugins() {
// Плагины TwelveMonkeys (WebP, CMYK-JPEG) лежат внутри fat jar —
// явная регистрация гарантирует, что ImageIO их увидит.
ImageIO.scanForPlugins();
}
/**
* Возвращает облегчённую версию картинки или пустой Optional, если оригинал
* стоит сохранить как есть: он и так маленький, не читается или пережатая
* версия получилась не легче.
*/
public Optional<OptimizedImage> optimize(byte[] source, String contentType) {
if (source.length <= SKIP_BELOW_BYTES) {
return Optional.empty();
}
try {
Thumbnails.Builder<?> builder = Thumbnails.of(new ByteArrayInputStream(source));
// size() увеличивает маленькие картинки, поэтому для них только пережимаем.
builder = maxSide(source) > MAX_DIMENSION
? builder.size(MAX_DIMENSION, MAX_DIMENSION)
: builder.scale(1.0);
BufferedImage image = builder.asBufferedImage();
boolean keepAlpha = image.getColorModel().hasAlpha() && !"image/jpeg".equals(contentType);
OptimizedImage optimized = keepAlpha
? new OptimizedImage(writePng(image), "image/png", ".png")
: new OptimizedImage(writeJpeg(toRgb(image)), "image/jpeg", ".jpg");
if (optimized.content().length >= source.length) {
return Optional.empty();
}
log.info("Картинка сжата: {} КБ -> {} КБ ({}x{})",
source.length / 1024, optimized.content().length / 1024, image.getWidth(), image.getHeight());
return Optional.of(optimized);
} catch (IOException | RuntimeException e) {
log.warn("Не удалось оптимизировать картинку ({}), сохраняем оригинал: {}", contentType, e.getMessage());
return Optional.empty();
}
}
/** Размер из заголовка файла, без декодирования пикселей. */
private static int maxSide(byte[] source) throws IOException {
try (ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(source))) {
Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if (!readers.hasNext()) {
throw new IOException("неизвестный формат");
}
ImageReader reader = readers.next();
try {
reader.setInput(in);
return Math.max(reader.getWidth(0), reader.getHeight(0));
} finally {
reader.dispose();
}
}
}
private static BufferedImage toRgb(BufferedImage image) {
if (image.getType() == BufferedImage.TYPE_INT_RGB) {
return image;
}
BufferedImage rgb = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = rgb.createGraphics();
try {
// Прозрачные места (PNG/WebP без альфы на выходе) заливаем белым, а не чёрным.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(image, 0, 0, null);
} finally {
g.dispose();
}
return rgb;
}
private static byte[] writeJpeg(BufferedImage image) throws IOException {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
if (!writers.hasNext()) {
throw new IOException("нет JPEG-кодировщика");
}
ImageWriter writer = writers.next();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(JPEG_QUALITY);
// Progressive: браузер сразу рисует размытый кадр и дорисовывает детали.
if (param.canWriteProgressive()) {
param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
}
writer.write(null, new IIOImage(image, null, null), param);
} finally {
writer.dispose();
}
return out.toByteArray();
}
private static byte[] writePng(BufferedImage image) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (!ImageIO.write(image, "png", out)) {
throw new IOException("нет PNG-кодировщика");
}
return out.toByteArray();
}
}

View File

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

View File

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

View File

@@ -1,76 +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;
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);
} 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;
}
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());
}
}
}

View File

@@ -17,29 +17,40 @@ import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.PostSearchService;
import com.krylov.refound.search.SearchSuggestService;
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 java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import com.krylov.refound.util.TimeZoneContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Set;
@Service
@RequiredArgsConstructor
@Slf4j
@@ -58,42 +69,81 @@ public class PostService {
private final ObjectMapper objectMapper;
private final PostCacheService postCacheService;
private final PostCacheKeyGenerator postCacheKeyGenerator;
private final MapCacheService mapCacheService;
@Transactional
public PostRequest create(PostRequest request, List<MultipartFile> images) {
private final PostDeletionService postDeletionService;
private final TransactionTemplate transactionTemplate;
private final PostSearchService postSearchService;
private final SearchSuggestService searchSuggestService;
/**
* Создание объявления. Сетевые вызовы — геокодер и загрузка фото в MinIO — идут
* до транзакции: соединение с БД не держится, пока ждём внешние сервисы.
* Если транзакция не прошла, загруженные файлы удаляются.
*/
public PostResponse 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(LocalDateTime.now());
post.setStatus(PostStatus.MODERATION);
post.setUser(currentUser);
post.setIsReward(request.getReward());
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);
PostResponse created;
try {
created = transactionTemplate.execute(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();
// Ответ собираем в транзакции: картинки и автор — ленивые связи
return toResponse(post, true);
});
} 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;
return created;
}
public Page<PostResponse> getFeed(String search, Pageable pageable) {
/**
* Публичная лента: фильтры по типу, категориям и городам + поиск по тексту.
* С текстом поиска — полнотекстовый поиск с ранжированием по релевантности
* (сортировка из pageable игнорируется) и без кэша: запросы почти всегда
* уникальны, а GIN-индекс отвечает быстро. Без текста — обычная лента,
* кэшируется в Redis с учётом фильтров.
*/
public Page<PostResponse> getFeed(String search, PostFeedFilter filter, Pageable pageable) {
PostFeedFilter feedFilter = filter == null ? PostFeedFilter.NONE : filter;
if (PostSearchService.hasSearchText(search)) {
Page<Long> ids = postSearchService.search(search, feedFilter, FEED_VISIBLE_STATUSES, pageable);
// Статистика для подсказок: только удачные поиски и только первая страница —
// подгрузка следующих страниц того же запроса не делает слово популярнее
if (pageable.getPageNumber() == 0 && ids.getTotalElements() > 0) {
searchSuggestService.recordSearch(search);
}
return new PageImpl<>(loadInOrder(ids.getContent()), ids.getPageable(), ids.getTotalElements());
}
// Без уникального ключа в сортировке порядок постов с одинаковым createdAt
// недетерминирован, и при LIMIT/OFFSET посты дублируются или пропадают между страницами
if (pageable.getSort().getOrderFor("id") == null) {
pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(),
pageable.getSort().and(Sort.by(Sort.Direction.DESC, "id")));
}
// Ключ содержит версию ленты, она читается до запроса в БД
String cacheKey = postCacheKeyGenerator.feedKey(search, pageable);
String cacheKey = postCacheKeyGenerator.feedKey(feedFilter, pageable);
CachedPostPage cached = postCacheService.getFeed(cacheKey);
@@ -104,7 +154,7 @@ public class PostService {
log.debug("Feed cache MISS: {}", cacheKey);
Specification<Post> spec = PostSpecification.hasSearch(search)
Specification<Post> spec = PostSpecification.feedFilter(feedFilter)
.and((root, query, cb) ->
root.get("status").in(FEED_VISIBLE_STATUSES)
);
@@ -125,6 +175,21 @@ public class PostService {
return responsePage;
}
/** Загружает посты по id и отдаёт их в том же порядке (порядок релевантности поиска). */
private List<PostResponse> loadInOrder(List<Long> ids) {
if (ids.isEmpty()) {
return List.of();
}
Map<Long, Post> byId = postRepository.findAllById(ids).stream()
.collect(Collectors.toMap(Post::getId, Function.identity()));
return ids.stream()
.map(byId::get)
// пост могли удалить между двумя запросами — просто пропускаем
.filter(Objects::nonNull)
.map(post -> toResponse(post, true))
.toList();
}
/**
* Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id,
* несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер,
@@ -132,6 +197,18 @@ public class PostService {
* Владелец видит все свои посты (включая MODERATION и REJECTED), остальные — только
* опубликованные (ACTIVE и CLOSED).
*/
/**
* Объявления пользователя постранично (GET /api/v1/users/{userId}/posts).
* Владелец видит все свои посты, остальные — только опубликованные.
*/
@Transactional(readOnly = true)
public Page<PostResponse> getPostsByUser(Long userId, Pageable pageable) {
Page<Post> posts = isCurrentUser(userId)
? postRepository.findByUserId(userId, pageable)
: postRepository.findByUserIdAndStatusIn(userId, FEED_VISIBLE_STATUSES, pageable);
return posts.map(post -> toResponse(post, false));
}
public List<PostResponse> getPostsByUserId(Long userId) {
boolean owner = isCurrentUser(userId);
@@ -149,12 +226,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) {
@@ -170,14 +244,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);
@@ -190,18 +275,13 @@ public class PostService {
post.setType(request.getType());
post.setIsReward(request.getReward());
post.setReward(request.getRewardText());
post.setAddress(normalizeAddress(request.getAddress()));
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();
@@ -211,28 +291,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
@@ -257,27 +329,24 @@ 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);
}
public List<PostResponse> searchByCity(String city) {
/**
* Устаревший поиск по подстроке города/района — тот же фильтр есть в ленте
* (GET /api/v1/posts?city=). Оставлен на переходный период, уже постранично.
*/
@Deprecated
@Transactional(readOnly = true)
public Page<PostResponse> searchByCity(String city, Pageable pageable) {
if (!StringUtils.hasText(city)) {
return List.of();
return Page.empty(pageable);
}
Specification<Post> spec = Specification.where(PostSpecification.cityOrDistrictLike(city))
.and((root, query, cb) -> root.get("status").in(FEED_VISIBLE_STATUSES));
List<Post> posts = postRepository.findAll(spec);
if (posts.isEmpty()) {
return List.of();
}
return posts.stream()
.map(post -> toResponse(post, true))
.toList();
return postRepository.findAll(spec, pageable).map(post -> toResponse(post, true));
}
public List<String> getCities() {
@@ -329,44 +398,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) {
@@ -401,4 +494,8 @@ public class PostService {
return toResponse(post, true);
}
}
private static String normalizeAddress(String address) {
return StringUtils.hasText(address) ? address.trim() : null;
}
}

View File

@@ -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]);
}
}
}

View File

@@ -4,12 +4,12 @@ import com.krylov.refound.dto.ReviewRequestDto;
import com.krylov.refound.dto.ReviewResponseDto;
import com.krylov.refound.entity.Review;
import com.krylov.refound.repository.ReviewRepository;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import com.krylov.refound.util.TimeZoneContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ReviewService {
@@ -28,7 +28,7 @@ public class ReviewService {
review.setAuthorName(username); // или firstName из User
review.setRating(request.getRating());
review.setText(request.getText());
review.setCreatedAt(LocalDateTime.now());
review.setCreatedAt(TimeZoneContext.now());
Review saved = reviewRepository.save(review);
return toResponse(saved);

Some files were not shown because too many files have changed in this diff Show More