Coverage for fastblocks / adapters / app / default.py: 39%
189 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Default App Adapter for FastBlocks.
3Provides the main FastBlocks application instance with lifecycle management,
4startup/shutdown sequences, and adapter integration.
6Author: lesleslie <les@wedgwoodwebworks.com>
7Created: 2025-01-12
8"""
10import typing as t
11from base64 import b64encode
12from contextlib import asynccontextmanager, suppress
13from time import perf_counter
14from uuid import UUID
16# Oneiric imports
17from oneiric.core.resolution import Resolver
18from starlette.types import ASGIApp, Receive, Scope, Send
19from fastblocks.applications import FastBlocks
21from ._base import AppBase, AppBaseSettings
23# Custom Oneiric-compatible adapter system
24depends = Resolver()
25_using_oneiric = True
27main_start = perf_counter()
28Cache = Storage = None
31class AppSettings(AppBaseSettings):
32 url: str = "http://localhost:8000"
33 token_id: str | None = "_fb_"
35 def __init__(self, **data: t.Any) -> None:
36 super().__init__(**data)
37 # Note: URL configuration moved to runtime initialization
38 # to avoid coroutine access in __init__
39 token_prefix = self.token_id or "_fb_"
40 self.token_id = "".join(
41 [token_prefix, b64encode(self.name.encode()).decode().rstrip("=")],
42 )
45class FastBlocksApp(FastBlocks):
46 def __init__(self, **kwargs: t.Any) -> None:
47 super().__init__(lifespan=self.lifespan, **kwargs)
49 async def init(self) -> None:
50 pass
52 def _get_startup_time(self) -> float:
53 startup_time = getattr(self, "_startup_time", None)
54 if startup_time is None or startup_time <= 0:
55 import time
57 init_start = getattr(self, "_init_start_time", None)
58 startup_time = time.time() - init_start if init_start else 0.001
59 return startup_time
61 def _get_debug_enabled(self, config: t.Any) -> list[str]:
62 debug_enabled = []
63 if hasattr(config, "debug"):
64 for key, value in vars(config.debug).items():
65 if value and key != "production":
66 debug_enabled.append(key)
67 return debug_enabled
69 def _get_color_constants(self) -> dict[str, str]:
70 return {
71 "GREEN": "\033[92m",
72 "BLUE": "\033[94m",
73 "YELLOW": "\033[93m",
74 "CYAN": "\033[96m",
75 "RESET": "\033[0m",
76 "BOLD": "\033[1m",
77 }
79 def _format_info_lines(
80 self,
81 config: t.Any,
82 colors: dict[str, str],
83 debug_enabled: list[str],
84 startup_time: float,
85 ) -> list[str]:
86 app_title = getattr(config.app, "title", "Welcome to FastBlocks")
87 app_domain = getattr(config.app, "domain", "localhost")
88 debug_str = ", ".join(debug_enabled) if debug_enabled else "disabled"
90 return [
91 f"{colors['CYAN']}{colors['BOLD']}{app_title}{colors['RESET']}",
92 f"{colors['BLUE']}Domain: {app_domain}{colors['RESET']}",
93 f"{colors['YELLOW']}Debug: {debug_str}{colors['RESET']}",
94 f"{colors['YELLOW']}══════════════════════════════════════════════════{colors['RESET']}",
95 f"{colors['GREEN']}🚀 FastBlocks Application Ready{colors['RESET']}",
96 f"{colors['YELLOW']}⚡ Startup time: {startup_time * 1000:.2f}ms{colors['RESET']}",
97 f"{colors['CYAN']}🌐 Server running on http://127.0.0.1:8000{colors['RESET']}",
98 f"{colors['YELLOW']}══════════════════════════════════════════════════{colors['RESET']}",
99 ]
101 def _clean_and_center_line(self, line: str, colors: dict[str, str]) -> str:
102 line_clean = line
103 for color in colors.values():
104 line_clean = line_clean.replace(color, "")
105 line_width = len(line_clean)
106 padding = max(0, (90 - line_width) // 2)
107 return " " * padding + line
109 async def _display_fancy_startup(self) -> None:
110 # MIGRATED: Removed ACB import - using Oneiric equivalent
111 from aioconsole import aprint
112 from pyfiglet import Figlet
114 config = await depends.resolve("fastblocks", "config")
115 app_name = getattr(config.app, "name", "FastBlocks")
116 startup_time = self._get_startup_time()
117 debug_enabled = self._get_debug_enabled(config)
118 colors = self._get_color_constants()
119 banner = Figlet(font="slant", width=90, justify="center").renderText(
120 app_name.upper(),
121 )
122 await aprint(f"\n\n{banner}\n")
123 info_lines = self._format_info_lines(
124 config,
125 colors,
126 debug_enabled,
127 startup_time,
128 )
129 for line in info_lines:
130 self._clean_and_center_line(line, colors)
132 async def _display_simple_startup(self) -> None:
133 from contextlib import suppress
135 with suppress(Exception):
136 # MIGRATED: Removed ACB import - using Oneiric equivalent
138 config = await depends.resolve("fastblocks", "config")
139 getattr(config.app, "name", "FastBlocks")
140 self._get_startup_time()
142 async def post_startup(self) -> None:
143 try:
144 await self._display_fancy_startup()
145 except Exception:
146 await self._display_simple_startup()
148 @asynccontextmanager
149 async def lifespan(self, app: "FastBlocks") -> t.AsyncIterator[None]:
150 try:
151 logger = getattr(self, "logger", None)
152 if logger:
153 logger.info("FastBlocks application starting up")
154 except Exception as e:
155 logger = getattr(self, "logger", None)
156 if logger:
157 logger.exception(f"Error during startup: {e}")
158 raise
159 yield
160 logger = getattr(self, "logger", None)
161 if logger:
162 logger.info("FastBlocks application shutting down")
165class App(AppBase):
166 settings: AppSettings | None = None
167 router: t.Any = None
168 middleware_manager: t.Any = None
169 templates: t.Any = None
170 models: t.Any = None
171 exception_handlers: t.Any = None
172 middleware_stack: t.Any = None
173 user_middleware: t.Any = None
174 fastblocks_app: t.Any = None
176 def __init__(self, **kwargs: t.Any) -> None:
177 super().__init__(**kwargs)
178 self.settings = AppSettings()
179 self.fastblocks_app = FastBlocksApp()
180 self.router = None
181 self.middleware_manager = None
182 self.templates = None
183 self.models = None
184 self.exception_handlers = {}
185 self.middleware_stack = None
186 self.user_middleware = []
187 self.state = None
189 @property
190 def logger(self) -> t.Any:
191 if hasattr(super(), "logger"):
192 with suppress(Exception):
193 return super().logger
194 # For Oneiric, we'll use a simpler approach
195 # In practice, this would be replaced with actual logger resolution
196 import logging
198 return logging.getLogger(self.__class__.__name__)
200 @logger.setter
201 def logger(self, value: t.Any) -> None:
202 pass
204 @logger.deleter
205 def logger(self) -> None:
206 pass
208 async def init(self) -> None:
209 import time
211 self._init_start_time = time.time()
212 await self.fastblocks_app.init()
213 # For Oneiric, we'll use a simpler approach
214 # In practice, this would be replaced with actual dependency resolution
215 self.templates = None # Placeholder - would use actual templates
216 self.models = None # Placeholder - would use actual models
217 self.router = None # Placeholder - would use actual routes
218 self.middleware_manager = None
219 self.exception_handlers = self.fastblocks_app.exception_handlers
220 self.middleware_stack = self.fastblocks_app.middleware_stack
221 self.user_middleware = self.fastblocks_app.user_middleware
222 self.state = self.fastblocks_app.state
223 import time
225 self._startup_time = time.time() - self._init_start_time
226 self.fastblocks_app._startup_time = self._startup_time
227 self.fastblocks_app._init_start_time = self._init_start_time
228 await self.post_startup()
230 def __call__(self, scope: Scope, receive: Receive, send: Send) -> ASGIApp:
231 return t.cast(ASGIApp, self.fastblocks_app(scope, receive, send))
233 def __getattr__(self, name: str) -> t.Any:
234 return getattr(self.fastblocks_app, name)
236 async def post_startup(self) -> None:
237 await self.fastblocks_app.post_startup()
239 async def _setup_admin_adapter(self, app: FastBlocks) -> None:
240 # For Oneiric, we'll use a simpler approach
241 # In practice, this would be replaced with actual admin setup
242 # Placeholder - would use actual admin, sql, auth resolution
243 pass
245 async def _startup_sequence(self, app: FastBlocks) -> None:
246 await self._setup_admin_adapter(app)
247 await self.post_startup()
248 main_start_time = perf_counter() - main_start
249 self.logger.warning(f"App started in {main_start_time} s")
251 async def _shutdown_logger(self) -> None:
252 import asyncio
254 completer = None
255 if hasattr(self.logger, "complete"):
256 completer = self.logger.complete()
257 elif hasattr(self.logger, "stop"):
258 completer = self.logger.stop()
259 if completer:
260 await asyncio.wait_for(completer, timeout=1.0)
262 def _cancel_remaining_tasks(self) -> None:
263 import asyncio
265 loop = asyncio.get_event_loop()
266 tasks = [t for t in asyncio.all_tasks(loop) if not t.done()]
267 if tasks:
268 self.logger.debug(f"Cancelling {len(tasks)} remaining tasks")
269 for task in tasks:
270 task.cancel()
272 @asynccontextmanager
273 async def lifespan(self, app: FastBlocks) -> t.AsyncIterator[None]:
274 try:
275 await self._startup_sequence(app)
276 except Exception as e:
277 self.logger.exception(f"Error during startup: {e}")
278 raise
279 yield
280 self.logger.critical("Application shut down")
281 try:
282 await self._shutdown_logger()
283 except TimeoutError:
284 self.logger.warning("Logger completion timed out, forcing shutdown")
285 except Exception as e:
286 self.logger.exception(f"Logger completion failed: {e}")
287 finally:
288 with suppress(Exception):
289 self._cancel_remaining_tasks()
292MODULE_ID = UUID("01937d86-8f6e-7f70-c231-5678901234ef")
293MODULE_STATUS = "STABLE" # Oneiric-compatible status
295# Note: depends.register(App) removed as Oneiric expects different object types
296# In practice, this would be replaced with proper Oneiric registration