McpSessionAdapter.groovy
7.64 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
* This software is in the public domain under CC0 1.0 Universal plus a
* Grant of Patent License.
*
* To the extent possible under law, author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software (see the LICENSE.md file). If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
package org.moqui.mcp.adapter
import org.moqui.entity.EntityValue
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
/**
* Adapter that maps Moqui Visit sessions to MCP sessions.
* Provides in-memory session tracking to avoid database lock contention.
*/
class McpSessionAdapter {
protected final static Logger logger = LoggerFactory.getLogger(McpSessionAdapter.class)
// Visit ID → MCP Session state
private final Map<String, McpSession> sessions = new ConcurrentHashMap<>()
// User ID → Set of Visit IDs (for user-targeted notifications)
private final Map<String, Set<String>> userSessions = new ConcurrentHashMap<>()
// Session-specific locks to avoid sessionId.intern() deadlocks
private final Map<String, Object> sessionLocks = new ConcurrentHashMap<>()
/**
* Create a new MCP session from a Moqui Visit
* @param visit The Moqui Visit entity
* @return The created McpSession
*/
McpSession createSession(EntityValue visit) {
String visitId = visit.visitId?.toString()
String userId = visit.userId?.toString()
if (!visitId) {
throw new IllegalArgumentException("Visit must have a visitId")
}
def session = new McpSession(
visitId: visitId,
userId: userId,
state: McpSession.STATE_INITIALIZED
)
sessions.put(visitId, session)
// Track user → sessions mapping
if (userId) {
def userSet = userSessions.computeIfAbsent(userId) { new ConcurrentHashMap<>().newKeySet() }
userSet.add(visitId)
}
logger.debug("Created MCP session ${visitId} for user ${userId}")
return session
}
/**
* Create a new MCP session with explicit parameters
* @param visitId The Visit/session ID
* @param userId The user ID
* @return The created McpSession
*/
McpSession createSession(String visitId, String userId) {
if (!visitId) {
throw new IllegalArgumentException("visitId is required")
}
def session = new McpSession(
visitId: visitId,
userId: userId,
state: McpSession.STATE_INITIALIZED
)
sessions.put(visitId, session)
// Track user → sessions mapping
if (userId) {
def userSet = userSessions.computeIfAbsent(userId) { new ConcurrentHashMap<>().newKeySet() }
userSet.add(visitId)
}
logger.debug("Created MCP session ${visitId} for user ${userId}")
return session
}
/**
* Close and remove a session
* @param visitId The session/visit ID to close
*/
void closeSession(String visitId) {
def session = sessions.remove(visitId)
if (session) {
// Remove from user tracking
if (session.userId) {
def userSet = userSessions.get(session.userId)
if (userSet) {
userSet.remove(visitId)
if (userSet.isEmpty()) {
userSessions.remove(session.userId)
}
}
}
// Clean up session lock
sessionLocks.remove(visitId)
logger.debug("Closed MCP session ${visitId}")
}
}
/**
* Get a session by visit ID
* @param visitId The session/visit ID
* @return The McpSession or null if not found
*/
McpSession getSession(String visitId) {
return sessions.get(visitId)
}
/**
* Check if a session exists and is active
* @param visitId The session/visit ID
* @return true if the session exists
*/
boolean hasSession(String visitId) {
return sessions.containsKey(visitId)
}
/**
* Get all session IDs for a specific user
* @param userId The user ID
* @return Set of session/visit IDs (empty set if none)
*/
Set<String> getSessionsForUser(String userId) {
return userSessions.get(userId) ?: Collections.emptySet()
}
/**
* Get all active session IDs
* @return Set of all session IDs
*/
Set<String> getAllSessionIds() {
return sessions.keySet()
}
/**
* Get the count of active sessions
* @return Number of active sessions
*/
int getSessionCount() {
return sessions.size()
}
/**
* Get a session-specific lock for synchronized operations
* @param visitId The session/visit ID
* @return The lock object
*/
Object getSessionLock(String visitId) {
return sessionLocks.computeIfAbsent(visitId) { new Object() }
}
/**
* Update session state
* @param visitId The session/visit ID
* @param state The new state
*/
void setSessionState(String visitId, int state) {
def session = sessions.get(visitId)
if (session) {
session.state = state
logger.debug("Session ${visitId} state changed to ${state}")
}
}
/**
* Update session activity timestamp
* @param visitId The session/visit ID
*/
void touchSession(String visitId) {
def session = sessions.get(visitId)
if (session) {
session.touch()
}
}
/**
* Get session statistics for monitoring
* @return Map of session statistics
*/
Map getStatistics() {
return [
totalSessions: sessions.size(),
usersWithSessions: userSessions.size(),
sessionsPerUser: userSessions.collectEntries { userId, sessionSet ->
[(userId): sessionSet.size()]
}
]
}
}
/**
* Represents an MCP session state
*/
class McpSession {
static final int STATE_UNINITIALIZED = 0
static final int STATE_INITIALIZING = 1
static final int STATE_INITIALIZED = 2
String visitId
String userId
int state = STATE_UNINITIALIZED
long lastActivity = System.currentTimeMillis()
long createdAt = System.currentTimeMillis()
// SSE writer reference (for active connections)
PrintWriter sseWriter
// Notification queue for this session
List<Map> notificationQueue = Collections.synchronizedList(new ArrayList<>())
// Subscriptions (method names this session is subscribed to)
Set<String> subscriptions = Collections.newSetFromMap(new ConcurrentHashMap<>())
void touch() {
lastActivity = System.currentTimeMillis()
}
boolean isActive() {
return state == STATE_INITIALIZED && sseWriter != null && !sseWriter.checkError()
}
boolean hasActiveWriter() {
return sseWriter != null && !sseWriter.checkError()
}
long getDurationMs() {
return System.currentTimeMillis() - createdAt
}
Map toMap() {
return [
visitId: visitId,
userId: userId,
state: state,
lastActivity: lastActivity,
createdAt: createdAt,
durationMs: getDurationMs(),
active: isActive(),
hasWriter: sseWriter != null,
queuedNotifications: notificationQueue.size(),
subscriptions: subscriptions.toList()
]
}
}