Coverage for fastblocks / adapters / sitemap / core.py: 22%
161 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"""FastBlocks Sitemap Core Implementation.
3Core sitemap functionality moved from standalone module to adapter pattern.
4Based on asgi-sitemaps by Florian Dahlitz with FastBlocks enhancements.
6Original asgi-sitemaps library:
7- Author: Florian Dahlitz
8- Repository: https://github.com/DahlitzFlorian/asgi-sitemaps
9- License: MIT
10"""
12import contextvars
13import datetime as dt
14import inspect
15import typing as t
16from collections.abc import (
17 AsyncIterable,
18 AsyncIterator,
19 Awaitable,
20 Callable,
21 Iterable,
22 Sequence,
23)
24from typing import TypeVar, cast
25from urllib.parse import urljoin, urlsplit
28# Custom implementations for ACB compatibility
29def debug(msg: str) -> None:
30 """Custom debug function for Oneiric compatibility."""
31 print(f"[DEBUG] {msg}")
34from oneiric.core.resolution import Resolver
36# Oneiric resolver for dependency injection
37depends = Resolver()
39if t.TYPE_CHECKING:
40 from starlette.types import Scope
42T = TypeVar("T")
43ItemsTypes = Iterable[T] | Awaitable[Iterable[T]] | AsyncIterable[T]
45SCOPE_CTX_VAR = contextvars.ContextVar["Scope"]("fastblocks.sitemaps.scope")
48class BaseSitemap[T]:
49 protocol: str = "auto"
51 def __init__(self) -> None:
52 if self.protocol not in ("http", "https", "auto"):
53 raise ValueError(f"Invalid protocol: {self.protocol}")
54 debug(f"BaseSitemap: Initialized with protocol={self.protocol}")
56 def items(self) -> ItemsTypes[T]:
57 raise NotImplementedError("Subclasses must implement items() method")
59 def location(self, item: T) -> str:
60 raise NotImplementedError("Subclasses must implement location() method")
62 def lastmod(self, item: T) -> dt.datetime | None:
63 return None
65 def changefreq(self, item: T) -> str | None:
66 return None
68 def priority(self, item: T) -> float:
69 return 0.5
71 @property
72 def scope(self) -> "Scope":
73 try:
74 return SCOPE_CTX_VAR.get()
75 except LookupError as e:
76 raise RuntimeError(
77 "Scope accessed outside of an ASGI request. "
78 "Ensure sitemap generation happens within request context."
79 ) from e
82class SitemapApp:
83 def __init__(
84 self,
85 sitemaps: BaseSitemap[t.Any] | list[BaseSitemap[t.Any]],
86 *,
87 domain: str,
88 cache_ttl: int = 3600,
89 ) -> None:
90 self._sitemaps = (
91 [sitemaps] if isinstance(sitemaps, BaseSitemap) else list(sitemaps)
92 )
93 self._domain = domain
94 self._cache_ttl = cache_ttl
95 debug(
96 f"SitemapApp: Initialized with {len(self._sitemaps)} sitemaps, domain={domain}"
97 )
99 async def __call__(
100 self,
101 scope: "Scope",
102 receive: Callable[[], Awaitable[dict[str, t.Any]]],
103 send: Callable[[dict[str, t.Any]], Awaitable[None]],
104 ) -> None:
105 if scope["type"] != "http":
106 await self._send_error(send, 404)
107 return
109 debug(
110 f"SitemapApp: Processing sitemap request for {scope.get('path', 'unknown')}"
111 )
113 try:
114 content = await generate_sitemap(
115 self._sitemaps, scope=scope, domain=self._domain
116 )
118 headers = [
119 [b"content-type", b"application/xml; charset=utf-8"],
120 [b"content-length", str(len(content)).encode()],
121 [b"cache-control", f"public, max-age={self._cache_ttl}".encode()],
122 ]
124 message = await receive()
125 if message["type"] != "http.request":
126 await self._send_error(send, 400)
127 return
129 await send(
130 {"type": "http.response.start", "status": 200, "headers": headers}
131 )
132 await send({"type": "http.response.body", "body": content})
134 debug(f"SitemapApp: Sent sitemap response ({len(content)} bytes)")
136 except Exception as e:
137 debug(f"SitemapApp: Error generating sitemap: {e}")
138 await self._send_error(send, 500)
140 async def _send_error(
141 self, send: Callable[[dict[str, t.Any]], Awaitable[None]], status: int
142 ) -> None:
143 await send(
144 {
145 "type": "http.response.start",
146 "status": status,
147 "headers": [[b"content-type", b"text/plain"]],
148 }
149 )
150 await send(
151 {
152 "type": "http.response.body",
153 "body": f"Error {status}".encode(),
154 }
155 )
158async def generate_sitemap(
159 sitemaps: Sequence[BaseSitemap[t.Any]], *, scope: "Scope", domain: str
160) -> bytes:
161 debug(f"generate_sitemap: Starting generation for {len(sitemaps)} sitemaps")
163 SCOPE_CTX_VAR.set(scope)
165 cache_key = f"fastblocks:sitemap:{domain}"
166 cached_content = await _get_cached_sitemap(cache_key)
167 if cached_content:
168 debug("generate_sitemap: Returning cached sitemap")
169 return cached_content
171 try:
172 content = await _generate_sitemap_content(sitemaps, scope=scope, domain=domain)
174 await _cache_sitemap(cache_key, content)
176 debug(f"generate_sitemap: Generated {len(content)} bytes")
177 return content
179 except Exception as e:
180 debug(f"generate_sitemap: Error during generation: {e}")
181 raise
184async def _generate_sitemap_content(
185 sitemaps: Sequence[BaseSitemap[t.Any]], *, scope: "Scope", domain: str
186) -> bytes:
187 async def _lines() -> AsyncIterator[bytes]:
188 yield b'<?xml version="1.0" encoding="utf-8"?>'
189 yield b'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
190 total_urls = 0
191 for sitemap_idx, sitemap in enumerate(sitemaps):
192 debug(
193 f"generate_sitemap: Processing sitemap {sitemap_idx + 1}/{len(sitemaps)}"
194 )
195 try:
196 async for item in _ensure_async_iterator(sitemap.items()):
197 yield 4 * b" " + b"<url>"
198 fields = get_fields(sitemap, item, scope=scope, domain=domain)
199 for name, value in fields.items():
200 escaped_value = _escape_xml(value)
201 yield 8 * b" " + f"<{name}>{escaped_value}</{name}>".encode()
202 yield 4 * b" " + b"</url>"
203 total_urls += 1
204 except Exception as e:
205 debug(f"generate_sitemap: Error processing sitemap {sitemap_idx}: {e}")
206 yield b"</urlset>"
207 debug(f"generate_sitemap: Generated {total_urls} URLs")
209 return b"\n".join([line async for line in _lines()])
212async def _ensure_async_iterator[T](items: ItemsTypes[T]) -> AsyncIterator[T]:
213 try:
214 if hasattr(items, "__aiter__"):
215 items_async = cast(AsyncIterable[T], items)
216 async for item in items_async:
217 yield item
218 elif inspect.isawaitable(items):
219 items_awaitable = items
220 resolved_items = await items_awaitable
221 for item in resolved_items:
222 yield item
223 else:
224 items_sync = items
225 for item in items_sync:
226 yield item
227 except Exception as e:
228 debug(f"_ensure_async_iterator: Error processing items: {e}")
231def get_fields(
232 sitemap: BaseSitemap[T], item: T, *, scope: "Scope", domain: str
233) -> dict[str, str]:
234 if sitemap.protocol == "auto":
235 protocol = scope.get("scheme", "https")
236 else:
237 protocol = sitemap.protocol
239 try:
240 location = sitemap.location(item)
241 lastmod = sitemap.lastmod(item)
242 changefreq = sitemap.changefreq(item)
243 priority = sitemap.priority(item)
245 parsed_location = urlsplit(location)
246 if parsed_location.scheme or parsed_location.netloc:
247 raise ValueError(f"Location contains scheme or domain: {location}")
249 fields: dict[str, str] = {}
251 fields["loc"] = urljoin(f"{protocol}://{domain}", location)
253 if lastmod is not None:
254 fields["lastmod"] = lastmod.strftime("%Y-%m-%d")
255 if changefreq is not None:
256 fields["changefreq"] = changefreq
258 priority_value = max(0.0, min(1.0, priority))
259 fields["priority"] = f"{priority_value:.1f}"
261 return fields
263 except Exception as e:
264 debug(f"get_fields: Error processing item {item}: {e}")
265 return {"loc": urljoin(f"{protocol}://{domain}", "/"), "priority": "0.5"}
268def _escape_xml(value: str) -> str:
269 return (
270 value.replace("&", "&")
271 .replace("<", "<")
272 .replace(">", ">")
273 .replace('"', """)
274 .replace("'", "'")
275 )
278async def _get_cached_sitemap(cache_key: str) -> bytes | None:
279 try:
280 cache = await depends.resolve("fastblocks", "cache")
281 if cache and hasattr(cache, "get"):
282 cached_data = await cache.get(cache_key)
283 if cached_data:
284 debug(f"_get_cached_sitemap: Cache hit for {cache_key}")
285 return (
286 cached_data
287 if isinstance(cached_data, bytes)
288 else cached_data.encode()
289 )
290 except Exception as e:
291 debug(f"_get_cached_sitemap: Cache error: {e}")
293 return None
296async def _cache_sitemap(cache_key: str, content: bytes) -> None:
297 try:
298 cache = await depends.resolve("fastblocks", "cache")
299 if cache and hasattr(cache, "set"):
300 await cache.set(cache_key, content, ttl=3600)
301 debug(f"_cache_sitemap: Cached sitemap ({len(content)} bytes)")
302 except Exception as e:
303 debug(f"_cache_sitemap: Cache error: {e}")