feat: 실시간 알림(인앱+SSE, Redis pub/sub) + Redis 캐싱 (8단계)

알림(8-2):
- Notification 모듈 + SSE 스트림(@Sse, @SkipTransform 으로 표준 래퍼 우회).
- 12종 알림 적재(업무 지시/해제/승인요청/승인/수정요청/시작/마감변경/삭제/댓글·답글,
  멤버 초대/역할변경/제거). 행위자 제외 + 중복 dedup. AppShell 종(미읽음 뱃지·드롭다운).
- 실시간 fan-out: REDIS_HOST 시 ioredis pub/sub(다중 인스턴스), 미설정 시 인메모리 폴백.

Redis 캐싱(8-3):
- CacheModule → @keyv/redis(미설정 시 인메모리 폴백). 저장소 목록을 버전 네임스페이스로
  캐시, 생성/수정/삭제·동기화·멤버 초대/제거 시 무효화(공유 버전 키라 다중 인스턴스 정합).
- enableShutdownHooks 로 종료 시 Redis 연결 graceful close.

검증: 백엔드 build/lint 0·20 tests, 프론트 build/lint/type-check 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-19 13:12:47 +09:00
parent ef858f6e34
commit d87726194b
23 changed files with 1539 additions and 42 deletions
@@ -0,0 +1,35 @@
import { useApi } from './useApi'
import { DEFAULT_PAGE_SIZE } from '@/types/pagination'
import type { ApiNotificationList, UnreadCountResult } from '@/types/notification'
// 알림 도메인 API Composable — 인터셉터가 success/data 를 언래핑
// (실시간 스트림 SSE 는 store 에서 EventSource 로 직접 다룬다 — axios 비대상)
export function useNotification() {
const api = useApi()
// 내 알림 목록(페이지네이션 + 미읽음 수)
async function list(
page = 1,
size = DEFAULT_PAGE_SIZE,
): Promise<ApiNotificationList> {
return (await api.get('/notifications', {
params: { page, size },
})) as unknown as ApiNotificationList
}
// 단건 읽음 처리
async function markRead(id: string): Promise<UnreadCountResult> {
return (await api.post(
`/notifications/${id}/read`,
)) as unknown as UnreadCountResult
}
// 전체 읽음 처리
async function markAllRead(): Promise<UnreadCountResult> {
return (await api.post(
'/notifications/read-all',
)) as unknown as UnreadCountResult
}
return { list, markRead, markAllRead }
}
+296 -19
View File
@@ -1,9 +1,12 @@
<script setup lang="ts">
// 앱 공통 셸 — 상단 탑바(브랜드/네비/우측 액션) + 본문 슬롯
// 모든 인증 이후 화면이 이 레이아웃을 공유한다.
import { computed, ref } from 'vue'
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import { useAuthStore } from '@/stores/auth.store'
import { useNotificationStore } from '@/stores/notification.store'
import type { NotificationView } from '@/types/notification'
const route = useRoute()
const router = useRouter()
@@ -21,9 +24,35 @@ const meInitial = computed(() => me.value?.name?.charAt(0) ?? '?')
// 사용자 메뉴 토글
const menuOpen = ref(false)
// 로그아웃 → 로그인 화면으로
// --- 알림(실시간 SSE) ---
const notiStore = useNotificationStore()
const {
views: notiViews,
unreadCount,
loading: notiLoading,
loadingMore: notiLoadingMore,
hasMore: notiHasMore,
} = storeToRefs(notiStore)
const notiOpen = ref(false)
// 알림 항목 클릭 — 읽음 처리 후 대상 화면으로 이동
async function onNotiClick(v: NotificationView) {
notiOpen.value = false
await notiStore.markRead(v.id)
if (v.to) await router.push(v.to)
}
// AppShell 은 인증 이후 화면에서만 마운트되므로 여기서 스트림 연결(멱등)
// (store 싱글톤이 연결을 보유 → 화면 전환에도 끊기지 않음. 해제는 로그아웃 시에만)
onMounted(() => {
if (authStore.isLoggedIn) void notiStore.connect()
})
// 로그아웃 → 알림 스트림 해제 후 로그인 화면으로
async function onLogout() {
menuOpen.value = false
notiStore.disconnect()
await authStore.logout()
await router.push('/login')
}
@@ -82,24 +111,108 @@ async function onLogout() {
<path d="m21 21-4-4" />
</svg>
</button>
<button
class="icon-btn"
type="button"
title="알림"
aria-label="알림"
>
<svg
width="17"
height="17"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
<div class="noti-wrap">
<button
class="icon-btn noti-btn"
type="button"
title="알림"
aria-label="알림"
aria-haspopup="menu"
:aria-expanded="notiOpen"
@click="notiOpen = !notiOpen"
>
<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
<path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
</svg>
</button>
<svg
width="17"
height="17"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
<path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
</svg>
<span
v-if="unreadCount > 0"
class="noti-badge"
:aria-label="`읽지 않은 알림 ${unreadCount}`"
>{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
</button>
<!-- 알림 드롭다운 -->
<div
v-if="notiOpen"
class="noti-panel"
role="menu"
>
<div class="noti-head">
<span class="noti-title">알림</span>
<button
v-if="unreadCount > 0"
type="button"
class="noti-readall"
@click="notiStore.markAllRead()"
>
모두 읽음
</button>
</div>
<div class="noti-list">
<div
v-if="notiLoading && notiViews.length === 0"
class="noti-empty"
>
불러오는
</div>
<div
v-else-if="notiViews.length === 0"
class="noti-empty"
>
알림이 없습니다.
</div>
<template v-else>
<button
v-for="v in notiViews"
:key="v.id"
type="button"
class="noti-item"
:class="{ unread: !v.read }"
role="menuitem"
@click="onNotiClick(v)"
>
<span
class="noti-dot"
:class="`tone-${v.tone || 'none'}`"
/>
<span class="noti-body">
<!-- noti-text v-html store 에서 사용자 입력을 escapeHtml 신뢰 태그(<b>) 조립한 마크업이다 (XSS 위험 없음) -->
<!-- eslint-disable vue/no-v-html -->
<span
class="noti-text"
v-html="v.html"
/>
<!-- eslint-enable vue/no-v-html -->
<span class="noti-time">{{ v.time }}</span>
</span>
</button>
<button
v-if="notiHasMore"
type="button"
class="noti-more"
:disabled="notiLoadingMore"
@click="notiStore.loadMore()"
>
{{ notiLoadingMore ? '불러오는 중…' : '더보기' }}
</button>
</template>
</div>
</div>
<!-- 메뉴 바깥 클릭 닫기 -->
<div
v-if="notiOpen"
class="noti-overlay"
@click="notiOpen = false"
/>
</div>
<div class="me-wrap">
<button
class="me"
@@ -232,6 +345,170 @@ async function onLogout() {
background: #f1f2f4;
color: var(--text);
}
/* 알림 종 + 드롭다운 */
.noti-wrap {
position: relative;
}
.noti-btn {
position: relative;
}
.noti-badge {
position: absolute;
top: -0.125rem;
right: -0.125rem;
min-width: 1rem;
height: 1rem;
padding: 0 0.25rem;
border-radius: 0.5rem;
background: var(--red);
color: #fff;
font-size: 0.625rem;
font-weight: 700;
line-height: 1rem;
text-align: center;
box-shadow: 0 0 0 2px var(--panel);
}
.noti-panel {
position: absolute;
top: calc(100% + 0.5rem);
right: 0;
z-index: 60;
width: 22rem;
max-width: 90vw;
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
overflow: hidden;
}
.noti-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.6875rem 0.875rem;
border-bottom: 1px solid var(--border);
}
.noti-title {
font-size: 0.844rem;
font-weight: 700;
color: var(--text);
}
.noti-readall {
border: none;
background: transparent;
color: var(--accent);
font-family: inherit;
font-size: 0.75rem;
font-weight: 600;
cursor: pointer;
padding: 0.125rem 0.25rem;
border-radius: var(--radius-sm);
}
.noti-readall:hover {
background: var(--accent-weak);
}
.noti-list {
max-height: 24rem;
overflow-y: auto;
}
.noti-empty {
padding: 1.75rem 0.875rem;
text-align: center;
font-size: 0.781rem;
color: var(--text-3);
}
.noti-item {
display: flex;
align-items: flex-start;
gap: 0.625rem;
width: 100%;
padding: 0.6875rem 0.875rem;
border: none;
border-top: 1px solid var(--border);
background: transparent;
font-family: inherit;
text-align: left;
cursor: pointer;
}
.noti-item:first-child {
border-top: none;
}
.noti-item:hover {
background: #fafbfc;
}
.noti-item.unread {
background: var(--accent-weak);
}
.noti-item.unread:hover {
background: #eceafd;
}
.noti-dot {
width: 0.4375rem;
height: 0.4375rem;
border-radius: 50%;
margin-top: 0.375rem;
flex-shrink: 0;
background: var(--text-3);
}
.noti-dot.tone-blue {
background: var(--blue);
}
.noti-dot.tone-amber {
background: var(--amber);
}
.noti-dot.tone-green {
background: var(--green);
}
.noti-dot.tone-red {
background: var(--red);
}
.noti-dot.tone-accent {
background: var(--accent);
}
.noti-body {
flex: 1;
min-width: 0;
}
.noti-text {
display: block;
font-size: 0.8125rem;
color: var(--text);
line-height: 1.45;
}
.noti-text :deep(b) {
font-weight: 600;
}
.noti-time {
display: block;
margin-top: 0.1875rem;
font-size: 0.6875rem;
color: var(--text-3);
}
.noti-more {
width: 100%;
padding: 0.625rem;
border: none;
border-top: 1px solid var(--border);
background: transparent;
font-family: inherit;
font-size: 0.781rem;
font-weight: 600;
color: var(--accent);
cursor: pointer;
}
.noti-more:hover {
background: #fafbfc;
}
.noti-more:disabled {
color: var(--text-3);
cursor: default;
}
.noti-overlay {
position: fixed;
inset: 0;
z-index: 55;
}
.me-wrap {
position: relative;
margin-left: 0.25rem;
+247
View File
@@ -0,0 +1,247 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useNotification } from '@/composables/useNotification'
import { DEFAULT_PAGE_SIZE } from '@/types/pagination'
import { escapeHtml, relativeTimeKo, taskDueInfo } from '@/shared/utils/format'
import type { ApiNotification, NotificationView } from '@/types/notification'
// payload(자유형)에서 문자열/숫자 값 안전 추출
function pstr(p: Record<string, unknown>, k: string): string {
const v = p[k]
return typeof v === 'string' ? v : ''
}
function pnum(p: Record<string, unknown>, k: string): number | null {
const v = p[k]
return typeof v === 'number' ? v : null
}
// API 알림 → 화면 뷰(type+payload → 톤/문구/이동경로). 사용자 입력은 escapeHtml 후 신뢰 태그만 조립
function toView(n: ApiNotification): NotificationView {
const p = n.payload
const actor = escapeHtml(pstr(p, 'actorName') || '누군가')
const repoName = escapeHtml(pstr(p, 'repoName'))
const taskTitle = escapeHtml(pstr(p, 'taskTitle'))
const repoId = pstr(p, 'repoId')
const taskSeq = pnum(p, 'taskSeq')
const taskTo = repoId && taskSeq !== null ? `/repos/${repoId}/tasks/${taskSeq}` : null
let tone = ''
let html = '새 알림'
let to: string | null = taskTo
switch (n.type) {
case 'task.assigned':
tone = 'blue'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 업무를 지시했습니다`
break
case 'task.unassigned':
tone = 'red'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 업무 담당에서 회원님을 제외했습니다`
break
case 'task.started':
tone = 'blue'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 업무를 시작했습니다`
break
case 'task.due_changed': {
const due = pstr(p, 'dueDate')
const body = due
? `마감기한을 <b>${escapeHtml(taskDueInfo(due, false).dateLabel)}</b>(으)로 변경했습니다`
: '마감기한을 해제했습니다'
tone = 'blue'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b>의 ${body}`
break
}
case 'task.removed':
tone = 'red'
to = repoId ? `/repos/${repoId}` : null // 업무가 삭제되므로 저장소로 이동
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 업무를 삭제했습니다`
break
case 'task.approval_requested':
tone = 'amber'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 승인을 요청했습니다`
break
case 'task.approved':
tone = 'green'
html = `<b>${taskTitle}</b> 업무가 승인되었습니다`
break
case 'task.changes_requested':
tone = 'red'
html = `<b>${actor}</b>님이 <b>${taskTitle}</b> 수정을 요청했습니다`
break
case 'task.commented':
tone = ''
html = `<b>${actor}</b>님이 <b>${taskTitle}</b>에 ${p.isReply === true ? '답글' : '댓글'}을 남겼습니다`
break
case 'member.invited':
tone = 'accent'
to = repoId ? `/repos/${repoId}` : null
html = `<b>${actor}</b>님이 <b>${repoName}</b> 저장소에 초대했습니다`
break
case 'member.role_changed': {
const role = pstr(p, 'roleType') === 'admin' ? '관리자' : '멤버'
tone = 'accent'
to = repoId ? `/repos/${repoId}` : null
html = `<b>${actor}</b>님이 <b>${repoName}</b>에서 회원님의 역할을 <b>${role}</b>(으)로 변경했습니다`
break
}
case 'member.removed':
tone = 'red'
to = repoId ? `/repos/${repoId}` : null
html = `<b>${actor}</b>님이 <b>${repoName}</b> 저장소에서 회원님을 제외했습니다`
break
}
return { id: n.id, read: n.read, tone, html, time: relativeTimeKo(n.createdAt), to }
}
// SSE 재연결 지연(ms) — 토큰 만료/네트워크 끊김 시 정리 후 재시도
const RECONNECT_DELAY = 5_000
// 알림 스토어 — 수신함(목록/미읽음) + 실시간 스트림(SSE)
// EventSource 는 store 싱글톤이 보유해 화면 전환과 무관하게 연결을 유지한다(로그아웃 시에만 해제).
export const useNotificationStore = defineStore('notification', () => {
const items = ref<ApiNotification[]>([])
const unreadCount = ref(0)
const total = ref(0)
const page = ref(0)
const loading = ref(false)
const loadingMore = ref(false)
const views = computed<NotificationView[]>(() => items.value.map(toView))
const hasMore = computed(() => items.value.length < total.value)
const notificationApi = useNotification()
// --- SSE 실시간 스트림 ---
// (Pinia setup store 외부 상태 — 반응형 불필요한 연결 핸들/타이머)
let es: EventSource | null = null
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
let wantConnected = false
function openStream(): void {
const base = import.meta.env.VITE_API_BASE_URL || '/api'
es = new EventSource(`${base}/notifications/stream`, { withCredentials: true })
es.onmessage = (e: MessageEvent<string>) => {
try {
const n = JSON.parse(e.data) as ApiNotification
// 재연결 시 동일 알림 재수신 방어(중복 id 무시)
if (items.value.some((x) => x.id === n.id)) return
items.value.unshift(n)
total.value += 1
if (!n.read) unreadCount.value += 1
} catch {
// 파싱 실패(하트비트 등 비정상 페이로드) 무시
}
}
es.onerror = () => {
// 연결 끊김(토큰 만료/네트워크) — 정리 후 재연결 예약. 해제 의사가 있으면 멈춤
if (es) {
es.close()
es = null
}
if (wantConnected && !reconnectTimer) {
reconnectTimer = setTimeout(() => {
reconnectTimer = null
if (wantConnected) openStream()
}, RECONNECT_DELAY)
}
}
}
// 연결 시작(멱등) — 최초 1회 목록 로드 + 스트림 오픈. 로그인 화면 진입마다 호출돼도 안전
async function connect(): Promise<void> {
if (wantConnected) return
wantConnected = true
await fetchInitial()
openStream()
}
// 연결 해제 + 상태 초기화(로그아웃 시)
function disconnect(): void {
wantConnected = false
if (reconnectTimer) {
clearTimeout(reconnectTimer)
reconnectTimer = null
}
if (es) {
es.close()
es = null
}
items.value = []
unreadCount.value = 0
total.value = 0
page.value = 0
}
// --- 목록/읽음 처리 ---
// 첫 페이지(리셋) 로드 + 미읽음 수 동기화
async function fetchInitial(): Promise<void> {
loading.value = true
try {
const res = await notificationApi.list(1, DEFAULT_PAGE_SIZE)
items.value = res.items
total.value = res.total
unreadCount.value = res.unreadCount
page.value = 1
} finally {
loading.value = false
}
}
// 다음 페이지 이어붙이기(더보기)
async function loadMore(): Promise<void> {
if (loadingMore.value || !hasMore.value) return
loadingMore.value = true
try {
const res = await notificationApi.list(page.value + 1, DEFAULT_PAGE_SIZE)
// 그 사이 실시간 수신으로 중복될 수 있는 id 는 제외하고 append
const known = new Set(items.value.map((x) => x.id))
items.value.push(...res.items.filter((n) => !known.has(n.id)))
total.value = res.total
unreadCount.value = res.unreadCount
page.value += 1
} finally {
loadingMore.value = false
}
}
// 단건 읽음 처리(낙관적 갱신 후 서버 미읽음 수로 보정)
async function markRead(id: string): Promise<void> {
const target = items.value.find((n) => n.id === id)
if (!target || target.read) return
target.read = true
try {
const { unreadCount: c } = await notificationApi.markRead(id)
unreadCount.value = c
} catch {
target.read = false // 실패 시 롤백(인터셉터가 알림 처리)
}
}
// 전체 읽음 처리
async function markAllRead(): Promise<void> {
if (unreadCount.value === 0) return
try {
const { unreadCount: c } = await notificationApi.markAllRead()
items.value.forEach((n) => (n.read = true))
unreadCount.value = c
} catch {
// 인터셉터가 알림 처리
}
}
return {
items,
views,
unreadCount,
total,
loading,
loadingMore,
hasMore,
connect,
disconnect,
fetchInitial,
loadMore,
markRead,
markAllRead,
}
})
+47
View File
@@ -0,0 +1,47 @@
// 알림 도메인 타입 — 백엔드 NotificationService 응답과 1:1
import type { Paginated } from '@/types/pagination'
// 알림 타입(백엔드 NotificationType 과 동일)
export type NotificationType =
| 'task.assigned'
| 'task.unassigned'
| 'task.approval_requested'
| 'task.approved'
| 'task.changes_requested'
| 'task.started'
| 'task.due_changed'
| 'task.removed'
| 'task.commented'
| 'member.invited'
| 'member.role_changed'
| 'member.removed'
// 알림(API 원시) — 표시 문구/링크는 프론트가 type+payload 로 조립
export interface ApiNotification {
id: string
type: NotificationType
payload: Record<string, unknown>
read: boolean
createdAt: string
}
// 목록 응답 — 페이지네이션 + 미읽음 수 동봉
export type ApiNotificationList = Paginated<ApiNotification> & {
unreadCount: number
}
// 읽음 처리 응답
export interface UnreadCountResult {
unreadCount: number
}
// 화면용 알림 뷰(type+payload → 톤/문구/이동경로 파생)
export interface NotificationView {
id: string
read: boolean
tone: string // 좌측 점 색상(blue/amber/green/red/accent/'')
html: string // 조립된 문구(사용자 입력은 escapeHtml 적용)
time: string // 상대시간
to: string | null // 클릭 시 이동 경로
}