|
| 1 | +import { type FastifyInstance } from 'fastify'; |
| 2 | +import { requireAuthenticationAny, requireOAuthScope } from '../../../middleware/oauthMiddleware'; |
| 3 | +import { requireTeamPermission } from '../../../middleware/roleMiddleware'; |
| 4 | +import { McpInstallationService } from '../../../services/mcpInstallationService'; |
| 5 | +import { getDb } from '../../../db'; |
| 6 | +import { |
| 7 | + TEAM_ID_PARAM_SCHEMA, |
| 8 | + DUAL_AUTH_SECURITY, |
| 9 | + formatInstallationListResponse, |
| 10 | + type TeamIdParams, |
| 11 | + type RawInstallationListItem |
| 12 | +} from './schemas'; |
| 13 | + |
| 14 | +// ============================================================================= |
| 15 | +// ROUTE IMPLEMENTATION |
| 16 | +// ============================================================================= |
| 17 | + |
| 18 | +export default async function getInstallationsStreamRoute(server: FastifyInstance) { |
| 19 | + server.get<{ |
| 20 | + Params: TeamIdParams; |
| 21 | + }>('/teams/:teamId/mcp/installations/stream', { |
| 22 | + sse: true, |
| 23 | + preValidation: [ |
| 24 | + requireAuthenticationAny(), |
| 25 | + requireOAuthScope('mcp:read'), |
| 26 | + requireTeamPermission('mcp.installations.view') |
| 27 | + ], |
| 28 | + schema: { |
| 29 | + tags: ['MCP Installations'], |
| 30 | + summary: 'Stream MCP installations (SSE)', |
| 31 | + description: 'Real-time installations list stream via Server-Sent Events. Sends initial snapshot then streams list changes as they occur (new installations, deletions, status updates). Connection automatically reconnects on disconnect.', |
| 32 | + security: DUAL_AUTH_SECURITY, |
| 33 | + |
| 34 | + params: TEAM_ID_PARAM_SCHEMA, |
| 35 | + }, |
| 36 | + }, async (request, reply) => { |
| 37 | + const { teamId } = request.params as TeamIdParams; |
| 38 | + const userId = request.user!.id; |
| 39 | + const authType = request.tokenPayload ? 'oauth2' : 'cookie'; |
| 40 | + |
| 41 | + request.log.info( |
| 42 | + { |
| 43 | + operation: 'stream_mcp_installations', |
| 44 | + teamId, |
| 45 | + userId, |
| 46 | + authType |
| 47 | + }, |
| 48 | + 'Starting MCP installations SSE stream' |
| 49 | + ); |
| 50 | + |
| 51 | + try { |
| 52 | + const db = getDb(); |
| 53 | + const installationService = new McpInstallationService(db, request.log); |
| 54 | + |
| 55 | + // Step 1: Get initial installations list |
| 56 | + const initialInstallations = await installationService.getTeamInstallations(teamId, userId); |
| 57 | + |
| 58 | + // Step 2: Send initial snapshot |
| 59 | + const initialSnapshot = formatInstallationListResponse(initialInstallations as RawInstallationListItem[]); |
| 60 | + |
| 61 | + reply.sse.send({ |
| 62 | + id: new Date().toISOString(), |
| 63 | + event: 'snapshot', |
| 64 | + data: { installations: initialSnapshot }, |
| 65 | + }); |
| 66 | + |
| 67 | + request.log.info( |
| 68 | + { |
| 69 | + operation: 'stream_snapshot_sent', |
| 70 | + teamId, |
| 71 | + installationsCount: initialInstallations.length, |
| 72 | + }, |
| 73 | + 'Initial installations snapshot sent' |
| 74 | + ); |
| 75 | + |
| 76 | + // Step 3: Keep connection alive |
| 77 | + reply.sse.keepAlive(); |
| 78 | + |
| 79 | + // Track last update for change detection |
| 80 | + let lastInstallationIds = new Set(initialInstallations.map(i => i.id)); |
| 81 | + |
| 82 | + // Step 4: Poll for changes every 3 seconds |
| 83 | + const pollInterval = setInterval(async () => { |
| 84 | + // Check #1: Before starting async work |
| 85 | + if (!reply.sse.isConnected) { |
| 86 | + clearInterval(pollInterval); |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + try { |
| 91 | + // Query for updated installations |
| 92 | + const updatedInstallations = await installationService.getTeamInstallations(teamId, userId); |
| 93 | + const currentInstallationIds = new Set(updatedInstallations.map(i => i.id)); |
| 94 | + |
| 95 | + // Check #2: After async operation completes |
| 96 | + if (!reply.sse.isConnected) { |
| 97 | + clearInterval(pollInterval); |
| 98 | + return; |
| 99 | + } |
| 100 | + |
| 101 | + // Detect changes: |
| 102 | + // 1. New installations (ID in current but not in last) |
| 103 | + // 2. Deleted installations (ID in last but not in current) |
| 104 | + // 3. Status changes or other updates |
| 105 | + const hasNewInstallations = Array.from(currentInstallationIds).some(id => !lastInstallationIds.has(id)); |
| 106 | + const hasDeletedInstallations = Array.from(lastInstallationIds).some(id => !currentInstallationIds.has(id)); |
| 107 | + |
| 108 | + // Check for status changes by comparing installation objects |
| 109 | + const hasStatusChanges = updatedInstallations.some(updated => { |
| 110 | + const previous = initialInstallations.find(prev => prev.id === updated.id); |
| 111 | + if (!previous) return false; // New installation, already covered |
| 112 | + |
| 113 | + // Compare status fields (using type assertion since these are raw database results) |
| 114 | + const prevRaw = previous as unknown as RawInstallationListItem; |
| 115 | + const updatedRaw = updated as unknown as RawInstallationListItem; |
| 116 | + |
| 117 | + return ( |
| 118 | + prevRaw.status !== updatedRaw.status || |
| 119 | + prevRaw.status_message !== updatedRaw.status_message || |
| 120 | + prevRaw.last_used_at?.getTime() !== updatedRaw.last_used_at?.getTime() |
| 121 | + ); |
| 122 | + }); |
| 123 | + |
| 124 | + if (hasNewInstallations || hasDeletedInstallations || hasStatusChanges) { |
| 125 | + const updatedSnapshot = formatInstallationListResponse(updatedInstallations as RawInstallationListItem[]); |
| 126 | + |
| 127 | + reply.sse.send({ |
| 128 | + id: new Date().toISOString(), |
| 129 | + event: 'installations_update', |
| 130 | + data: { installations: updatedSnapshot }, |
| 131 | + }); |
| 132 | + |
| 133 | + // Update tracking variables |
| 134 | + lastInstallationIds = currentInstallationIds; |
| 135 | + initialInstallations.length = 0; |
| 136 | + initialInstallations.push(...updatedInstallations); |
| 137 | + |
| 138 | + request.log.debug( |
| 139 | + { |
| 140 | + operation: 'stream_installations_update', |
| 141 | + teamId, |
| 142 | + installationsCount: updatedInstallations.length, |
| 143 | + hasNewInstallations, |
| 144 | + hasDeletedInstallations, |
| 145 | + hasStatusChanges |
| 146 | + }, |
| 147 | + 'Installations list update streamed' |
| 148 | + ); |
| 149 | + } |
| 150 | + } catch (error) { |
| 151 | + request.log.error( |
| 152 | + { |
| 153 | + operation: 'poll_installations_failed', |
| 154 | + teamId, |
| 155 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 156 | + }, |
| 157 | + 'Failed to poll for installations updates' |
| 158 | + ); |
| 159 | + } |
| 160 | + }, 3000); // Poll every 3 seconds |
| 161 | + |
| 162 | + // Step 5: Cleanup on disconnect |
| 163 | + reply.sse.onClose(() => { |
| 164 | + clearInterval(pollInterval); |
| 165 | + request.log.info( |
| 166 | + { |
| 167 | + operation: 'stream_mcp_installations_closed', |
| 168 | + teamId, |
| 169 | + }, |
| 170 | + 'MCP installations SSE stream closed' |
| 171 | + ); |
| 172 | + }); |
| 173 | + |
| 174 | + } catch (error) { |
| 175 | + request.log.error( |
| 176 | + { |
| 177 | + operation: 'stream_mcp_installations_failed', |
| 178 | + teamId, |
| 179 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 180 | + }, |
| 181 | + 'Failed to start MCP installations SSE stream' |
| 182 | + ); |
| 183 | + |
| 184 | + // Can't send JSON error after SSE started, log only |
| 185 | + throw error; |
| 186 | + } |
| 187 | + }); |
| 188 | +} |
0 commit comments