Files
nahodka-back/src/main/java/com/krylov/refound/search/SearchSuggestService.java
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

127 lines
5.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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('ё', 'е');
}
}