feat: implement real-time event handling and SSE support; add event publishing and subscription mechanisms

This commit is contained in:
2026-01-17 01:39:06 +00:00
parent f3c0f492be
commit 56b1c40642
13 changed files with 473 additions and 13 deletions
+64
View File
@@ -0,0 +1,64 @@
import type { RedisConnector } from '@sammo-ts/infra';
import type { RealtimeEvent } from '@sammo-ts/common';
export type RealtimeListener = (event: RealtimeEvent) => void;
export const parseRealtimeEvent = (message: string): RealtimeEvent | null => {
if (!message) {
return null;
}
try {
const parsed = JSON.parse(message) as RealtimeEvent;
if (!parsed || typeof parsed !== 'object') {
return null;
}
if (typeof parsed.type !== 'string') {
return null;
}
return parsed;
} catch {
return null;
}
};
// Redis pub/sub 이벤트를 SSE 구독자에게 전달하는 중계 허브.
export class RedisRealtimeEventHub {
private readonly listeners = new Set<RealtimeListener>();
private subscribed = false;
constructor(
private readonly redis: RedisConnector['client'],
private readonly channel: string
) {}
async start(): Promise<void> {
if (this.subscribed) {
return;
}
await this.redis.subscribe(this.channel, (message) => {
const event = parseRealtimeEvent(message);
if (!event) {
return;
}
for (const listener of this.listeners) {
listener(event);
}
});
this.subscribed = true;
}
subscribe(listener: RealtimeListener): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
async stop(): Promise<void> {
if (this.subscribed) {
await this.redis.unsubscribe(this.channel);
this.subscribed = false;
}
await this.redis.quit();
}
}
+12
View File
@@ -0,0 +1,12 @@
import type { RedisConnector } from '@sammo-ts/infra';
import { buildGameEventChannel, type RealtimeEvent } from '@sammo-ts/common';
// 게임 서버의 실시간 이벤트를 Redis pub/sub 채널로 송신한다.
export const publishRealtimeEvent = async (
redis: RedisConnector['client'],
profileName: string,
event: RealtimeEvent
): Promise<void> => {
const channel = buildGameEventChannel(profileName);
await redis.publish(channel, JSON.stringify(event));
};
+30
View File
@@ -0,0 +1,30 @@
export interface SseFrame {
event?: string;
data?: string;
id?: string;
retry?: number;
}
const splitLines = (value: string): string[] => value.split(/\r?\n/);
export const formatSseFrame = (frame: SseFrame): string => {
const lines: string[] = [];
if (frame.event) {
lines.push(`event: ${frame.event}`);
}
if (frame.id) {
lines.push(`id: ${frame.id}`);
}
if (frame.retry !== undefined) {
lines.push(`retry: ${frame.retry}`);
}
const dataLines = splitLines(frame.data ?? '');
for (const line of dataLines) {
lines.push(`data: ${line}`);
}
lines.push('');
return lines.join('\n');
};