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 @@ -202,6 +202,7 @@ private Map<String, Object> handleRegularMessage(String connectionId, MessagePay
broadcastMessage.put("messageId", savedMessage.getMessageId());
broadcastMessage.put("roomId", savedMessage.getRoomId());
broadcastMessage.put("userId", savedMessage.getUserId());
broadcastMessage.put("nickname", savedMessage.getNickname());
broadcastMessage.put("content", savedMessage.getContent());
broadcastMessage.put("messageType", savedMessage.getMessageType());
broadcastMessage.put("createdAt", savedMessage.getCreatedAt());
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
import com.mzc.secondproject.serverless.common.util.ResponseGenerator;
import com.mzc.secondproject.serverless.domain.opic.dto.request.CreateSessionRequest;
import com.mzc.secondproject.serverless.domain.opic.dto.request.SubmitAnswerRequest;
import com.mzc.secondproject.serverless.domain.opic.dto.response.CreateSessionResponse;
import com.mzc.secondproject.serverless.domain.opic.dto.response.FeedbackResponse;
import com.mzc.secondproject.serverless.domain.opic.dto.response.QuestionResponse;
import com.mzc.secondproject.serverless.domain.opic.model.OPIcAnswer;
import com.mzc.secondproject.serverless.domain.opic.model.OPIcQuestion;
import com.mzc.secondproject.serverless.domain.opic.model.OPIcSession;
Expand Down Expand Up @@ -119,55 +121,59 @@ public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent ev
*/
private APIGatewayProxyResponseEvent createSession(APIGatewayProxyRequestEvent event, String userId) {
CreateSessionRequest request = gson.fromJson(event.getBody(), CreateSessionRequest.class);

logger.info("세션 생성 요청: userId={}, topic={}, level={}",
userId, request.topic(), request.targetLevel());

// 주제 + 소주제 + 레벨로 질문 세트 조회
List<OPIcQuestion> questions = repository.findQuestionsByTopicSubTopicAndLevel(
request.topic(),
request.subTopic(),
request.targetLevel()

logger.info("세션 생성 요청: userId={}, topic={}, subTopic={}, targetLevel={}",
userId, request.topic(), request.subTopic(), request.targetLevel());

// 질문 세트 조회 (주제+소주제로 조회)
List<OPIcQuestion> questions = repository.findQuestionsByTopicAndSubTopic(
request.topic(), // 예: "DESCRIPTION"
request.subTopic() // 예: "HOMES"
);


// 질문 데이터 없음 예외 처리
if (questions.isEmpty()) {
return ResponseGenerator.notFound("해당 주제/레벨의 질문이 없습니다.");
String msg = String.format("해당 주제(%s)와 소주제(%s)에 해당하는 질문이 없습니다.",
request.topic(), request.subTopic());
return ResponseGenerator.notFound(msg);
}
// 최대 3개 질문 선택 (랜덤 셔플)

// 질문 3개 랜덤 선택
Collections.shuffle(questions);
List<String> questionIds = questions.stream()
List<OPIcQuestion> selectedQuestions = questions.stream()
.limit(3)
.sorted(Comparator.comparingInt(OPIcQuestion::getOrderInSet))
.collect(Collectors.toList());

// 질문 ID 목록 추출
List<String> questionIds = selectedQuestions.stream()
.map(OPIcQuestion::getQuestionId)
.collect(Collectors.toList());
// 세션 생성

// 세션 저장
OPIcSession session = repository.createSession(
userId,
request.topic(),
request.subTopic(),
request.targetLevel(),
request.targetLevel(), // 사용자가 선택한 레벨 저장 (AL, IM2 등)
questionIds
);
// 첫 질문 Polly 음성 URL 생성 (#368 PollyService 연동)
OPIcQuestion firstQuestion = questions.get(0);

// 첫 번째 질문 응답 생성
OPIcQuestion firstQuestion = selectedQuestions.get(0);
String audioUrl = generateQuestionAudioUrl(firstQuestion);

// Response
Map<String, Object> response = new LinkedHashMap<>();
response.put("sessionId", session.getSessionId());
response.put("totalQuestions", session.getTotalQuestions());
response.put("firstQuestion", Map.of(
"questionId", firstQuestion.getQuestionId(),
"questionText", firstQuestion.getQuestionText(),
"audioUrl", audioUrl,
"questionNumber", 1,
"totalQuestions", session.getTotalQuestions()
));

logger.info("세션 생성 완료: sessionId={}", session.getSessionId());
return ResponseGenerator.created("세션이 생성되었습니다.", response);

QuestionResponse questionResponse = new QuestionResponse(
firstQuestion.getQuestionId(),
firstQuestion.getQuestionText(),
audioUrl,
1, // 현재 질문 번호
3 // 총 질문 수
);

return ResponseGenerator.ok(
new CreateSessionResponse(session.getSessionId(), questionResponse, 3)
);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ public class OPIcQuestion {

private String pk; // QUESTION#questionId
private String sk; // METADATA
private String gsi1pk; // TOPIC#travel
private String gsi1sk; // LEVEL#IM2
private String gsi1pk; // TOPIC#DESCRIPTION (질문 유형 - 대주제)
private String gsi1sk; // SUBTOPIC#HOMES (질문 소재 - 소주제)

private String questionId;
private String topic; // 대주제
private String subTopic; // 소주제
private String topic; // DESCRIPTION, HABIT, PAST_EXPERIENCE ...
private String subTopic; // HOMES, BANKS, MUSIC ...
private String level; // 난이도 (IM1, IM2, IM3, IH, AL)
private String questionText; // 질문 텍스트 (영어)
private String questionTextKo; // 질문 텍스트 (한국어, 참고용)
Expand Down
Loading