Skip to content

Commit e850d63

Browse files
committed
refactory: 결과 전송을 ChatSuccessHandler로 분리
1 parent 9e23b34 commit e850d63

File tree

6 files changed

+72
-66
lines changed

6 files changed

+72
-66
lines changed

ProjectVG.Application/ApplicationServiceCollectionExtensions.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,9 @@ public static IServiceCollection AddApplicationServices(this IServiceCollection
4848
services.AddScoped<ChatLLMProcessor>();
4949
services.AddScoped<ChatTTSProcessor>();
5050
services.AddScoped<ChatResultProcessor>();
51-
51+
5252
// Chat Services - Handlers
53+
services.AddScoped<ChatSuccessHandler>();
5354
services.AddScoped<ChatFailureHandler>();
5455

5556
// Chat Services - Cost Tracking Decorators

ProjectVG.Application/Services/Chat/ChatService.cs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ public class ChatService : IChatService
1414
{
1515
private readonly IServiceScopeFactory _scopeFactory;
1616
private readonly ILogger<ChatService> _logger;
17+
private readonly IChatMetricsService _metricsService;
1718

1819
private readonly IConversationService _conversationService;
1920
private readonly ICharacterService _characterService;
@@ -26,10 +27,12 @@ public class ChatService : IChatService
2627
private readonly ICostTrackingDecorator<ChatLLMProcessor> _llmProcessor;
2728
private readonly ICostTrackingDecorator<ChatTTSProcessor> _ttsProcessor;
2829
private readonly ChatResultProcessor _resultProcessor;
29-
private readonly IChatMetricsService _metricsService;
30-
private readonly ChatFailureHandler _failureHandler;
30+
31+
private readonly ChatSuccessHandler _chatSuccessHandler;
32+
private readonly ChatFailureHandler _chatFailureHandler;
3133

3234
public ChatService(
35+
IChatMetricsService metricsService,
3336
IServiceScopeFactory scopeFactory,
3437
ILogger<ChatService> logger,
3538
IConversationService conversationService,
@@ -41,23 +44,25 @@ public ChatService(
4144
ICostTrackingDecorator<ChatLLMProcessor> llmProcessor,
4245
ICostTrackingDecorator<ChatTTSProcessor> ttsProcessor,
4346
ChatResultProcessor resultProcessor,
44-
IChatMetricsService metricsService,
45-
ChatFailureHandler failureHandler
47+
48+
ChatSuccessHandler chatSuccessHandler,
49+
ChatFailureHandler chatFailureHandler
4650
) {
51+
_metricsService = metricsService;
4752
_scopeFactory = scopeFactory;
4853
_logger = logger;
54+
4955
_conversationService = conversationService;
5056
_characterService = characterService;
5157
_validator = validator;
5258
_memoryPreprocessor = memoryPreprocessor;
5359
_inputProcessor = inputProcessor;
5460
_actionProcessor = actionProcessor;
55-
5661
_llmProcessor = llmProcessor;
5762
_ttsProcessor = ttsProcessor;
5863
_resultProcessor = resultProcessor;
59-
_metricsService = metricsService;
60-
_failureHandler = failureHandler;
64+
_chatSuccessHandler = chatSuccessHandler;
65+
_chatFailureHandler = chatFailureHandler;
6166
}
6267

6368
public async Task<ChatRequestResult> EnqueueChatRequestAsync(ChatRequestCommand command)
@@ -81,16 +86,14 @@ public async Task<ChatRequestResult> EnqueueChatRequestAsync(ChatRequestCommand
8186
/// </summary>
8287
private async Task<ChatProcessContext> PrepareChatRequestAsync(ChatRequestCommand command)
8388
{
84-
var characterDto = await _characterService.GetCharacterByIdAsync(command.CharacterId);
85-
var conversationHistory = await _conversationService.GetConversationHistoryAsync(command.UserId, command.CharacterId, 10);
86-
87-
command.SetConversationHistory(conversationHistory);
8889
await _inputProcessor.ProcessAsync(command);
8990
await _actionProcessor.ProcessAsync(command);
90-
91+
92+
var characterInfo = await _characterService.GetCharacterByIdAsync(command.CharacterId);
93+
var conversationHistoryContext = await _conversationService.GetConversationHistoryAsync(command.UserId, command.CharacterId, 10);
9194
var memoryContext = await _memoryPreprocessor.CollectMemoryContextAsync(command);
9295

93-
return new ChatProcessContext(command, characterDto!, conversationHistory, memoryContext);
96+
return new ChatProcessContext(command, characterInfo, conversationHistoryContext, memoryContext);
9497
}
9598

9699
/// <summary>
@@ -99,17 +102,17 @@ private async Task<ChatProcessContext> PrepareChatRequestAsync(ChatRequestComman
99102
private async Task ProcessChatRequestInternalAsync(ChatProcessContext context)
100103
{
101104
try {
102-
//
103105
await _llmProcessor.ProcessAsync(context);
104106
await _ttsProcessor.ProcessAsync(context);
105-
107+
108+
await _chatSuccessHandler.HandleAsync(context);
109+
106110
using var scope = _scopeFactory.CreateScope();
107111
var resultProcessor = scope.ServiceProvider.GetRequiredService<ChatResultProcessor>();
108-
await resultProcessor.SendResultsAsync(context);
109112
await resultProcessor.PersistResultsAsync(context);
110113
}
111-
catch (Exception ex) {
112-
await _failureHandler.HandleFailureAsync(context, ex);
114+
catch (Exception) {
115+
await _chatFailureHandler.HandleAsync(context);
113116
}
114117
finally {
115118
_metricsService.EndChatMetrics();

ProjectVG.Application/Services/Chat/Handlers/ChatFailureHandler.cs

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,36 +10,22 @@ public class ChatFailureHandler
1010
{
1111
private readonly ILogger<ChatFailureHandler> _logger;
1212
private readonly IWebSocketManager _webSocketService;
13-
private readonly IConversationService _conversationService;
14-
private readonly IMemoryClient _memoryClient;
1513

1614
public ChatFailureHandler(
1715
ILogger<ChatFailureHandler> logger,
18-
IWebSocketManager webSocketService,
19-
IConversationService conversationService,
20-
IMemoryClient memoryClient)
16+
IWebSocketManager webSocketService)
2117
{
2218
_logger = logger;
2319
_webSocketService = webSocketService;
24-
_conversationService = conversationService;
25-
_memoryClient = memoryClient;
2620
}
2721

28-
public Task HandleFailureAsync(ChatProcessContext context, Exception exception)
22+
public async Task HandleAsync(ChatProcessContext context)
2923
{
30-
_logger.LogError(exception, "채팅 처리 실패: 세션 {UserId}", context.SessionId);
31-
return SendErrorMessageAsync(context, "요청 처리 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
32-
}
33-
34-
private async Task SendErrorMessageAsync(ChatProcessContext context, string errorMessage)
35-
{
36-
try
37-
{
38-
var errorResponse = new WebSocketMessage("error", new { message = errorMessage });
24+
try {
25+
var errorResponse = new WebSocketMessage("fail", "");
3926
await _webSocketService.SendAsync(context.UserId.ToString(), errorResponse);
4027
}
41-
catch (Exception ex)
42-
{
28+
catch (Exception ex) {
4329
_logger.LogError(ex, "오류 메시지 전송 실패: 세션 {UserId}", context.SessionId);
4430
}
4531
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using ProjectVG.Application.Models.Chat;
2+
using ProjectVG.Application.Models.WebSocket;
3+
using ProjectVG.Application.Services.WebSocket;
4+
5+
6+
namespace ProjectVG.Application.Services.Chat.Handlers
7+
{
8+
public class ChatSuccessHandler
9+
{
10+
private readonly ILogger<ChatSuccessHandler> _logger;
11+
private readonly IWebSocketManager _webSocketService;
12+
13+
public ChatSuccessHandler(
14+
ILogger<ChatSuccessHandler> logger,
15+
IWebSocketManager webSocketService)
16+
{
17+
_logger = logger;
18+
_webSocketService = webSocketService;
19+
}
20+
21+
public async Task HandleAsync(ChatProcessContext context)
22+
{
23+
foreach (var segment in context.Segments.OrderBy(s => s.Order)) {
24+
if (segment.IsEmpty) continue;
25+
26+
var integratedMessage = new IntegratedChatMessage {
27+
SessionId = context.SessionId,
28+
Text = segment.Text,
29+
AudioFormat = segment.AudioContentType ?? "wav",
30+
AudioLength = segment.AudioLength,
31+
Timestamp = DateTime.UtcNow
32+
};
33+
34+
integratedMessage.SetAudioData(segment.AudioData);
35+
36+
var wsMessage = new WebSocketMessage("chat", integratedMessage);
37+
await _webSocketService.SendAsync(context.UserId.ToString(), wsMessage);
38+
}
39+
40+
_logger.LogDebug("채팅 결과 전송 완료: 세션 {UserId}, 세그먼트 {SegmentCount}개",
41+
context.SessionId, context.Segments.Count(s => !s.IsEmpty));
42+
}
43+
}
44+
}

ProjectVG.Application/Services/Chat/IChatService.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,6 @@ namespace ProjectVG.Application.Services.Chat
44
{
55
public interface IChatService
66
{
7-
/// <summary>
8-
/// 채팅 요청을 검증하고 처리합니다
9-
/// </summary>
10-
/// <param name="command">채팅 처리 명령</param>
11-
/// <returns>작업 요청 결과</returns>
127
Task<ChatRequestResult> EnqueueChatRequestAsync(ChatRequestCommand command);
138
}
149
}

ProjectVG.Application/Services/Chat/Processors/ChatResultProcessor.cs

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -97,28 +97,5 @@ private async Task PersistMemoryAsync(ChatProcessContext context)
9797
_logger.LogWarning(ex, "메모리 삽입 실패: 사용자={UserId}, 캐릭터={CharacterId}", context.UserId, context.CharacterId);
9898
}
9999
}
100-
101-
public async Task SendResultsAsync(ChatProcessContext context)
102-
{
103-
foreach (var segment in context.Segments.OrderBy(s => s.Order)) {
104-
if (segment.IsEmpty) continue;
105-
106-
var integratedMessage = new IntegratedChatMessage {
107-
SessionId = context.SessionId,
108-
Text = segment.Text,
109-
AudioFormat = segment.AudioContentType ?? "wav",
110-
AudioLength = segment.AudioLength,
111-
Timestamp = DateTime.UtcNow
112-
};
113-
114-
integratedMessage.SetAudioData(segment.AudioData);
115-
116-
var wsMessage = new WebSocketMessage("chat", integratedMessage);
117-
await _webSocketService.SendAsync(context.UserId.ToString(), wsMessage);
118-
}
119-
120-
_logger.LogDebug("채팅 결과 전송 완료: 세션 {UserId}, 세그먼트 {SegmentCount}개",
121-
context.SessionId, context.Segments.Count(s => !s.IsEmpty));
122-
}
123100
}
124101
}

0 commit comments

Comments
 (0)