-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSseManager.kt
More file actions
230 lines (190 loc) · 7.53 KB
/
SseManager.kt
File metadata and controls
230 lines (190 loc) · 7.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package com.kiero.data.sse.manager
import com.kiero.data.sse.model.SseEvent
import com.kiero.data.sse.repository.SseRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.cancellation.CancellationException
@Singleton
class SseManager @Inject constructor(
private val sseRepository: SseRepository
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var sseJob: Job? = null
private var tokenRefreshJob: Job? = null
private var cachedAccessToken: String? = null
private val mutex = Mutex()
// 부모 이벤트
private val _parentInviteEvents = MutableSharedFlow<SseEvent.Parent.Invite>(
replay = 0,
extraBufferCapacity = 1
)
val parentInviteEvents: SharedFlow<SseEvent.Parent.Invite> = _parentInviteEvents.asSharedFlow()
private val _parentFeedEvents = MutableSharedFlow<SseEvent.Parent.Feed>(
replay = 0,
extraBufferCapacity = 1
)
val parentFeedEvents: SharedFlow<SseEvent.Parent.Feed> = _parentFeedEvents.asSharedFlow()
private val _parentScheduleEvents = MutableSharedFlow<SseEvent.Parent.Schedule>(
replay = 0,
extraBufferCapacity = 1
)
val parentScheduleEvents = _parentScheduleEvents.asSharedFlow()
// 자녀 이벤트
private val _childMissionEvents = MutableSharedFlow<SseEvent.Kid.Mission>(
replay = 0,
extraBufferCapacity = 1
)
val childMissionEvents: SharedFlow<SseEvent.Kid.Mission> = _childMissionEvents.asSharedFlow()
private val _childScheduleEvents = MutableSharedFlow<SseEvent.Kid.Schedule>(
replay = 0,
extraBufferCapacity = 1
)
val childScheduleEvents: SharedFlow<SseEvent.Kid.Schedule> = _childScheduleEvents.asSharedFlow()
private val _childCouponEvents = MutableSharedFlow<SseEvent.Kid.Coupon>(
replay = 0,
extraBufferCapacity = 1
)
val childCouponEvents: SharedFlow<SseEvent.Kid.Coupon> = _childCouponEvents.asSharedFlow()
private val _childDateEvents = MutableSharedFlow<SseEvent.Kid.Date>(
replay = 0,
extraBufferCapacity = 1
)
val dateEvents: SharedFlow<SseEvent.Kid.Date> = _childDateEvents.asSharedFlow()
// 연결 상태
private val _connectionState = MutableSharedFlow<Boolean>(replay = 1)
val connectionState: SharedFlow<Boolean> = _connectionState.asSharedFlow()
private var isSubscribed = false
private var isParentMode = true
fun startParentSubscription() {
initSubscription(isParent = true)
}
fun startChildSubscription() {
initSubscription(isParent = false)
}
private fun initSubscription(isParent: Boolean) {
scope.launch {
mutex.withLock {
if (isSubscribed && isParentMode == isParent) return@launch
stopSubscriptionInternal()
isSubscribed = true
isParentMode = isParent
cachedAccessToken = null
sseJob = launch {
subscriptionLoop(isParent)
}
startTokenRefreshTimer()
}
}
}
private suspend fun subscriptionLoop(isParent: Boolean) {
while (currentCoroutineContext().isActive && isSubscribed) {
try {
// 실패 시 재발급으로 continue
val token = getValidToken() ?: continue
Timber.d("🔄 SSE 연결 시도 (Token: ${token.take(10)}...)")
sseRepository.subscribeEvents(token)
.collect { event ->
_connectionState.emit(true)
if (isParent) handleParentEvent(event)
else handleChildEvent(event)
}
Timber.w("SSE 스트림 종료됨. 즉시 재연결 시도.")
} catch (e: Exception) {
// 상위에 에러 던지기
if (e is CancellationException) throw e
Timber.e(e, "SSE 연결 중 에러 발생")
_connectionState.emit(false)
if (isTokenExpiredError(e)) {
Timber.w("토큰 만료 감지 -> 캐시 삭제 후 재발급 예정")
cachedAccessToken = null
}
delay(3000L)
}
}
}
private fun startTokenRefreshTimer() {
tokenRefreshJob?.cancel()
tokenRefreshJob = scope.launch {
while (isActive) {
delay(180_000L)
Timber.d("⏰ SSE 토큰 갱신 주기 도래 (3분)")
mutex.withLock {
if (isSubscribed) {
cachedAccessToken = null
// 현재 job 취소
sseJob?.cancel()
sseJob = launch {
subscriptionLoop(isParentMode)
}
}
}
}
}
}
private suspend fun getValidToken(): String? {
cachedAccessToken?.let { return it }
return try {
val result = sseRepository.issueSubscribeToken()
result.getOrNull()?.also { newToken ->
cachedAccessToken = newToken
Timber.d("새 SSE 토큰 발급 완료")
}
} catch (e: Exception) {
Timber.e(e, "토큰 발급 실패")
delay(5000L)
null
}
}
private fun isTokenExpiredError(t: Throwable): Boolean {
return t.message?.contains("403") == true || t.message?.contains("Unauthorized") == true
}
fun stopSubscription() {
scope.launch {
mutex.withLock {
stopSubscriptionInternal()
}
}
}
private suspend fun stopSubscriptionInternal() {
isSubscribed = false
cachedAccessToken = null
sseJob?.cancelAndJoin()
tokenRefreshJob?.cancel()
_connectionState.emit(false)
Timber.d("⛔ SSE 구독 완전 중지")
}
private suspend fun handleParentEvent(event: SseEvent) {
when (event) {
is SseEvent.Connected -> Timber.d("부모 SSE Connected")
is SseEvent.Parent.Invite -> _parentInviteEvents.emit(event)
is SseEvent.Parent.Feed -> _parentFeedEvents.emit(event)
is SseEvent.Parent.Schedule -> _parentScheduleEvents.emit(event)
else -> Timber.w("부모 모드에서 알 수 없는 이벤트: $event")
}
}
private suspend fun handleChildEvent(event: SseEvent) {
when (event) {
is SseEvent.Connected -> Timber.d("아이 SSE Connected")
is SseEvent.Kid.Mission -> _childMissionEvents.emit(event)
is SseEvent.Kid.Schedule -> _childScheduleEvents.emit(event)
is SseEvent.Kid.Coupon -> _childCouponEvents.emit(event)
is SseEvent.Kid.Date -> _childDateEvents.emit(event)
else -> Timber.w("자녀 모드에서 알 수 없는 이벤트: $event")
}
}
}