|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:io'; |
| 4 | +import 'package:shelf/shelf.dart' as shelf; |
| 5 | +import 'package:shelf/shelf_io.dart' as shelf_io; |
| 6 | +import 'package:shelf_router/shelf_router.dart'; |
| 7 | +import 'package:opencli_daemon/core/request_router.dart'; |
| 8 | +import 'package:opencli_daemon/ipc/ipc_protocol.dart'; |
| 9 | +import 'package:opencli_daemon/api/api_translator.dart'; |
| 10 | +import 'package:opencli_daemon/api/message_handler.dart'; |
| 11 | + |
| 12 | +/// Unified API server on port 9529 for Web UI integration |
| 13 | +/// |
| 14 | +/// Provides HTTP REST API that bridges to the existing RequestRouter, |
| 15 | +/// allowing Web UI to execute commands and methods via HTTP. |
| 16 | +class UnifiedApiServer { |
| 17 | + final RequestRouter _requestRouter; |
| 18 | + final MessageHandler _messageHandler; |
| 19 | + final int port; |
| 20 | + HttpServer? _server; |
| 21 | + |
| 22 | + UnifiedApiServer({ |
| 23 | + required RequestRouter requestRouter, |
| 24 | + required MessageHandler messageHandler, |
| 25 | + this.port = 9529, |
| 26 | + }) : _requestRouter = requestRouter, |
| 27 | + _messageHandler = messageHandler; |
| 28 | + |
| 29 | + Future<void> start() async { |
| 30 | + final router = Router(); |
| 31 | + |
| 32 | + // POST /api/v1/execute - Main execution endpoint |
| 33 | + router.post('/api/v1/execute', _handleExecute); |
| 34 | + |
| 35 | + // GET /api/v1/status - Status proxy |
| 36 | + router.get('/api/v1/status', _handleStatus); |
| 37 | + |
| 38 | + // GET /health - Health check |
| 39 | + router.get('/health', _handleHealth); |
| 40 | + |
| 41 | + // WebSocket /ws - Real-time messaging |
| 42 | + router.get('/ws', _messageHandler.handler); |
| 43 | + |
| 44 | + final handler = const shelf.Pipeline() |
| 45 | + .addMiddleware(shelf.logRequests()) |
| 46 | + .addMiddleware(_corsMiddleware()) |
| 47 | + .addMiddleware(_errorHandlingMiddleware()) |
| 48 | + .addHandler(router.call); |
| 49 | + |
| 50 | + try { |
| 51 | + _server = await shelf_io.serve( |
| 52 | + handler, |
| 53 | + InternetAddress.loopbackIPv4, |
| 54 | + port, |
| 55 | + ); |
| 56 | + print( |
| 57 | + '✓ Unified API server listening on http://localhost:${_server!.port}'); |
| 58 | + print( |
| 59 | + ' - Execute API: POST http://localhost:${_server!.port}/api/v1/execute'); |
| 60 | + print(' - WebSocket: ws://localhost:${_server!.port}/ws'); |
| 61 | + } catch (e) { |
| 62 | + print('⚠️ Failed to start unified API server: $e'); |
| 63 | + rethrow; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + Future<void> stop() async { |
| 68 | + await _server?.close(force: true); |
| 69 | + _server = null; |
| 70 | + } |
| 71 | + |
| 72 | + /// Handle POST /api/v1/execute |
| 73 | + /// |
| 74 | + /// Expected request body: {"method": "...", "params": [...], "context": {...}} |
| 75 | + /// Returns: {"success": true/false, "result": "...", ...} |
| 76 | + Future<shelf.Response> _handleExecute(shelf.Request request) async { |
| 77 | + final startTime = DateTime.now(); |
| 78 | + |
| 79 | + try { |
| 80 | + // Parse JSON body |
| 81 | + final body = await request.readAsString(); |
| 82 | + |
| 83 | + if (body.isEmpty) { |
| 84 | + return shelf.Response.badRequest( |
| 85 | + body: jsonEncode( |
| 86 | + ApiTranslator.errorToHttp('Empty request body', null), |
| 87 | + ), |
| 88 | + headers: {'Content-Type': 'application/json'}, |
| 89 | + ); |
| 90 | + } |
| 91 | + |
| 92 | + final json = jsonDecode(body) as Map<String, dynamic>; |
| 93 | + |
| 94 | + // Validate required fields |
| 95 | + if (!json.containsKey('method')) { |
| 96 | + return shelf.Response.badRequest( |
| 97 | + body: jsonEncode( |
| 98 | + ApiTranslator.errorToHttp('Missing required field: method', null), |
| 99 | + ), |
| 100 | + headers: {'Content-Type': 'application/json'}, |
| 101 | + ); |
| 102 | + } |
| 103 | + |
| 104 | + // Convert to IpcRequest |
| 105 | + final ipcRequest = ApiTranslator.httpToIpcRequest(json); |
| 106 | + |
| 107 | + // Route through RequestRouter |
| 108 | + final result = await _requestRouter.route(ipcRequest); |
| 109 | + |
| 110 | + // Calculate duration |
| 111 | + final duration = |
| 112 | + DateTime.now().difference(startTime).inMicroseconds; |
| 113 | + |
| 114 | + // Build response |
| 115 | + final ipcResponse = IpcResponse( |
| 116 | + success: true, |
| 117 | + result: result, |
| 118 | + durationUs: duration, |
| 119 | + cached: false, |
| 120 | + requestId: ipcRequest.requestId, |
| 121 | + ); |
| 122 | + |
| 123 | + // Convert back to HTTP JSON |
| 124 | + final responseJson = ApiTranslator.ipcResponseToHttp(ipcResponse); |
| 125 | + |
| 126 | + return shelf.Response.ok( |
| 127 | + jsonEncode(responseJson), |
| 128 | + headers: {'Content-Type': 'application/json'}, |
| 129 | + ); |
| 130 | + } on FormatException catch (e) { |
| 131 | + return shelf.Response.badRequest( |
| 132 | + body: jsonEncode( |
| 133 | + ApiTranslator.errorToHttp('Invalid JSON: ${e.message}', null), |
| 134 | + ), |
| 135 | + headers: {'Content-Type': 'application/json'}, |
| 136 | + ); |
| 137 | + } catch (e, stack) { |
| 138 | + print('Execute error: $e\n$stack'); |
| 139 | + final errorJson = ApiTranslator.errorToHttp(e.toString(), null); |
| 140 | + return shelf.Response.internalServerError( |
| 141 | + body: jsonEncode(errorJson), |
| 142 | + headers: {'Content-Type': 'application/json'}, |
| 143 | + ); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /// Handle GET /api/v1/status |
| 148 | + Future<shelf.Response> _handleStatus(shelf.Request request) async { |
| 149 | + final status = { |
| 150 | + 'status': 'running', |
| 151 | + 'version': '0.1.0', |
| 152 | + 'timestamp': DateTime.now().toIso8601String(), |
| 153 | + }; |
| 154 | + |
| 155 | + return shelf.Response.ok( |
| 156 | + jsonEncode(status), |
| 157 | + headers: {'Content-Type': 'application/json'}, |
| 158 | + ); |
| 159 | + } |
| 160 | + |
| 161 | + /// Handle GET /health |
| 162 | + Future<shelf.Response> _handleHealth(shelf.Request request) async { |
| 163 | + return shelf.Response.ok('OK'); |
| 164 | + } |
| 165 | + |
| 166 | + /// CORS middleware for Web UI access |
| 167 | + shelf.Middleware _corsMiddleware() { |
| 168 | + return (shelf.Handler handler) { |
| 169 | + return (shelf.Request request) async { |
| 170 | + if (request.method == 'OPTIONS') { |
| 171 | + return shelf.Response.ok('', headers: _corsHeaders); |
| 172 | + } |
| 173 | + |
| 174 | + final response = await handler(request); |
| 175 | + return response.change(headers: _corsHeaders); |
| 176 | + }; |
| 177 | + }; |
| 178 | + } |
| 179 | + |
| 180 | + Map<String, String> get _corsHeaders => { |
| 181 | + 'Access-Control-Allow-Origin': '*', |
| 182 | + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', |
| 183 | + 'Access-Control-Allow-Headers': 'Content-Type', |
| 184 | + }; |
| 185 | + |
| 186 | + /// Error handling middleware |
| 187 | + shelf.Middleware _errorHandlingMiddleware() { |
| 188 | + return (shelf.Handler handler) { |
| 189 | + return (shelf.Request request) async { |
| 190 | + try { |
| 191 | + return await handler(request); |
| 192 | + } catch (e, stack) { |
| 193 | + print('API Error: $e\n$stack'); |
| 194 | + return shelf.Response.internalServerError( |
| 195 | + body: jsonEncode({'error': e.toString()}), |
| 196 | + headers: {'Content-Type': 'application/json'}, |
| 197 | + ); |
| 198 | + } |
| 199 | + }; |
| 200 | + }; |
| 201 | + } |
| 202 | +} |
0 commit comments