Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor - 슬랙 메시지 형식 리팩토링으로 가독성 향상 #202

Merged
merged 12 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import sopt.org.hmh.domain.auth.dto.response.ReissueResponse;
import sopt.org.hmh.domain.challenge.dto.request.NewChallengeOrder;
import sopt.org.hmh.domain.challenge.service.ChallengeFacade;
import sopt.org.hmh.domain.slack.builder.NewUserSlackMessageBuilder;
import sopt.org.hmh.domain.slack.constant.SlackStatus;
import sopt.org.hmh.domain.user.domain.User;
import sopt.org.hmh.domain.auth.dto.request.SocialSignUpRequest;
import sopt.org.hmh.domain.auth.dto.response.LoginResponse;
Expand All @@ -27,6 +29,7 @@ public class AuthFacade {
private final ChallengeFacade challengeFacade;
private final TokenService tokenService;
private final UserService userService;
private final NewUserSlackMessageBuilder newUserSlackMessageBuilder;

@Transactional(readOnly = true)
public LoginResponse login(String socialAccessToken, SocialPlatform socialPlatform) {
Expand All @@ -41,7 +44,7 @@ public LoginResponse signup(SocialSignUpRequest request, String socialAccessToke
SocialPlatform socialPlatform = request.socialPlatform();
String socialId = this.getSocialIdBySocialAccessToken(socialPlatform, socialAccessToken);

User newUser = userService.addUser(socialPlatform, socialId, request.name(), os);
User newUser = userService.addUser(socialPlatform, socialId, request.name());
Long newUserId = newUser.getId();

userService.registerOnboardingInfo(request, newUserId);
Expand All @@ -51,6 +54,8 @@ public LoginResponse signup(SocialSignUpRequest request, String socialAccessToke
newUserId, os, timeZone
));

newUserSlackMessageBuilder.sendNotification(SlackStatus.NEW_USER_SIGNUP, request.name(), os);

return performLogin(newUser, socialAccessToken, socialPlatform);
}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/sopt/org/hmh/domain/slack/SlackSender.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ public class SlackSender {

private final Slack slackClient = Slack.getInstance();

public void sendSlackNotification(String webhookUrl, String title, Attachment attachment) {
public void sendSlackNotification(String webhookUrl, String mainText, Attachment attachment) {
try {
slackClient.send(webhookUrl, WebhookPayloads.payload(p -> p
.text(title)
.text("*" + mainText + "*")
.attachments(List.of(attachment))
));
} catch (IOException slackError) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package sopt.org.hmh.domain.slack.builder;

import com.slack.api.model.Attachment;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import sopt.org.hmh.domain.auth.exception.AuthError;
import sopt.org.hmh.domain.slack.SlackSender;
import sopt.org.hmh.domain.slack.constant.SlackStatus;
import sopt.org.hmh.global.auth.jwt.exception.JwtError;
import sopt.org.hmh.global.common.exception.base.ErrorBase;
import sopt.org.hmh.global.common.exception.base.ExceptionBase;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Component
@RequiredArgsConstructor
Expand All @@ -21,25 +29,46 @@ public class ErrorSlackMessageBuilder implements SlackMessageBuilder {

private final SlackSender slackSender;

public void sendNotification(SlackStatus status, Exception e, HttpServletRequest request) {
slackSender.sendSlackNotification(serverErrorWebUrl, status.getTitle(),
generateSlackAttachment(status, e, request));
private static final Set<String> EXCLUDED_ERROR_MESSAGES = Set.of(
JwtError.INVALID_ACCESS_TOKEN.getErrorMessage(),
JwtError.INVALID_SOCIAL_ACCESS_TOKEN.getErrorMessage(),
AuthError.NOT_SIGNUP_USER.getErrorMessage(),
AuthError.DUPLICATE_USER.getErrorMessage()
);

private boolean shouldSendNotification(ErrorBase e) {
return !EXCLUDED_ERROR_MESSAGES.contains(e.getErrorMessage());
}

public void sendNotification(SlackStatus status, Exception exception, HttpServletRequest request) {
if (exception instanceof ExceptionBase) {
ErrorBase error = ((ExceptionBase) exception).getError();
if (shouldSendNotification(error)) {
sendSlackNotification(status, error.getHttpStatus(), error.getErrorMessage(), request);
}
} else if (exception instanceof ServletException) {
sendSlackNotification(status, HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage(), request);
}
}

private void sendSlackNotification(SlackStatus status, HttpStatus statusCode, String errorMessage, HttpServletRequest request) {
slackSender.sendSlackNotification(serverErrorWebUrl,
status.getTitle() + " : " + statusCode,
generateSlackAttachment(status, errorMessage, request));
}

@Override
public Attachment generateSlackAttachment(SlackStatus status, Object... params) {
Exception e = (Exception) params[0];
String errorMessage = (String) params[0];
HttpServletRequest request = (HttpServletRequest) params[1];

String requestTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now());

return Attachment.builder()
.color(changeColorToHex(status.getColor()))
.title(requestTime + " 발생 오류 로그")
.text(requestTime + " 발생")
.fields(List.of(
generateSlackField("User Info", "- ID : " + request.getRemoteUser()),
generateSlackField("Request URL", "[" + request.getMethod() + "] " + request.getRequestURI()),
generateSlackField("Error Info", e.getMessage())))
generateSlackField("Error Message", errorMessage)))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class NewUserSlackMessageBuilder implements SlackMessageBuilder{
public void sendNotification(SlackStatus status, String userName, String os) {
slackSender.sendSlackNotification(
newUserWebUrl,
status.getTitle(),
status.getTitle() + " : 회원 수 " + userRepository.count() + "명",
generateSlackAttachment(status, userName, os));
}

Expand All @@ -34,10 +34,9 @@ public Attachment generateSlackAttachment(SlackStatus status, Object... params)

return Attachment.builder()
.color(changeColorToHex(status.getColor()))
.title("새로운 유저 '" + userName + "'님이 가입했습니다!")
.fields(List.of(
generateSlackField("총 유저 수", " 👉 " + userRepository.count() + "명"),
generateSlackField("가입한 OS", "👉 " + os)))
generateSlackField("User Name", userName),
generateSlackField("User OS", os)))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
@Getter
@RequiredArgsConstructor
public enum SlackStatus {
NEW_USER_SIGNUP(java.awt.Color.GREEN, "🎉 신규 유저 회원 가입 발생"),
INTERNAL_ERROR(java.awt.Color.ORANGE, "🚨 서버 내부 에러 발생"),
CLIENT_ERROR(java.awt.Color.RED, "😭 서버 오류 발생");
NEW_USER_SIGNUP(java.awt.Color.GREEN, "🎉 신규 유저"),
INTERNAL_ERROR(java.awt.Color.ORANGE, "🚨 서버 내부 에러"),
CLIENT_ERROR(java.awt.Color.RED, "😭 서버 오류");

private final java.awt.Color color;
private final String title;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import sopt.org.hmh.domain.auth.exception.AuthException;
import sopt.org.hmh.domain.auth.repository.OnboardingInfoRepository;
import sopt.org.hmh.domain.auth.repository.ProblemRepository;
import sopt.org.hmh.domain.slack.builder.NewUserSlackMessageBuilder;
import sopt.org.hmh.domain.slack.constant.SlackStatus;
import sopt.org.hmh.domain.user.domain.User;
import sopt.org.hmh.domain.user.domain.UserConstants;
import sopt.org.hmh.domain.user.domain.exception.UserError;
Expand All @@ -31,7 +29,6 @@ public class UserService {
private final UserRepository userRepository;
private final OnboardingInfoRepository onboardingInfoRepository;
private final ProblemRepository problemRepository;
private final NewUserSlackMessageBuilder newUserSlackMessageBuilder;

@Transactional
public void withdraw(Long userId) {
Expand Down Expand Up @@ -59,17 +56,15 @@ public void validateDuplicateUser(String socialId, SocialPlatform socialPlatform
}
}

public User addUser(SocialPlatform socialPlatform, String socialId, String name, String os) {
public User addUser(SocialPlatform socialPlatform, String socialId, String name) {
this.validateDuplicateUser(socialId, socialPlatform);
User user = userRepository.save(
return userRepository.save(
User.builder()
.socialPlatform(socialPlatform)
.socialId(socialId)
.name(validateName(name))
.build()
);
newUserSlackMessageBuilder.sendNotification(SlackStatus.NEW_USER_SIGNUP, name, os);
return user;
}

private String validateName(String name) {
Expand Down
Loading