Main aiohttp server implementation for NLWeb
| 30 | |
| 31 | |
| 32 | class AioHTTPServer: |
| 33 | """Main aiohttp server implementation for NLWeb""" |
| 34 | |
| 35 | def __init__(self, config_path: str | None = None): |
| 36 | if config_path is None: |
| 37 | config_path = "config/config_webserver.yaml" |
| 38 | self.config = self._load_config(config_path) |
| 39 | self.app: web.Application | None = None |
| 40 | self.runner: web.AppRunner | None = None |
| 41 | self.site: web.TCPSite | None = None |
| 42 | self.record_file: str | None = None |
| 43 | |
| 44 | def _load_config(self, config_path: str) -> dict[str, Any]: |
| 45 | """Load configuration from YAML file""" |
| 46 | base_path = Path(__file__).parent.parent.parent.parent |
| 47 | config_file = base_path / config_path |
| 48 | |
| 49 | if not config_file.exists(): |
| 50 | logger.warning(f"Config file not found at {config_file}, using defaults") |
| 51 | return self._get_default_config() |
| 52 | |
| 53 | with open(config_file) as f: |
| 54 | config = yaml.safe_load(f) |
| 55 | |
| 56 | # Override with environment variables |
| 57 | config['port'] = int(os.environ.get('PORT', config.get('port', 8000))) |
| 58 | |
| 59 | # Azure App Service specific |
| 60 | if os.environ.get('WEBSITE_SITE_NAME'): |
| 61 | config['server']['host'] = '0.0.0.0' |
| 62 | logger.info("Running in Azure App Service mode") |
| 63 | |
| 64 | return config |
| 65 | |
| 66 | def _get_default_config(self) -> dict[str, Any]: |
| 67 | """Get default configuration""" |
| 68 | return { |
| 69 | 'port': 8000, |
| 70 | 'static_directory': '../static', |
| 71 | 'mode': 'development', |
| 72 | 'server': { |
| 73 | 'host': '0.0.0.0', |
| 74 | 'enable_cors': True, |
| 75 | 'max_connections': 100, |
| 76 | 'timeout': 30, |
| 77 | 'ssl': { |
| 78 | 'enabled': False, |
| 79 | 'cert_file_env': 'SSL_CERT_FILE', |
| 80 | 'key_file_env': 'SSL_KEY_FILE' |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | def _setup_ssl_context(self) -> ssl.SSLContext | None: |
| 86 | """Setup SSL context if enabled""" |
| 87 | ssl_config = self.config.get('server', {}).get('ssl', {}) |
| 88 | |
| 89 | if not ssl_config.get('enabled', False): |