|
| 1 | +import '../../typeDefs/expressContext'; |
| 2 | +import express from 'express'; |
| 3 | +import { ObjectId } from 'mongodb'; |
| 4 | +import { getEventsFactory } from '../../resolvers/helpers/eventsFactory'; |
| 5 | +import { checkUserInWorkspaceByProjectId } from '../../directives/requireUserInWorkspace'; |
| 6 | +import { askAiService } from './service'; |
| 7 | +import type { AiStreamPart } from '@hawk.so/types'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Verify the requesting user is a member of the project's workspace. |
| 11 | + * |
| 12 | + * @param req - Express request |
| 13 | + * @param res - Express response |
| 14 | + * @param projectId - project id from query parameters (may be `string[]` if repeated) |
| 15 | + * @returns user id and validated project id if authorized, `null` otherwise (response already sent) |
| 16 | + */ |
| 17 | +async function authorizeProjectAccess( |
| 18 | + req: express.Request, |
| 19 | + res: express.Response, |
| 20 | + projectId: unknown |
| 21 | +): Promise<{ userId: string; projectId: string } | null> { |
| 22 | + const userId = req.context?.user?.id; |
| 23 | + |
| 24 | + if (!userId) { |
| 25 | + res.status(401).json({ error: 'Unauthorized. Please provide authorization token.' }); |
| 26 | + |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + if (!projectId || typeof projectId !== 'string') { |
| 31 | + res.status(400).json({ error: 'projectId query parameter is required' }); |
| 32 | + |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + if (!ObjectId.isValid(projectId)) { |
| 37 | + res.status(400).json({ error: `Invalid projectId format: ${projectId}` }); |
| 38 | + |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + await checkUserInWorkspaceByProjectId(req.context, projectId); |
| 44 | + } catch (error) { |
| 45 | + res.status(403).json({ error: error instanceof Error ? error.message : 'You have no access to this workspace' }); |
| 46 | + |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + return { |
| 51 | + userId, |
| 52 | + projectId, |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Create AI assistant router |
| 58 | + * |
| 59 | + * @returns Express router with AI assistant endpoints |
| 60 | + */ |
| 61 | +export function createAiStreamRouter(): express.Router { |
| 62 | + const router = express.Router(); |
| 63 | + |
| 64 | + /** |
| 65 | + * GET /integration/ai/stream?projectId=<projectId>&eventId=<eventId>&originalEventId=<originalEventId> |
| 66 | + * Stream an AI suggestion for the event |
| 67 | + */ |
| 68 | + router.get('/stream', async (req, res, next) => { |
| 69 | + const abort = new AbortController(); |
| 70 | + |
| 71 | + /** Abort response generation when connection is closed */ |
| 72 | + res.on('close', () => abort.abort()); |
| 73 | + |
| 74 | + try { |
| 75 | + const { projectId, eventId, originalEventId } = req.query; |
| 76 | + |
| 77 | + const authResult = await authorizeProjectAccess(req, res, projectId); |
| 78 | + |
| 79 | + if (!authResult) { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + if (!eventId || typeof eventId !== 'string') { |
| 84 | + res.status(400).json({ error: 'eventId query parameter is required' }); |
| 85 | + |
| 86 | + return; |
| 87 | + } |
| 88 | + |
| 89 | + if (!originalEventId || typeof originalEventId !== 'string') { |
| 90 | + res.status(400).json({ error: 'originalEventId query parameter is required' }); |
| 91 | + |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + const eventsFactory = getEventsFactory(req.context, authResult.projectId); |
| 96 | + |
| 97 | + let stream; |
| 98 | + |
| 99 | + try { |
| 100 | + stream = await askAiService.streamSuggestion(eventsFactory, eventId, originalEventId, abort.signal); |
| 101 | + } catch (error) { |
| 102 | + if (!(error instanceof Error) || error.message !== 'Event not found') { |
| 103 | + throw error; |
| 104 | + } |
| 105 | + |
| 106 | + res.status(404).json({ error: error.message }); |
| 107 | + |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + res.writeHead(200, { |
| 112 | + 'content-type': 'text/event-stream', |
| 113 | + 'cache-control': 'no-cache', |
| 114 | + connection: 'keep-alive', |
| 115 | + }); |
| 116 | + |
| 117 | + try { |
| 118 | + for await (const part of stream) { |
| 119 | + if (abort.signal.aborted) { |
| 120 | + break; |
| 121 | + } |
| 122 | + |
| 123 | + res.write(`data: ${JSON.stringify(part)}\n\n`); |
| 124 | + } |
| 125 | + } catch (error) { |
| 126 | + if (!abort.signal.aborted) { |
| 127 | + const part: AiStreamPart = { |
| 128 | + type: 'error', |
| 129 | + errorText: error instanceof Error ? error.message : 'AI suggestion failed.', |
| 130 | + }; |
| 131 | + |
| 132 | + res.write(`data: ${JSON.stringify(part)}\n\n`); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + res.end(); |
| 137 | + } catch (error) { |
| 138 | + if (abort.signal.aborted) { |
| 139 | + return; |
| 140 | + } |
| 141 | + |
| 142 | + next(error); |
| 143 | + } |
| 144 | + }); |
| 145 | + |
| 146 | + return router; |
| 147 | +} |
| 148 | + |
| 149 | +/** |
| 150 | + * Append AI assistant routes to Express app |
| 151 | + * |
| 152 | + * @param app - Express application instance |
| 153 | + */ |
| 154 | +export function appendAiAssistantRoutes(app: express.Application): void { |
| 155 | + app.use('/integration/ai', createAiStreamRouter()); |
| 156 | +} |
0 commit comments