Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

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_settings reads server.icon_cache_dir, but the examples place icon_cache_dir at the YAML root, so the custom path or empty value is ignored and the default directory is used.

Place icon_cache_dir under server in both README configuration examples.

Also at README.md:100.

Prompt for AI agents
In `README.md` at line 59:

**Documented cache path is ignored**

When a user follows either README configuration example to customize or disable icon storage, `load_settings` reads `server.icon_cache_dir`, but the examples place `icon_cache_dir` at the YAML root, so the custom path or empty value is ignored and the default directory is used.

Place `icon_cache_dir` under `server` in both README configuration examples.

Also at `README.md:100`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Nest the cache option under server

When a user follows either README YAML snippet and changes icon_cache_dir to customize or disable storage, this root-level key is ignored: load_settings() reads only server.icon_cache_dir, so the app silently keeps using the default. Indent the option under server: in both snippets.

Useful? React with 👍 / 👎.


channels:
- blatants
Expand Down Expand Up @@ -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

Expand Down
19 changes: 17 additions & 2 deletions config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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
58 changes: 46 additions & 12 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 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.

Prompt for AI agents
In `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


Expand Down
2 changes: 2 additions & 0 deletions src/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ class Settings:
ipa_cache_global_workers: int
ipa_cache_part_size: int
ipa_cache_max_bytes: int
icon_cache_dir: str = ""


def _slug(value: str) -> str:
Expand Down Expand Up @@ -223,4 +224,5 @@ def load_settings() -> Settings:
ipa_cache_global_workers=max(int(_setting("server.ipa_cache_global_workers", "8")), 1),
ipa_cache_part_size=max(int(_setting("server.ipa_cache_part_size", str(8 * 1024 * 1024))), 512 * 1024),
ipa_cache_max_bytes=max(int(_setting("server.ipa_cache_max_mb", "1024")), 0) * 1024 * 1024,
icon_cache_dir=str(_setting("server.icon_cache_dir", "/data/icon-cache")).strip(),
)