♻️ refactor: split AgentService into focused service modules

- **BaseService**: Shared database connection and JSON serialization utilities
- **AgentService**: Agent management operations (CRUD for agents)
- **SessionService**: Session management operations (CRUD for sessions)
- **SessionLogService**: Session log management operations (CRUD for session logs)

Updated API routes to use appropriate services:
- sessions.ts now uses SessionService for session operations
- session-logs.ts now uses SessionLogService and SessionService as needed
- Maintains backward compatibility with existing API endpoints

Benefits:
- Single Responsibility Principle - each service has a clear focus
- Better code organization and maintainability
- Easier testing and debugging
- Improved separation of concerns
- Shared database infrastructure via BaseService

All TypeScript compilation and build checks pass.
This commit is contained in:
Vaayne
2025-09-12 16:25:50 +08:00
parent 9c956a30ea
commit 64f3d08d4e
8 changed files with 705 additions and 657 deletions
+14 -12
View File
@@ -2,6 +2,8 @@ import express, { Request, Response } from 'express'
import { body, param, query, validationResult } from 'express-validator'
import { agentService } from '../../services/agents/AgentService'
import { sessionLogService } from '../../services/agents/SessionLogService'
import { sessionService } from '../../services/agents/SessionService'
import { loggerService } from '../../services/LoggerService'
const logger = loggerService.withContext('ApiServerSessionLogsRoutes')
@@ -75,7 +77,7 @@ const checkAgentAndSessionExist = async (req: Request, res: Response, next: any)
return
}
const session = await agentService.getSession(sessionId)
const session = await sessionService.getSession(sessionId)
if (!session) {
res.status(404).json({
error: {
@@ -251,7 +253,7 @@ function createSessionLogsRouter(): express.Router {
logger.info(`Creating new log entry for session: ${sessionId}`)
logger.debug('Log data:', logData)
const log = await agentService.createSessionLog(logData)
const log = await sessionLogService.createSessionLog(logData)
logger.info(`Log entry created successfully: ${log.id}`)
return res.status(201).json(log)
@@ -344,7 +346,7 @@ function createSessionLogsRouter(): express.Router {
logger.info(`Creating ${logsData.length} log entries for session: ${sessionId}`)
const logs = await agentService.bulkCreateSessionLogs(logsData)
const logs = await sessionLogService.bulkCreateSessionLogs(logsData)
logger.info(`${logs.length} log entries created successfully for session: ${sessionId}`)
return res.status(201).json({
@@ -454,7 +456,7 @@ function createSessionLogsRouter(): express.Router {
logger.info(`Listing logs for session: ${sessionId} with limit=${limit}, offset=${offset}`)
const result = await agentService.listSessionLogs(sessionId, { limit, offset })
const result = await sessionLogService.listSessionLogs(sessionId, { limit, offset })
logger.info(`Retrieved ${result.logs.length} logs (total: ${result.total}) for session: ${sessionId}`)
return res.json({
@@ -536,7 +538,7 @@ function createSessionLogsRouter(): express.Router {
logger.info(`Getting log entry: ${logId} for session: ${sessionId}`)
const log = await agentService.getSessionLog(logIdNum)
const log = await sessionLogService.getSessionLog(logIdNum)
if (!log) {
logger.warn(`Log entry not found: ${logId}`)
@@ -658,7 +660,7 @@ function createSessionLogsRouter(): express.Router {
logger.debug('Update data:', req.body)
// First check if log exists and belongs to session
const existingLog = await agentService.getSessionLog(logIdNum)
const existingLog = await sessionLogService.getSessionLog(logIdNum)
if (!existingLog || existingLog.session_id !== sessionId) {
logger.warn(`Log entry ${logId} not found for session ${sessionId}`)
return res.status(404).json({
@@ -670,7 +672,7 @@ function createSessionLogsRouter(): express.Router {
})
}
const log = await agentService.updateSessionLog(logIdNum, req.body)
const log = await sessionLogService.updateSessionLog(logIdNum, req.body)
if (!log) {
logger.warn(`Log entry not found for update: ${logId}`)
@@ -755,7 +757,7 @@ function createSessionLogsRouter(): express.Router {
logger.info(`Deleting log entry: ${logId} for session: ${sessionId}`)
// First check if log exists and belongs to session
const existingLog = await agentService.getSessionLog(logIdNum)
const existingLog = await sessionLogService.getSessionLog(logIdNum)
if (!existingLog || existingLog.session_id !== sessionId) {
logger.warn(`Log entry ${logId} not found for session ${sessionId}`)
return res.status(404).json({
@@ -767,7 +769,7 @@ function createSessionLogsRouter(): express.Router {
})
}
const deleted = await agentService.deleteSessionLog(logIdNum)
const deleted = await sessionLogService.deleteSessionLog(logIdNum)
if (!deleted) {
logger.warn(`Log entry not found for deletion: ${logId}`)
@@ -880,7 +882,7 @@ router.get(
const offset = req.query.offset ? parseInt(req.query.offset as string) : 0
// Check if session exists
const sessionExists = await agentService.sessionExists(sessionId)
const sessionExists = await sessionService.sessionExists(sessionId)
if (!sessionExists) {
return res.status(404).json({
error: {
@@ -893,7 +895,7 @@ router.get(
logger.info(`Listing logs for session: ${sessionId} with limit=${limit}, offset=${offset}`)
const result = await agentService.listSessionLogs(sessionId, { limit, offset })
const result = await sessionLogService.listSessionLogs(sessionId, { limit, offset })
logger.info(`Retrieved ${result.logs.length} logs (total: ${result.total}) for session: ${sessionId}`)
return res.json({
@@ -956,7 +958,7 @@ router.get('/session-logs/:logId', validateLogId, handleValidationErrors, async
logger.info(`Getting log entry: ${logId}`)
const log = await agentService.getSessionLog(logIdNum)
const log = await sessionLogService.getSessionLog(logIdNum)
if (!log) {
logger.warn(`Log entry not found: ${logId}`)
+12 -11
View File
@@ -2,6 +2,7 @@ import express, { Request, Response } from 'express'
import { body, param, query, validationResult } from 'express-validator'
import { agentService } from '../../services/agents/AgentService'
import { sessionService } from '../../services/agents/SessionService'
import { loggerService } from '../../services/LoggerService'
const logger = loggerService.withContext('ApiServerSessionsRoutes')
@@ -321,7 +322,7 @@ function createSessionsRouter(): express.Router {
logger.info(`Creating new session for agent: ${agentId}`)
logger.debug('Session data:', sessionData)
const session = await agentService.createSession(sessionData)
const session = await sessionService.createSession(sessionData)
logger.info(`Session created successfully: ${session.id}`)
return res.status(201).json(session)
@@ -428,7 +429,7 @@ function createSessionsRouter(): express.Router {
logger.info(`Listing sessions for agent: ${agentId} with limit=${limit}, offset=${offset}, status=${status}`)
const result = await agentService.listSessions(agentId, { limit, offset, status })
const result = await sessionService.listSessions(agentId, { limit, offset, status })
logger.info(`Retrieved ${result.sessions.length} sessions (total: ${result.total}) for agent: ${agentId}`)
return res.json({
@@ -501,7 +502,7 @@ function createSessionsRouter(): express.Router {
const { agentId, sessionId } = req.params
logger.info(`Getting session: ${sessionId} for agent: ${agentId}`)
const session = await agentService.getSession(sessionId)
const session = await sessionService.getSession(sessionId)
if (!session) {
logger.warn(`Session not found: ${sessionId}`)
@@ -607,7 +608,7 @@ function createSessionsRouter(): express.Router {
logger.debug('Update data:', req.body)
// First check if session exists and belongs to agent
const existingSession = await agentService.getSession(sessionId)
const existingSession = await sessionService.getSession(sessionId)
if (!existingSession || existingSession.main_agent_id !== agentId) {
logger.warn(`Session ${sessionId} not found for agent ${agentId}`)
return res.status(404).json({
@@ -619,7 +620,7 @@ function createSessionsRouter(): express.Router {
})
}
const session = await agentService.updateSession(sessionId, req.body)
const session = await sessionService.updateSession(sessionId, req.body)
if (!session) {
logger.warn(`Session not found for update: ${sessionId}`)
@@ -720,7 +721,7 @@ function createSessionsRouter(): express.Router {
logger.info(`Updating session status: ${sessionId} for agent: ${agentId} to ${status}`)
// First check if session exists and belongs to agent
const existingSession = await agentService.getSession(sessionId)
const existingSession = await sessionService.getSession(sessionId)
if (!existingSession || existingSession.main_agent_id !== agentId) {
logger.warn(`Session ${sessionId} not found for agent ${agentId}`)
return res.status(404).json({
@@ -732,7 +733,7 @@ function createSessionsRouter(): express.Router {
})
}
const session = await agentService.updateSessionStatus(sessionId, status)
const session = await sessionService.updateSessionStatus(sessionId, status)
if (!session) {
logger.warn(`Session not found for status update: ${sessionId}`)
@@ -808,7 +809,7 @@ function createSessionsRouter(): express.Router {
logger.info(`Deleting session: ${sessionId} for agent: ${agentId}`)
// First check if session exists and belongs to agent
const existingSession = await agentService.getSession(sessionId)
const existingSession = await sessionService.getSession(sessionId)
if (!existingSession || existingSession.main_agent_id !== agentId) {
logger.warn(`Session ${sessionId} not found for agent ${agentId}`)
return res.status(404).json({
@@ -820,7 +821,7 @@ function createSessionsRouter(): express.Router {
})
}
const deleted = await agentService.deleteSession(sessionId)
const deleted = await sessionService.deleteSession(sessionId)
if (!deleted) {
logger.warn(`Session not found for deletion: ${sessionId}`)
@@ -923,7 +924,7 @@ router.get('/', validatePagination, handleValidationErrors, async (req: Request,
logger.info(`Listing all sessions with limit=${limit}, offset=${offset}, status=${status}`)
const result = await agentService.listSessions(undefined, { limit, offset, status })
const result = await sessionService.listSessions(undefined, { limit, offset, status })
logger.info(`Retrieved ${result.sessions.length} sessions (total: ${result.total})`)
return res.json({
@@ -983,7 +984,7 @@ router.get('/:sessionId', validateSessionId, handleValidationErrors, async (req:
const { sessionId } = req.params
logger.info(`Getting session: ${sessionId}`)
const session = await agentService.getSession(sessionId)
const session = await sessionService.getSession(sessionId)
if (!session) {
logger.warn(`Session not found: ${sessionId}`)