-
Notifications
You must be signed in to change notification settings - Fork 1
[KUIT-58] AWS SQS 기반 디스코드 역할 동기화 #59
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
Open
lyouxsun
wants to merge
11
commits into
main
Choose a base branch
from
refactor/KUIT-58
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8670849
feat: 디스코드 봇 Docker 이미지 빌드/배포/컨테이너 생성 로직 추가
lyouxsun 393d7e7
chore: discord-bot 의존성 초기화 및 lockfile 추가
lyouxsun d8a2627
chore: deploy.sh 실행 권한 설정 추가
lyouxsun a93d38a
deploy: discord-bot 재시작 최소화 (이미지 변경 시만)
lyouxsun 4fc1160
refactor: AWSpring(SDK v2) 기반 S3 설정으로 마이그레이션
lyouxsun 0bccce5
fix: S3 presigned 서명 조건 수정
lyouxsun a65ee4f
feat: SQS 기반 역할 변경 이벤트 수신 로직 구현
lyouxsun c580aa1
fix: flyway 관련 테스트 오류 수정
lyouxsun c78751f
fix: .env에 SQS_QUEUE_NAME 추가
lyouxsun 71f5af4
feat: 디스코드 역할 변경 이벤트 DB 반영 로직 추가
lyouxsun e8393c1
fix: 코드리뷰 피드백 반영
lyouxsun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,6 +11,14 @@ jobs: | |
| steps: | ||
| - uses: actions/checkout@v4 | ||
|
|
||
| - name: Detect changed paths | ||
| id: changes | ||
| uses: dorny/paths-filter@v3 | ||
| with: | ||
| filters: | | ||
| bot: | ||
| - 'discord-bot/**' | ||
|
|
||
| - name: Cache gradle | ||
| uses: actions/setup-java@v4 | ||
| with: | ||
|
|
@@ -29,19 +37,28 @@ jobs: | |
| - name: Build with Gradle Wrapper | ||
| run: ./gradlew build | ||
|
|
||
| - name: Build Docker Image | ||
| run: | ||
| - name: Build Docker Images (Spring) | ||
| run: | | ||
| docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_IMAGE_NAME }} . | ||
| - name: Build Docker Image (Discord Bot) | ||
| if: steps.changes.outputs.bot == 'true' | ||
| run: | | ||
| docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_BOT_IMAGE_NAME }}:latest ./discord-bot | ||
|
|
||
| - name: Login to Docker Hub | ||
| uses: docker/login-action@v3 | ||
| with: | ||
| username: ${{ secrets.DOCKERHUB_USERNAME }} | ||
| password: ${{ secrets.DOCKERHUB_TOKEN }} | ||
|
|
||
| - name: Publish Docker Image to Docker Hub | ||
| run: | ||
| docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_IMAGE_NAME }} | ||
| - name: Publish Docker Image to Docker Hub (Spring) | ||
| run: | | ||
| docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_IMAGE_NAME }}:latest | ||
|
|
||
| - name: Publish Docker Image to Docker Hub (Discord Bot) | ||
| if: steps.changes.outputs.bot == 'true' | ||
| run: | | ||
| docker push ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_BOT_IMAGE_NAME }}:latest | ||
|
|
||
| - name: Upload Flyway migrations to EC2 | ||
| uses: appleboy/[email protected] | ||
|
|
@@ -54,6 +71,26 @@ jobs: | |
| target: "/home/ubuntu/migrations/" | ||
| strip_components: 4 | ||
|
|
||
| - name: Upload docker compose files to EC2 (overwrite) | ||
| uses: appleboy/[email protected] | ||
| with: | ||
| host: ${{ secrets.SSH_HOST }} | ||
| username: ${{ secrets.SSH_USERNAME }} | ||
| key: ${{ secrets.SSH_PASSWORD }} | ||
| port: ${{ secrets.SSH_PORT }} | ||
| source: "docker-compose.yml" | ||
| target: "/home/ubuntu/" | ||
|
|
||
| - name: Upload deploy script to EC2 (overwrite) | ||
| uses: appleboy/[email protected] | ||
| with: | ||
| host: ${{ secrets.SSH_HOST }} | ||
| username: ${{ secrets.SSH_USERNAME }} | ||
| key: ${{ secrets.SSH_PASSWORD }} | ||
| port: ${{ secrets.SSH_PORT }} | ||
| source: "scripts/deploy.sh" | ||
| target: "/home/ubuntu/" | ||
| strip_components: 1 | ||
|
|
||
| - name: executing remote ssh commands using password | ||
| uses: appleboy/[email protected] | ||
|
|
@@ -63,6 +100,9 @@ jobs: | |
| key: ${{ secrets.SSH_PASSWORD }} | ||
| port: ${{ secrets.SSH_PORT }} | ||
| script: | | ||
| echo "🔧 Ensuring deploy.sh is executable" | ||
| sudo chmod +x /home/ubuntu/deploy.sh | ||
|
|
||
| echo "📄 Writing /home/ubuntu/.env" | ||
| sudo bash -c 'cat > /home/ubuntu/.env << EOF | ||
| DISCORD_CLIENT_ID=${{ secrets.DISCORD_CLIENT_ID }} | ||
|
|
@@ -81,6 +121,9 @@ jobs: | |
| PROD_DB_URL=${{ secrets.PROD_DB_URL }} | ||
| PROD_DB_USERNAME=${{ secrets.PROD_DB_USERNAME }} | ||
| PROD_DB_PASSWORD=${{ secrets.PROD_DB_PASSWORD }} | ||
|
|
||
| SQS_QUEUE_URL=${{ secrets.SQS_QUEUE_URL }} | ||
| SQS_QUEUE_NAME=${{ secrets.SQS_QUEUE_NAME }} | ||
| EOF' | ||
|
|
||
| echo "🛫 Running Flyway migrations (one-off)" | ||
|
|
@@ -98,5 +141,4 @@ jobs: | |
| -password="$PROD_DB_PASSWORD" \ | ||
| migrate | ||
|
|
||
|
|
||
| sudo /home/ubuntu/deploy.sh | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| node_modules/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| FROM node:20-alpine | ||
|
|
||
| WORKDIR /app | ||
|
|
||
| # 의존성 설치 | ||
| COPY package*.json ./ | ||
| RUN npm ci --omit=dev | ||
|
|
||
| # 소스 복사 | ||
| COPY . . | ||
|
|
||
| # 실행 | ||
| CMD ["node", "index.js"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| /** | ||
| * Discord Bot (Producer) | ||
| * - Discord Gateway(WebSocket)에서 멤버 업데이트 이벤트를 수신 | ||
| * - 역할(Role) 변경을 감지하여 added/removed diff를 계산 | ||
| * - 계산된 이벤트를 SQS로 발행(SendMessage)하여 비동기 처리 파이프라인을 시작 | ||
| * | ||
| * 필요한 환경변수(.env): | ||
| * - DISCORD_BOT_TOKEN: Discord Bot 토큰 | ||
| * - SQS_QUEUE_URL: 발행 대상 SQS Queue URL | ||
| * - LOG_LEVEL | ||
| */ | ||
|
|
||
| // 역할 변경 감지 + diff 계산 | ||
| import { Client, GatewayIntentBits, Partials } from "discord.js"; | ||
| import { v4 as uuidv4 } from "uuid"; | ||
| import pino from "pino"; | ||
| import { publishRoleChangeEvent } from "./sqsProducer.js"; | ||
lyouxsun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const log = pino({ level: process.env.LOG_LEVEL || "info" }); | ||
|
|
||
| const client = new Client({ | ||
| intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers], | ||
| partials: [Partials.GuildMember], // 일부 이벤트에서 member 정보가 partial로 들어올 수 있어 fetch()로 보강 | ||
| }); | ||
|
|
||
| // oldMember/newMember의 역할 목록을 비교해 "추가된 역할"과 "삭제된 역할"을 계산 | ||
| // SQS에는 diff만 보내서 메시지를 가볍게 유지 | ||
| function diffRoles(oldMember, newMember) { | ||
| const oldSet = new Set(oldMember.roles.cache.keys()); | ||
| const newSet = new Set(newMember.roles.cache.keys()); | ||
|
|
||
| //@everyone 역할은 diff 계산에서 제외 : @everyone 역할은 role id가 guild id와 동일 | ||
| oldSet.delete(oldMember.guild.id); | ||
| newSet.delete(newMember.guild.id); | ||
|
|
||
| const added = []; | ||
| const removed = []; | ||
|
|
||
| for (const r of newSet) if (!oldSet.has(r)) added.push(r); | ||
| for (const r of oldSet) if (!newSet.has(r)) removed.push(r); | ||
|
|
||
| return { added, removed }; | ||
| } | ||
|
|
||
| client.on("ready", () => { | ||
| log.info({ botUser: client.user?.tag }, "Discord bot ready"); | ||
| }); | ||
|
|
||
| // KST(Asia/Seoul) 기준으로 "YYYY-MM-DDTHH:mm:ss" 형태의 문자열을 생성 | ||
| function nowKstLocalDateTimeString() { | ||
| const now = new Date(); | ||
| // sv-SE 포맷은 24시간제 "YYYY-MM-DD HH:mm:ss" 형태로 안정적으로 출력되어 가공이 쉽습니다. | ||
| const kst = new Intl.DateTimeFormat("sv-SE", { | ||
| timeZone: "Asia/Seoul", | ||
| year: "numeric", | ||
| month: "2-digit", | ||
| day: "2-digit", | ||
| hour: "2-digit", | ||
| minute: "2-digit", | ||
| second: "2-digit", | ||
| hour12: false, | ||
| }).format(now); | ||
|
|
||
| return kst.replace(" ", "T"); | ||
| } | ||
|
|
||
|
|
||
| client.on("guildMemberUpdate", async (oldMember, newMember) => { | ||
| try { | ||
| // 이벤트 payload가 불완전하게 들어오는 경우가 있어 필요한 정보를 fetch로 보강 | ||
| // 네트워크 호출이므로 실패 가능 → try/catch로 감싸기 | ||
| if (oldMember.partial) oldMember = await oldMember.fetch(); | ||
| if (newMember.partial) newMember = await newMember.fetch(); | ||
|
|
||
| const { added, removed } = diffRoles(oldMember, newMember); | ||
| // 역할 변화가 없으면 SQS로 발행하지 않음 | ||
| if (added.length === 0 && removed.length === 0) return; | ||
|
|
||
| // SQS로 발행할 이벤트 메시지 | ||
| // - eventId: 중복 발행/재시도 상황에서 소비자가 멱등 처리할 수 있도록 UUID 부여 | ||
| const payload = { | ||
| eventType: "DISCORD_ROLE_CHANGED", | ||
| eventId: uuidv4(), | ||
| occurredAt: nowKstLocalDateTimeString(), | ||
| guildId: newMember.guild.id, | ||
| discordUserId: newMember.user.id, | ||
| discordLoginId: newMember.user.username, | ||
| addedRoleIds: added, | ||
| removedRoleIds: removed, | ||
| source: "discord-bot", | ||
| schemaVersion: 1, | ||
| }; | ||
|
|
||
| log.info( | ||
| { eventId: payload.eventId, discordUserId: payload.discordUserId, added, removed }, | ||
| "Role change detected" | ||
| ); | ||
|
|
||
| await publishRoleChangeEvent(payload); | ||
| } catch (err) { | ||
| log.error({ err }, "Failed handling guildMemberUpdate"); | ||
| } | ||
| }); | ||
|
|
||
| // Discord Gateway 로그인 (실패 시 토큰/인텐트/네트워크 설정을 점검하세요) | ||
| await client.login(process.env.DISCORD_BOT_TOKEN); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| import "./bot.js"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.