Coverage for fastblocks / actions / gather / routes.py: 34%

196 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Route gathering functionality to replace scattered route discovery.""" 

2 

3import typing as t 

4from contextlib import suppress 

5from importlib import import_module 

6from pathlib import Path 

7 

8# Migration: ACB -> Oneiric 

9# Try to import Oneiric components first, fall back to ACB for compatibility 

10try: 

11 # Oneiric imports (new) 

12 from oneiric.adapters.discovery import get_adapters 

13 from oneiric.core.logging import get_logger 

14 from oneiric.core.resolution import Resolver 

15 

16 # Create debug function for Oneiric (using logger) 

17 def debug(msg): 

18 logger = get_logger("fastblocks.actions.gather.routes") 

19 logger.debug(msg) 

20 

21 # Create root_path equivalent for Oneiric 

22 root_path = Path(__file__).parent.parent.parent.parent 

23 

24 # Create depends equivalent for Oneiric 

25 _resolver = Resolver() 

26 _using_oneiric = True 

27except ImportError: 

28 # Fallback to ACB imports (legacy) 

29 # MIGRATED: Removed ACB import - using Oneiric equivalent 

30 # MIGRATED: Removed ACB import - debug import debug 

31 _using_oneiric = False 

32 

33from anyio import Path as AsyncPath 

34from starlette.routing import Host, Mount, Route, Router, WebSocketRoute 

35 

36from .strategies import GatherStrategy, gather_with_strategy 

37 

38RouteType = Route | Router | Mount | Host | WebSocketRoute 

39 

40 

41class RouteGatherResult: 

42 def __init__( 

43 self, 

44 *, 

45 routes: list[RouteType] | None = None, 

46 adapter_routes: dict[str, list[RouteType]] | None = None, 

47 base_routes: list[RouteType] | None = None, 

48 errors: list[Exception] | None = None, 

49 ) -> None: 

50 self.routes = routes if routes is not None else [] 

51 self.adapter_routes = adapter_routes if adapter_routes is not None else {} 

52 self.base_routes = base_routes if base_routes is not None else [] 

53 self.errors = errors if errors is not None else [] 

54 

55 @property 

56 def total_routes(self) -> int: 

57 return len(self.routes) 

58 

59 @property 

60 def has_errors(self) -> bool: 

61 return len(self.errors) > 0 

62 

63 def extend_routes(self, additional_routes: list[RouteType]) -> None: 

64 self.routes.extend(additional_routes) 

65 

66 

67async def gather_routes( 

68 *, 

69 sources: list[str] | None = None, 

70 patterns: list[str] | None = None, 

71 include_base: bool = True, 

72 include_adapters: bool = True, 

73 strategy: GatherStrategy | None = None, 

74) -> RouteGatherResult: 

75 if sources is None: 

76 sources = ["adapters", "base_routes"] 

77 

78 if patterns is None: 

79 patterns = ["_routes.py", "routes.py"] 

80 

81 if strategy is None: 

82 strategy = GatherStrategy() 

83 

84 result = RouteGatherResult() 

85 

86 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]] = [] 

87 

88 if "adapters" in sources and include_adapters: 

89 tasks.append(_gather_adapter_routes(patterns, strategy)) 

90 

91 if "base_routes" in sources and include_base: 

92 tasks.append(_gather_base_routes(patterns)) 

93 

94 if "custom" in sources: 

95 tasks.append(_gather_custom_routes(patterns, strategy)) 

96 

97 gather_result = await gather_with_strategy( 

98 tasks, 

99 strategy, 

100 cache_key=f"routes:{':'.join(sources)}:{':'.join(patterns)}", 

101 ) 

102 

103 for success in gather_result.success: 

104 if isinstance(success, dict): 

105 result.adapter_routes.update(success) 

106 for routes in success.values(): 

107 result.routes.extend(routes) 

108 elif isinstance(success, list): 

109 result.base_routes.extend(success) 

110 result.routes.extend(success) 

111 

112 result.errors.extend(gather_result.errors) 

113 

114 debug(f"Gathered {result.total_routes} routes from {len(sources)} sources") 

115 

116 return result 

117 

118 

119async def _gather_adapter_routes( 

120 patterns: list[str], 

121 strategy: GatherStrategy, 

122) -> dict[str, list[RouteType]]: 

123 adapter_routes: dict[str, list[RouteType]] = {} 

124 

125 for adapter in get_adapters(): 

126 await _process_adapter_routes(adapter, patterns, strategy, adapter_routes) 

127 

128 return adapter_routes 

129 

130 

131async def _process_adapter_routes( 

132 adapter: t.Any, 

133 patterns: list[str], 

134 strategy: GatherStrategy, 

135 adapter_routes: dict[str, list[RouteType]], 

136) -> None: 

137 adapter_name = adapter.name 

138 adapter_path = adapter.path.parent 

139 routes = [] 

140 

141 for pattern in patterns: 

142 routes_path = adapter_path / pattern 

143 

144 if await AsyncPath(routes_path).exists(): 

145 try: 

146 found_routes = await _extract_routes_from_file(routes_path) 

147 if found_routes: 

148 routes.extend(found_routes) 

149 debug( 

150 f"Found {len(found_routes)} routes in {adapter_name}/{pattern}", 

151 ) 

152 except Exception as e: 

153 debug(f"Error gathering routes from {adapter_name}/{pattern}: {e}") 

154 raise 

155 

156 if routes: 

157 adapter_routes[adapter_name] = routes 

158 

159 

160async def _gather_base_routes(patterns: list[str]) -> list[RouteType]: 

161 base_routes = [] 

162 for pattern in patterns: 

163 routes_path = root_path / pattern 

164 if await AsyncPath(routes_path).exists(): 

165 try: 

166 routes = await _extract_routes_from_file(Path(routes_path)) 

167 if routes: 

168 base_routes.extend(routes) 

169 debug(f"Found {len(routes)} base routes in {pattern}") 

170 except Exception as e: 

171 debug(f"Error gathering base routes from {pattern}: {e}") 

172 

173 return base_routes 

174 

175 

176async def _gather_custom_routes( 

177 patterns: list[str], 

178 strategy: GatherStrategy, 

179) -> list[RouteType]: 

180 custom_routes = [] 

181 

182 custom_paths = [ 

183 root_path / "app" / "routes.py", 

184 root_path / "custom" / "routes.py", 

185 root_path / "src" / "routes.py", 

186 ] 

187 

188 for custom_path in custom_paths: 

189 if await AsyncPath(custom_path).exists(): 

190 try: 

191 routes = await _extract_routes_from_file(Path(custom_path)) 

192 if routes: 

193 custom_routes.extend(routes) 

194 debug(f"Found {len(routes)} custom routes in {custom_path}") 

195 

196 except Exception as e: 

197 debug(f"Error gathering custom routes from {custom_path}: {e}") 

198 if strategy.error_strategy.value == "fail_fast": 

199 raise 

200 

201 return custom_routes 

202 

203 

204async def _extract_routes_from_file(file_path: Path) -> list[RouteType]: 

205 module_path = _get_module_path_from_file_path(file_path) 

206 debug(f"Extracting routes from {file_path} -> {module_path}") 

207 try: 

208 with suppress(ModuleNotFoundError, ImportError): 

209 module = import_module(module_path) 

210 return _extract_routes_from_module(module, module_path) 

211 except Exception as e: 

212 debug(f"Error extracting routes from {file_path}: {e}") 

213 raise 

214 

215 return [] 

216 

217 

218def _get_module_path_from_file_path(file_path: Path) -> str: 

219 depth = -2 

220 if "adapters" in file_path.parts: 

221 depth = -4 

222 return ".".join(file_path.parts[depth:]).removesuffix(".py") 

223 

224 

225def _extract_routes_from_module(module: t.Any, module_path: str) -> list[RouteType]: 

226 if not hasattr(module, "routes"): 

227 debug(f"No routes attribute found in {module_path}") 

228 return [] 

229 module_routes = module.routes 

230 if not isinstance(module_routes, list): 

231 debug(f"Routes attribute in {module_path} is not a list: {type(module_routes)}") 

232 return [] 

233 

234 return _validate_route_objects(module_routes) 

235 

236 

237def _validate_route_objects(module_routes: list[t.Any]) -> list[RouteType]: 

238 valid_routes = [] 

239 for route in module_routes: 

240 if isinstance(route, Route | Router | Mount | Host | WebSocketRoute): 

241 valid_routes.append(route) 

242 else: 

243 debug(f"Skipping invalid route object: {type(route)}") 

244 

245 return valid_routes 

246 

247 

248async def gather_route_patterns( 

249 route_objects: list[RouteType], 

250) -> dict[str, t.Any]: 

251 patterns: dict[str, t.Any] = { 

252 "total_routes": len(route_objects), 

253 "route_types": {}, 

254 "path_patterns": [], 

255 "methods": set(), 

256 "endpoints": set(), 

257 } 

258 

259 for route in route_objects: 

260 route_type = type(route).__name__ 

261 patterns["route_types"][route_type] = ( 

262 patterns["route_types"].get(route_type, 0) + 1 

263 ) 

264 

265 path = getattr(route, "path", None) 

266 if path is not None: 

267 patterns["path_patterns"].append(path) 

268 

269 methods = getattr(route, "methods", None) 

270 if methods is not None: 

271 patterns["methods"].update(methods) 

272 

273 endpoint = getattr(route, "endpoint", None) 

274 if endpoint is not None: 

275 endpoint_name = getattr(endpoint, "__name__", str(endpoint)) 

276 patterns["endpoints"].add(endpoint_name) 

277 

278 patterns["methods"] = list(patterns["methods"]) 

279 patterns["endpoints"] = list(patterns["endpoints"]) 

280 

281 return patterns 

282 

283 

284def create_default_routes() -> list[RouteType]: 

285 try: 

286 routes_module = __import__( 

287 "fastblocks.adapters.routes.default", 

288 fromlist=["Routes"], 

289 ) 

290 Routes = routes_module.Routes 

291 routes_instance = Routes() 

292 return [ 

293 Route("/favicon.ico", endpoint=routes_instance.favicon, methods=["GET"]), 

294 Route("/robots.txt", endpoint=routes_instance.robots, methods=["GET"]), 

295 ] 

296 except (ImportError, AttributeError) as e: 

297 debug(f"Error loading default routes: {e}") 

298 return [] 

299 

300 

301async def validate_routes(routes: list[RouteType]) -> dict[str, t.Any]: 

302 validation: dict[str, t.Any] = { 

303 "valid_routes": [], 

304 "invalid_routes": [], 

305 "warnings": [], 

306 "total_checked": len(routes), 

307 } 

308 path_patterns: set[str] = set() 

309 for route in routes: 

310 _validate_single_route(route, validation, path_patterns) 

311 

312 return validation 

313 

314 

315def _validate_single_route( 

316 route: RouteType, 

317 validation: dict[str, t.Any], 

318 path_patterns: set[str], 

319) -> None: 

320 try: 

321 path = getattr(route, "path", None) 

322 if path is None: 

323 validation["invalid_routes"].append( 

324 {"route": str(route), "error": "Missing path attribute"}, 

325 ) 

326 return 

327 

328 _check_route_path_duplicates(route, validation, path_patterns) 

329 _check_route_endpoint(route, validation) 

330 validation["valid_routes"].append(route) 

331 

332 except Exception as e: 

333 validation["invalid_routes"].append({"route": str(route), "error": str(e)}) 

334 

335 

336def _check_route_path_duplicates( 

337 route: RouteType, 

338 validation: dict[str, t.Any], 

339 path_patterns: set[str], 

340) -> None: 

341 path = getattr(route, "path", None) 

342 if path is not None: 

343 if path in path_patterns: 

344 validation["warnings"].append(f"Duplicate path: {path}") 

345 path_patterns.add(path) 

346 

347 

348def _check_route_endpoint(route: RouteType, validation: dict[str, t.Any]) -> None: 

349 endpoint = getattr(route, "endpoint", None) 

350 path = getattr(route, "path", "unknown") 

351 if hasattr(route, "endpoint") and endpoint is None: 

352 validation["warnings"].append(f"Route {path} has no endpoint")