Repository navigation
Feat/persist channel icons #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -56,6 +56,7 @@ server: | |
| ipa_cache_global_workers: 8 | ||
| ipa_cache_part_size: 8388608 | ||
| ipa_cache_max_mb: 1024 | ||
| icon_cache_dir: /data/icon-cache | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a user follows either README YAML snippet and changes Useful? React with 👍 / 👎. |
||
|
|
||
| channels: | ||
| - blatants | ||
|
|
@@ -96,9 +97,10 @@ server: | |
| ipa_cache_global_workers: 8 | ||
| ipa_cache_part_size: 8388608 | ||
| ipa_cache_max_mb: 1024 | ||
| icon_cache_dir: /data/icon-cache | ||
| ``` | ||
|
|
||
| `telegram.parallel_connections` (default 8) opens extra Telegram connections per download so large files bypass Telegram's per-connection speed cap; set `1` to disable. Source JSON is cached for `server.cache_seconds`. IPA downloads are cached under `server.ipa_cache_dir` after the first request. Range requests then serve from local disk instead of re-fetching the same bytes from Telegram. On cold range requests, `server.ipa_cache_workers` downloads cache parts concurrently using `server.ipa_cache_part_size` byte chunks. `server.ipa_cache_global_workers` caps total Telegram cache downloads across files. `server.ipa_cache_max_mb` (default 1024 MB, `0` disables) caps total cache disk usage; whenever a new file is cached, older files are automatically deleted until usage is under the limit. | ||
| `telegram.parallel_connections` (default 8) opens extra Telegram connections per download so large files bypass Telegram's per-connection speed cap; set `1` to disable. Source JSON is cached for `server.cache_seconds`. IPA downloads are cached under `server.ipa_cache_dir` after the first request. Range requests then serve from local disk instead of re-fetching the same bytes from Telegram. On cold range requests, `server.ipa_cache_workers` downloads cache parts concurrently using `server.ipa_cache_part_size` byte chunks. `server.ipa_cache_global_workers` caps total Telegram cache downloads across files. `server.ipa_cache_max_mb` (default 1024 MB, `0` disables) caps total cache disk usage; whenever a new file is cached, older files are automatically deleted until usage is under the limit. Channel icons are fetched once and saved under `server.icon_cache_dir` (default `/data/icon-cache`, empty disables disk storage); they are never refreshed. Failed fetches are not saved and are retried on the next request. | ||
|
|
||
| ### Config UI | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,7 +15,22 @@ server: | |
| ipa_cache_global_workers: 8 | ||
| ipa_cache_part_size: 8388608 | ||
| ipa_cache_max_mb: 1024 | ||
| icon_cache_dir: /data/icon-cache | ||
|
|
||
| channels: | ||
| - blatants | ||
| - dvntms | ||
| - blatants | ||
| - eeveespotifyrevived | ||
| - the_public_archive | ||
| - ethModsGroup | ||
| - compiledipas | ||
| - ciesIPAs | ||
| - riftysIPAlibrary | ||
| - ipastar | ||
| - Sa1y0miii | ||
| - IAppsBestLibrary | ||
| - ASJTweaks | ||
| - ethModsGroup | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Duplicate channel sources are published When a user starts from the example channel list, Remove the duplicate channel entry from the example configuration or deduplicate sources by channel identity. Also at Prompt for AI agentsIn `config.example.yml` at line 32:
**Duplicate channel sources are published**
When a user starts from the example channel list, `_load_sources` creates a source for each duplicate channel entry and only deduplicates slugs, so the same Telegram channel appears as two sources with duplicate content.
Remove the duplicate channel entry from the example configuration or deduplicate sources by channel identity.
Also at `config.example.yml:24`, `config.example.yml:33`. |
||
| - c/2162963305 | ||
| - isignspace | ||
| - lPAUniverse | ||
| - thescholarslounge | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,9 +29,7 @@ | |
| source_caches: dict[str, dict[str, object]] = { | ||
| source.slug: {"expires_at": 0.0, "value": None} for source in settings.sources | ||
| } | ||
| source_icon_caches: dict[str, dict[str, object]] = { | ||
| source.slug: {"expires_at": 0.0, "value": None} for source in settings.sources | ||
| } | ||
| source_icon_caches: dict[str, bytes] = {} | ||
| ipa_cache_locks: dict[str, asyncio.Lock] = {} | ||
| ipa_cache_lock_refs: dict[str, int] = {} | ||
| ipa_cache_global_semaphore = asyncio.Semaphore(settings.ipa_cache_global_workers) | ||
|
|
@@ -66,7 +64,7 @@ def _runtime_refresh() -> None: | |
| telegram.settings = settings | ||
| telegram._channel_entities.clear() | ||
| source_caches = {source.slug: {"expires_at": 0.0, "value": None} for source in settings.sources} | ||
| source_icon_caches = {source.slug: {"expires_at": 0.0, "value": None} for source in settings.sources} | ||
| source_icon_caches = {} | ||
| sources_by_slug = {source.slug: source for source in settings.sources} | ||
| ipa_cache_global_semaphore = asyncio.Semaphore(settings.ipa_cache_global_workers) | ||
|
|
||
|
|
@@ -436,18 +434,54 @@ def _icon_response(icon: bytes, request: Request) -> Response: | |
| return Response(content=icon, media_type=media_type, headers=headers) | ||
|
|
||
|
|
||
| def _icon_cache_path(source_slug: str) -> Path | None: | ||
| if not settings.icon_cache_dir: | ||
| return None | ||
| # Slugs are sanitised in settings to [A-Za-z0-9_-], so they are safe as filenames. | ||
| return Path(settings.icon_cache_dir) / f"{source_slug}.img" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Previous channel icon is served When a configuration change assigns an existing slug to a different channel, Key both memory and disk icon caches by a stable channel identity rather than the slug alone. Also at Prompt for AI agentsIn `src/main.py` at line 441:
**Previous channel icon is served**
When a configuration change assigns an existing slug to a different channel, `_source_channel_icon` reads the memory or disk cache by `source.slug` without checking channel identity, so the replacement channel receives the previous channel’s icon indefinitely.
Key both memory and disk icon caches by a stable channel identity rather than the slug alone.
Also at `src/main.py:474-476`, `src/main.py:483`. |
||
|
|
||
|
|
||
| def _read_icon_cache(path: Path | None) -> bytes | None: | ||
| if path is None or not path.is_file(): | ||
| return None | ||
| try: | ||
| data = path.read_bytes() | ||
| except OSError as exc: | ||
| logger.warning("Channel icon cache read failed for %s: %s", path.name, exc) | ||
| return None | ||
| return data or None | ||
|
|
||
|
|
||
| def _write_icon_cache(path: Path | None, icon: bytes) -> None: | ||
| if path is None: | ||
| return | ||
| temp_path = path.with_name(f".{path.name}.tmp") | ||
| try: | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| temp_path.write_bytes(icon) | ||
| temp_path.replace(path) | ||
| except OSError as exc: | ||
| logger.warning("Channel icon cache write failed for %s: %s", path.name, exc) | ||
| temp_path.unlink(missing_ok=True) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Cache write failure aborts icon request When writing the cache fails and removing the temporary file also fails, Guard or suppress errors from temporary-file cleanup in the write-error handler. Prompt for AI agentsIn `src/main.py` at line 465:
**Cache write failure aborts icon request**
When writing the cache fails and removing the temporary file also fails, `_write_icon_cache` catches the initial filesystem error but lets `temp_path.unlink` raise another `OSError`, so the request fails instead of returning the fetched icon.
Guard or suppress errors from temporary-file cleanup in the write-error handler. |
||
|
|
||
|
|
||
| async def _source_channel_icon(source) -> bytes | None: | ||
| cache = source_icon_caches.setdefault(source.slug, {"expires_at": 0.0, "value": None}) | ||
| now = monotonic() | ||
| if float(cache["expires_at"]) > now: | ||
| value = cache["value"] | ||
| return value if isinstance(value, bytes) else None | ||
| icon = None | ||
| # Icons are fetched once and kept forever (memory, then disk). Only successful | ||
| # fetches are stored, so a failed attempt is retried on the next request. | ||
| cached = source_icon_caches.get(source.slug) | ||
| if isinstance(cached, bytes): | ||
| return cached | ||
| path = _icon_cache_path(source.slug) | ||
| from_disk = _read_icon_cache(path) | ||
| if from_disk: | ||
| source_icon_caches[source.slug] = from_disk | ||
| return from_disk | ||
| if not await telegram.is_authorized(): | ||
| return None | ||
| icon = await telegram.download_channel_photo(source) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Concurrent requests fetch icons repeatedly When multiple requests for the same uncached source arrive before its first Telegram download finishes, Coalesce concurrent misses for each source behind a shared in-flight download. Also at Prompt for AI agentsIn `src/main.py` at line 481:
**Concurrent requests fetch icons repeatedly**
When multiple requests for the same uncached source arrive before its first Telegram download finishes, `_source_channel_icon` lets each cache-missing request call `telegram.download_channel_photo`, so concurrent requests duplicate Telegram downloads and writes; callers can receive different bytes and a later write can replace the cached icon.
Coalesce concurrent misses for each source behind a shared in-flight download.
Also at `src/main.py:471`. |
||
| cache["value"] = icon | ||
| cache["expires_at"] = now + 86400 | ||
| if icon: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Failed icon fetches retry on every request When a channel has no downloadable photo or Telegram keeps failing while clients request its icon, Apply a bounded negative-cache or retry-backoff interval to failed icon fetches. Prompt for AI agentsIn `src/main.py` at line 482:
**Failed icon fetches retry on every request**
When a channel has no downloadable photo or Telegram keeps failing while clients request its icon, `_source_channel_icon()` records only truthy results, so a missing photo or failed Telegram download leaves no cache entry; each subsequent icon request repeats the upstream call, while `download_channel_photo()` suppresses download exceptions and the route returns the fallback icon.
Apply a bounded negative-cache or retry-backoff interval to failed icon fetches. |
||
| source_icon_caches[source.slug] = icon | ||
| _write_icon_cache(path, icon) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Icon cache can fill shared disk When many configured channels have their icons requested over time, Bound the icon cache with a size limit and eviction policy. Prompt for AI agentsIn `src/main.py` at line 484:
**Icon cache can fill shared disk**
When many configured channels have their icons requested over time, `_write_icon_cache` stores successful icons without a size limit or eviction, so the cache can fill `/data`, which is also used for the Telegram session and IPA cache, and disrupt the service.
Bound the icon cache with a size limit and eviction policy.
Comment on lines
+483
to
+484
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Refresh stores an old channel icon When the config UI replaces a channel with another channel using the same slug while the old channel’s icon request is awaiting Telegram, the in-flight request retains its old Before caching a fetched icon, verify that the current source for the slug still has the same channel identity as the request’s source. Prompt for AI agentsIn `src/main.py` at lines 483-484:
**Refresh stores an old channel icon**
When the config UI replaces a channel with another channel using the same slug while the old channel’s icon request is awaiting Telegram, the in-flight request retains its old `source`, but after `_runtime_refresh` replaces the global cache and settings, the request stores that old icon under the slug in the new cache and may write it to the new cache directory. A replacement channel reusing that slug is served the old channel’s icon.
Before caching a fetched icon, verify that the current source for the slug still has the same channel identity as the request’s source. |
||
| return icon | ||
|
|
||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium · Documented cache path is ignored
When a user follows either README configuration example to customize or disable icon storage,
load_settingsreadsserver.icon_cache_dir, but the examples placeicon_cache_dirat the YAML root, so the custom path or empty value is ignored and the default directory is used.Place
icon_cache_dirunderserverin both README configuration examples.Also at
README.md:100.Prompt for AI agents