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
|
// lib/realtime/NotificationManager.ts
import { Client } from 'pg';
import { EventEmitter } from 'events';
interface NotificationPayload {
id: string;
user_id: string;
title: string;
message: string;
type: string;
related_record_id?: string;
related_record_type?: string;
is_read: boolean;
created_at: string;
}
interface NotificationReadPayload {
id: string;
user_id: string;
is_read: boolean;
read_at?: string;
}
class NotificationManager extends EventEmitter {
private client: Client | null = null;
private isConnected = false;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectDelay = 1000;
private reconnectTimeout: NodeJS.Timeout | null = null;
constructor() {
super();
this.setMaxListeners(100); // SSE 연결이 많을 수 있으므로 제한 증가
this.connect();
}
private async connect() {
try {
// 기존 연결이 있으면 정리
if (this.client) {
try {
await this.client.end();
} catch (error) {
console.warn('Error closing existing connection:', error);
}
}
this.client = new Client({
connectionString: process.env.DATABASE_URL,
application_name: 'notification_listener',
// 연결 유지 설정
keepAlive: true,
keepAliveInitialDelayMillis: 10000,
});
await this.client.connect();
// LISTEN 채널 구독
await this.client.query('LISTEN new_notification');
await this.client.query('LISTEN notification_read');
console.log('NotificationManager: PostgreSQL LISTEN connected');
// 알림 수신 처리
this.client.on('notification', (msg) => {
try {
if (msg.channel === 'new_notification') {
const payload: NotificationPayload = JSON.parse(msg.payload || '{}');
console.log('New notification received:', payload.id, 'for user:', payload.user_id);
this.emit('newNotification', payload);
} else if (msg.channel === 'notification_read') {
const payload: NotificationReadPayload = JSON.parse(msg.payload || '{}');
console.log('Notification read:', payload.id, 'by user:', payload.user_id);
this.emit('notificationRead', payload);
}
} catch (error) {
console.error('Error parsing notification payload:', error);
}
});
// 연결 오류 처리
this.client.on('error', (error) => {
console.error('PostgreSQL LISTEN error:', error);
this.isConnected = false;
this.scheduleReconnect();
});
// 연결 종료 처리
this.client.on('end', () => {
console.log('PostgreSQL LISTEN connection ended');
this.isConnected = false;
this.scheduleReconnect();
});
this.isConnected = true;
this.reconnectAttempts = 0;
// 연결 성공 이벤트 발송
this.emit('connected');
} catch (error) {
console.error('Failed to connect NotificationManager:', error);
this.isConnected = false;
this.scheduleReconnect();
}
}
private scheduleReconnect() {
// 이미 재연결이 예약되어 있으면 무시
if (this.reconnectTimeout) {
return;
}
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('Max reconnection attempts reached for NotificationManager');
this.emit('maxReconnectAttemptsReached');
return;
}
this.reconnectAttempts++;
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
console.log(`Scheduling NotificationManager reconnection in ${delay}ms (attempt ${this.reconnectAttempts})`);
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null;
this.connect();
}, delay);
}
public async disconnect() {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
if (this.client) {
try {
await this.client.end();
} catch (error) {
console.warn('Error disconnecting NotificationManager:', error);
}
this.client = null;
}
this.isConnected = false;
this.emit('disconnected');
}
public getConnectionStatus(): boolean {
return this.isConnected && this.client !== null;
}
public getReconnectAttempts(): number {
return this.reconnectAttempts;
}
// 강제 재연결 (관리자 API용)
public async forceReconnect() {
console.log('Forcing NotificationManager reconnection...');
this.reconnectAttempts = 0;
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = null;
}
await this.disconnect();
await this.connect();
}
// 연결 상태 체크 (헬스체크용)
public async healthCheck(): Promise<{ status: string; details: any }> {
try {
if (!this.client || !this.isConnected) {
return {
status: 'unhealthy',
details: {
connected: false,
reconnectAttempts: this.reconnectAttempts,
maxReconnectAttempts: this.maxReconnectAttempts
}
};
}
// 간단한 쿼리로 연결 상태 확인
await this.client.query('SELECT 1');
return {
status: 'healthy',
details: {
connected: true,
reconnectAttempts: this.reconnectAttempts,
uptime: process.uptime()
}
};
} catch (error) {
return {
status: 'unhealthy',
details: {
connected: false,
error: error instanceof Error ? error.message : 'Unknown error',
reconnectAttempts: this.reconnectAttempts
}
};
}
}
}
// 싱글톤 인스턴스
const notificationManager = new NotificationManager();
// 프로세스 종료 시 정리
process.on('SIGINT', async () => {
console.log('Shutting down NotificationManager...');
await notificationManager.disconnect();
});
process.on('SIGTERM', async () => {
console.log('Shutting down NotificationManager...');
await notificationManager.disconnect();
});
export default notificationManager;
|