Skip to content
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
26 changes: 8 additions & 18 deletions ServerlessFunction/buildspec-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ env:
SAM_CLI_TELEMETRY: 0
GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.caching=true"
ENVIRONMENT: prod
STACK_NAME: group2-englishstudy-prod

phases:
install:
Expand All @@ -28,26 +27,17 @@ phases:
- echo "Building SAM application for $ENVIRONMENT..."
- cd $CODEBUILD_SRC_DIR/ServerlessFunction
- sam build --parallel --cached
- echo "Build completed"
- echo "Packaging SAM application..."
- sam package --s3-bucket group2-englishstudy-pipeline-artifacts --s3-prefix sam-packages/$ENVIRONMENT --output-template-file packaged-template.yaml

post_build:
commands:
- echo "Deploying to $ENVIRONMENT environment..."
- cd $CODEBUILD_SRC_DIR/ServerlessFunction
- |
sam deploy \
--stack-name $STACK_NAME \
--s3-bucket group2-englishstudy-pipeline-artifacts \
--s3-prefix sam-deploy/prod \
--region ap-northeast-2 \
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND \
--no-confirm-changeset \
--no-fail-on-empty-changeset \
--parameter-overrides \
Environment=$ENVIRONMENT \
ExistingCognitoUserPoolId=ap-northeast-2_ezDwzFCzR \
ExistingCognitoClientId=4ns077jcr1pkue2vvisr6qdpu5
- echo "Deployment completed on $(date)"
- echo "Build completed on $(date)"

artifacts:
files:
- packaged-template.yaml
base-directory: ServerlessFunction

cache:
paths:
Expand Down
23 changes: 8 additions & 15 deletions ServerlessFunction/buildspec-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ env:
SAM_CLI_TELEMETRY: 0
GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.caching=true"
ENVIRONMENT: test
STACK_NAME: group2-englishstudy-test

phases:
install:
Expand All @@ -28,23 +27,17 @@ phases:
- echo "Building SAM application for $ENVIRONMENT..."
- cd $CODEBUILD_SRC_DIR/ServerlessFunction
- sam build --parallel --cached
- echo "Build completed"
- echo "Packaging SAM application..."
- sam package --s3-bucket group2-englishstudy-pipeline-artifacts --s3-prefix sam-packages/$ENVIRONMENT --output-template-file packaged-template.yaml

post_build:
commands:
- echo "Deploying to $ENVIRONMENT environment..."
- cd $CODEBUILD_SRC_DIR/ServerlessFunction
- |
sam deploy \
--stack-name $STACK_NAME \
--resolve-s3 \
--s3-prefix $STACK_NAME \
--region ap-northeast-2 \
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND \
--no-confirm-changeset \
--no-fail-on-empty-changeset \
--parameter-overrides Environment=$ENVIRONMENT ExistingCognitoUserPoolId=ap-northeast-2_ezDwzFCzR ExistingCognitoClientId=4ns077jcr1pkue2vvisr6qdpu5
- echo "Deployment completed on $(date)"
- echo "Build completed on $(date)"

artifacts:
files:
- packaged-template.yaml
base-directory: ServerlessFunction

cache:
paths:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import com.mzc.secondproject.serverless.domain.chatting.model.ChatMessage;
import com.mzc.secondproject.serverless.domain.chatting.repository.ChatRoomRepository;
import com.mzc.secondproject.serverless.domain.chatting.service.ChatMessageService;
import com.mzc.secondproject.serverless.domain.user.model.User;
import com.mzc.secondproject.serverless.domain.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -29,21 +31,23 @@ public class ChatMessageHandler implements RequestHandler<APIGatewayProxyRequest

private final ChatMessageService chatMessageService;
private final ChatRoomRepository chatRoomRepository;
private final UserService userService;
private final HandlerRouter router;

/**
* 기본 생성자 (Lambda에서 사용)
*/
public ChatMessageHandler() {
this(new ChatMessageService(), new ChatRoomRepository());
this(new ChatMessageService(), new ChatRoomRepository(), new UserService());
}

/**
* 의존성 주입 생성자 (테스트 용이성)
*/
public ChatMessageHandler(ChatMessageService chatMessageService, ChatRoomRepository chatRoomRepository) {
public ChatMessageHandler(ChatMessageService chatMessageService, ChatRoomRepository chatRoomRepository, UserService userService) {
this.chatMessageService = chatMessageService;
this.chatRoomRepository = chatRoomRepository;
this.userService = userService;
this.router = initRouter();
}

Expand All @@ -69,6 +73,19 @@ private APIGatewayProxyResponseEvent sendMessage(APIGatewayProxyRequestEvent req
String messageType = dto.getMessageType() != null ? dto.getMessageType() : "TEXT";
String messageId = UUID.randomUUID().toString();
String now = Instant.now().toString();

String nickname = "Unknown";
try {
User user = userService.getUserProfile(userId);
if (user != null && user.getNickname() != null) {
nickname = user.getNickname();
} else {
nickname = "User-" + userId.substring(0, 5);
}
} catch (Exception e) {
logger.warn("닉네임 조회 실패: {}", e.getMessage());
nickname = "User-" + userId.substring(0, 5);
}

ChatMessage message = ChatMessage.builder()
.pk("ROOM#" + roomId)
Expand All @@ -80,6 +97,7 @@ private APIGatewayProxyResponseEvent sendMessage(APIGatewayProxyRequestEvent req
.messageId(messageId)
.roomId(roomId)
.userId(userId)
.nickname(nickname)
.content(dto.getContent())
.messageType(messageType)
.createdAt(now)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,42 @@ public Map<String, Object> handleRequest(Map<String, Object> event, Context cont
RoomToken token = optToken.get();
String userId = token.getUserId();
String roomId = token.getRoomId();

String nickname = "Unknown";

// Cognito Authorizer에서 닉네임 추출
try {
if (event.containsKey("requestContext")) {
Map<String, Object> reqCtx = (Map<String, Object>) event.get("requestContext");

if (reqCtx.containsKey("authorizer")) {
Map<String, Object> auth = (Map<String, Object>) reqCtx.get("authorizer");

Map<String, Object> claims = auth;
if (auth.containsKey("claims")) {
claims = (Map<String, Object>) auth.get("claims");
} else if (auth.containsKey("principalId")) {
claims = auth;
}

if (claims != null) {
if (claims.get("nickname") != null) {
nickname = (String) claims.get("nickname");
} else if (claims.get("custom:nickname") != null) {
nickname = (String) claims.get("custom:nickname");
} else if (claims.get("name") != null) {
nickname = (String) claims.get("name");
}
}
}
}
// 닉네임 못찾았으면 UserId 앞부분 표시
if ("Unknown".equals(nickname) && userId != null && userId.length() > 5) {
nickname = "User-" + userId.substring(0, 5);
}
} catch (Exception ex) {
logger.warn("닉네임 표시 실패: {}", ex.getMessage());
}

// 같은 방에서 기존 연결 삭제 (새로고침 시 중복 연결 방지)
connectionRepository.deleteUserConnectionsInRoom(userId, roomId);

Expand All @@ -72,6 +107,7 @@ public Map<String, Object> handleRequest(Map<String, Object> event, Context cont
.gsi2sk("CONN#" + connectionId)
.connectionId(connectionId)
.userId(userId)
.nickname(nickname)
.roomId(roomId)
.connectedAt(now)
.ttl(ttl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class Connection {

private String connectionId;
private String userId;
private String nickname;
private String roomId;
private String connectedAt;
private Long ttl; // 10분 후 자동 삭제
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.mzc.secondproject.serverless.domain.chatting.model.WordChainSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
Expand All @@ -19,16 +20,20 @@ public class WordChainSessionRepository {

private static final Logger logger = LoggerFactory.getLogger(WordChainSessionRepository.class);
private static final String TABLE_NAME = EnvConfig.getRequired("CHAT_TABLE_NAME");
private static final String GSI1_INDEX_NAME = "GSI1";

private final DynamoDbTable<WordChainSession> table;
private final DynamoDbIndex<WordChainSession> gsi1Index;

public WordChainSessionRepository() {
this.table = AwsClients.dynamoDbEnhanced()
.table(TABLE_NAME, TableSchema.fromBean(WordChainSession.class));
this.gsi1Index = table.index(GSI1_INDEX_NAME);
}

public WordChainSessionRepository(DynamoDbTable<WordChainSession> table) {
this.table = table;
this.gsi1Index = table.index(GSI1_INDEX_NAME);
}

/**
Expand All @@ -52,16 +57,16 @@ public Optional<WordChainSession> findById(String sessionId) {
}

/**
* 방의 활성 세션 조회
* 방의 활성 세션 조회 (GSI1 인덱스 사용)
*/
public Optional<WordChainSession> findActiveByRoomId(String roomId) {
return table.query(QueryConditional.sortBeginsWith(
return gsi1Index.query(QueryConditional.sortBeginsWith(
Key.builder()
.partitionValue("ROOM#" + roomId)
.sortValue("WORDCHAIN#")
.build()))
.items()
.stream()
.flatMap(page -> page.items().stream())
.filter(WordChainSession::isActive)
.findFirst();
}
Expand Down
Loading