mirror of
https://github.com/headporter81/specialsource-homepage-backend.git
synced 2026-12-06 07:41:09 +09:00
feat : 방명록(손님 쓰기·회원 삭제, IP당 30초 제한), 대화실(폴링, 메모리 200줄, 접속자 목록)
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 54s
SpecialSource Backend CI/CD / build-and-deploy (push) Successful in 54s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6e27519ff6
commit
926d78c094
8 files changed
+309
-1
No files matched your search
@@ -0,0 +1,97 @@
|
||||
package company.specialsource.controller;
|
||||
|
||||
import company.specialsource.config.ClientGuard;
|
||||
import company.specialsource.repository.UserRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 대화실: 브라우저가 2초마다 "after(마지막으로 받은 번호) 뒤의 새 말"을 물어보는 방식 (폴링).
|
||||
* 대화는 DB에 저장하지 않고 메모리에 최근 200줄만 → 서버가 꺼지면(매일 밤) 지워짐.
|
||||
* 접속자 = 최근 10초 안에 물어본 브라우저(client = 브라우저가 만든 임의 값).
|
||||
*/
|
||||
// ponytail: 폴링 방식. 접속자가 많아져 요청이 부담되면 WebSocket으로 바꾸기
|
||||
@RestController
|
||||
@RequestMapping("/api/chat")
|
||||
@RequiredArgsConstructor
|
||||
public class ChatController {
|
||||
|
||||
private static final int KEEP = 200;
|
||||
private static final Duration ONLINE = Duration.ofSeconds(10);
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public record ChatMessage(long id, String nickname, String message, boolean member, LocalDateTime at) {}
|
||||
|
||||
public record ChatRequest(String nickname, String message) {}
|
||||
|
||||
public record ChatResponse(List<ChatMessage> messages, List<String> online) {}
|
||||
|
||||
private record Seen(String nickname, Instant at) {}
|
||||
|
||||
private final Deque<ChatMessage> messages = new ArrayDeque<>();
|
||||
private final Map<String, Seen> clients = new ConcurrentHashMap<>();
|
||||
private long lastId = 0;
|
||||
|
||||
// after 없으면 최근 50줄. client·nick: 접속자 목록용
|
||||
@GetMapping
|
||||
public ChatResponse poll(@RequestParam(required = false) Long after, @RequestParam(required = false) String client,
|
||||
@RequestParam(required = false) String nick, Principal principal) {
|
||||
Instant now = Instant.now();
|
||||
if (client != null && client.length() <= 64) {
|
||||
String name = principal != null ? principal.getName() : clean(nick, 20);
|
||||
clients.put(client, new Seen(name.isEmpty() ? "손님" : name, now));
|
||||
}
|
||||
clients.values().removeIf(s -> s.at().plus(ONLINE).isBefore(now));
|
||||
List<String> online = clients.values().stream().map(Seen::nickname).distinct().sorted().toList();
|
||||
|
||||
synchronized (messages) {
|
||||
List<ChatMessage> out = after == null
|
||||
? messages.stream().skip(Math.max(0, messages.size() - 50)).toList()
|
||||
: messages.stream().filter(m -> m.id() > after).toList();
|
||||
return new ChatResponse(out, online);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> say(@RequestBody ChatRequest req, Principal principal, HttpServletRequest http) {
|
||||
String message = clean(req.message(), 200);
|
||||
if (message.isEmpty()) return bad("할 말을 1~200자로 써 주세요.");
|
||||
String nickname = principal != null ? principal.getName() : clean(req.nickname(), 20);
|
||||
if (nickname.isEmpty()) return bad("닉네임을 먼저 정해 주세요.");
|
||||
if (principal == null && userRepository.findByUsername(nickname).isPresent()) {
|
||||
return bad("회원 아이디와 같은 닉네임은 쓸 수 없어요.");
|
||||
}
|
||||
if (ClientGuard.tooSoon("chat:" + ClientGuard.ip(http), Duration.ofSeconds(1))) {
|
||||
return ResponseEntity.status(429).body(Map.of("error", "너무 빨라요. 1초에 한 번만 말할 수 있어요."));
|
||||
}
|
||||
synchronized (messages) {
|
||||
messages.addLast(new ChatMessage(++lastId, nickname, message, principal != null, LocalDateTime.now()));
|
||||
while (messages.size() > KEEP) messages.removeFirst();
|
||||
}
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
/** 앞뒤 공백 제거, 너무 길면 자름 (null이면 빈 문자열) */
|
||||
private static String clean(String s, int max) {
|
||||
if (s == null) return "";
|
||||
s = s.strip();
|
||||
return s.length() > max ? s.substring(0, max) : s;
|
||||
}
|
||||
|
||||
private static ResponseEntity<?> bad(String message) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", message));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user