Keep Store catalogues available during GitHub rate limits

This commit is contained in:
Arkemys Consulting
2026-11-17 13:07:00 +01:00
parent 598e95aa4a
commit 00aeb445ac
5 changed files with 166 additions and 74 deletions

View File

@@ -1254,6 +1254,8 @@ button.sr-app-delete { color: var(--danger); margin-inline-start: auto; }
}
.sr-store-search input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.sr-store [role="status"]:empty { display: none; }
.sr-store-source-notice { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; }
.sr-store-source-notice > [role="status"] { margin: 0; }
.sr-store h2 { font-size: 21px; line-height: 1.2; letter-spacing: -.025em; margin: 0 0 12px; }
.sr-store-section-head { justify-content: space-between; gap: 10px; margin-block-end: 12px; }
.sr-store-section-head h2 { margin: 0; }

View File

@@ -1,7 +1,7 @@
(() => {
if (location.origin !== "http://127.0.0.1:18784" && !globalThis.sideRelayWebBridge) return;
const bridge = (globalThis.sideRelayWebBridge ?? window.webkit.messageHandlers.signatureCompte);
const sourceChecks = new Map();
let nextSourceCheckAt = 0;
function node(tag, text = "", style = "") {
const el = document.createElement(tag);
@@ -1394,25 +1394,17 @@
}
}
async function checkSources() {
if (tab === "Store") return false;
const hour = 3600 * 1000;
const now = Date.now();
const stale = model.sources.filter(source =>
now - source.checkedAt * 1000 >= hour && now - (sourceChecks.get(source.id) || 0) >= hour);
if (!stale.length) return false;
let updated = false;
for (const source of stale) {
if (!section.isConnected) break;
sourceChecks.set(source.id, now);
try {
await catalogue("refresh", { sourceId: source.id });
updated = true;
} catch {
// Keep the cached catalogue if the publisher is unavailable.
}
if (tab === "Store" || !model.sources.length || now < nextSourceCheckAt) return false;
nextSourceCheckAt = now + 60_000;
try {
const result = await catalogue("refresh-store");
nextSourceCheckAt = Math.max(nextSourceCheckAt, result.refreshAfter * 1000 || 0);
if (result.updated && section.isConnected) await refreshLibrary();
return result.updated;
} catch {
return false;
}
if (updated && section.isConnected) await refreshLibrary();
return updated;
}
function updateFor(app) {
return model.updates?.[app.id] || null;
@@ -1426,7 +1418,7 @@
function mountStore(main) {
const store = globalThis.sideRelayStore({
node, button, feedback, catalogue, formatDate, failure: readableError,
node, button, feedback, catalogue, formatDate, githubRetryMessage, failure: readableError,
manage: trigger => manageSources(trigger, store.update),
prepare: prepareStoreInstall,
review: async (ipa, trigger, targets) => {
@@ -1438,6 +1430,12 @@
void store.refresh();
}
function githubRetryMessage(retryAt) {
if (!retryAt || retryAt * 1000 <= Date.now()) return "";
const resume = new Date(retryAt * 1000).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
return `GitHub sources can refresh after ${resume}.`;
}
async function prepareStoreInstall({ app, release }, trigger) {
const { requete } = globalThis.sideRelayJobs;
const [devices, accounts, deviceVersions] = await Promise.all([
@@ -1485,6 +1483,7 @@
const add = node("button", "Add Source", "btn btn-primary");
add.type = "submit";
form.append(label, add);
const publisherStatus = feedback();
let busy = false;
let sources = [];
async function run(operation, args, pending, done) {
@@ -1496,8 +1495,11 @@
try {
const result = await catalogue(operation, args);
sources = result.sources;
update(sources);
message.textContent = result.failed?.length ? "Some sources couldn’t load." : done;
update(result);
publisherStatus.textContent = githubRetryMessage(result.githubRetryAt);
const affected = operation === "refresh" ? sources.find(source => source.id === args.sourceId) : null;
message.textContent = affected ? result.updated ? done : ""
: operation === "refresh-store" && sources.some(source => source.refreshError) ? "" : done;
list();
return true;
} catch (error) {
@@ -1516,13 +1518,15 @@
function list() {
items.replaceChildren();
if (!sources.length) items.append(node("p", "No sources added.", "muted"));
for (const source of sources) {
const ordered = [...sources].sort((a, b) => Boolean(b.refreshError) - Boolean(a.refreshError));
for (const source of ordered) {
const row = node("div", "", "sr-store-source");
const identity = node("div");
const detail = source.checkedAt ?
(source.apps.length === 1 ? "1 app" : source.apps.length + " apps") + " · " + formatDate(source.checkedAt)
: "Pending download";
const count = source.apps.length === 1 ? "1 app" : source.apps.length + " apps";
const detail = source.refreshError ? (source.apps.length ? count + " cached" : "No apps available")
: source.checkedAt ? count + " · " + formatDate(source.checkedAt) : "Pending download";
identity.append(node("strong", source.name), node("p", detail, "muted"));
if (source.refreshError) identity.append(node("p", source.refreshError, "muted"));
const refresh = button("Refresh", () => run("refresh", { sourceId: source.id }, "Checking for updates…", "Source refreshed."));
refresh.setAttribute("aria-label", "Refresh " + source.name);
const remove = button("Remove", () => run("remove", { sourceId: source.id }, "Removing source…", "Source removed."), "sr-link");
@@ -1534,7 +1538,7 @@
const actions = node("footer", "", "sr-actions sr-store-source-actions");
actions.append(button("Refresh All", () => run("refresh-store", { force: "yes" }, "Refreshing sources…", "Sources refreshed.")),
button("Done", () => dialog.close(), "btn btn-primary sr-store-done"));
dialog.append(title, form, message, items, actions);
dialog.append(title, form, publisherStatus, message, items, actions);
dialog.addEventListener("close", () => {
dialog.remove();
if (trigger?.isConnected) trigger.focus();

View File

@@ -15,6 +15,7 @@ import re
import socket
import ssl
import tempfile
import threading
import time
from urllib.parse import quote, urljoin, urlsplit
from uuid import uuid4
@@ -27,6 +28,9 @@ SOURCE_BYTES = 2 * 1024 * 1024
IMAGE_BYTES = 4 * 1024 * 1024
IPA_BYTES = 512 * 1024 * 1024
STORE_REFRESH_INTERVAL = 3600
GITHUB_REFRESH_INTERVAL = 4 * STORE_REFRESH_INTERVAL
SOURCE_RETRY_INTERVAL = 300
GITHUB_API_HOST = "api.github.com"
BUNDLE_ID = re.compile(r"[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\Z")
VERSION = re.compile(r"[A-Za-z0-9.+-]{1,64}\Z")
DEFAULT_SOURCES = Path(__file__).with_name("StoreSources.json")
@@ -117,6 +121,19 @@ class SourceConnection(http.client.HTTPSConnection):
raise
class GitHubRateLimit(ValueError):
def __init__(self, response):
super().__init__("GitHub’s request limit was reached.")
now = int(time.time())
reset = response.getheader("X-RateLimit-Reset", "")
retry_after = response.getheader("Retry-After", "")
self.retry_at = max(
now + SOURCE_RETRY_INTERVAL,
int(reset) if reset.isascii() and reset.isdecimal() else 0,
now + int(retry_after) if retry_after.isascii() and retry_after.isdecimal() else 0,
)
@contextmanager
def open_url(url, accept):
for _ in range(6):
@@ -134,6 +151,10 @@ def open_url(url, accept):
raise ValueError("The source returned an invalid redirect.")
url = urljoin(url, location)
continue
if host == GITHUB_API_HOST and response.status in (403, 429) and (
response.status == 429 or response.getheader("X-RateLimit-Remaining") == "0"
or response.getheader("Retry-After")):
raise GitHubRateLimit(response)
if response.status != 200:
raise ValueError(f"The source server returned HTTP {response.status}.")
response.relay_url = url
@@ -537,37 +558,91 @@ def seed_store(db):
WHERE url=? AND catalogue='[]'""", (name, json.dumps(apps), checked, url))
def refresh_store(db, force=False):
cutoff = int(time.time()) - STORE_REFRESH_INTERVAL
entries = db.execute(
"SELECT id,url FROM ipa_sources WHERE checked_at <= ? OR ?", (cutoff, force)
).fetchall()
failed, changed = refresh_catalogues(db, entries)
return {"sources": sources(db, with_revision=True), "failed": failed, "updated": changed}
def store_schedule(db):
db.execute("""CREATE TABLE IF NOT EXISTS ipa_store_failures (
source_id TEXT PRIMARY KEY, message TEXT NOT NULL, tried_at INTEGER NOT NULL,
github_retry_at INTEGER NOT NULL)""")
rows = db.execute("""SELECT s.id,s.url,s.checked_at,f.message,f.tried_at,f.github_retry_at
FROM ipa_sources s LEFT JOIN ipa_store_failures f ON f.source_id=s.id""").fetchall()
github_retry_at = max((row[5] or 0 for row in rows), default=0)
schedule = {}
for source_id, url, checked, error, tried, _ in rows:
github = urlsplit(url).hostname == GITHUB_API_HOST
blocked_until = github_retry_at if github else 0
interval = GITHUB_REFRESH_INTERVAL if github else STORE_REFRESH_INTERVAL
due = checked + interval if checked else 0
if tried:
due = tried + SOURCE_RETRY_INTERVAL
schedule[source_id] = (url, error, max(due, blocked_until), blocked_until)
return schedule
def refreshable_sources(schedule, force=False):
now = int(time.time())
return [(source_id, url) for source_id, (url, _, due, blocked) in schedule.items()
if blocked <= now and (force or due <= now)]
def store_snapshot(db, updated=False):
schedule = store_schedule(db)
catalogues = sources(db, with_revision=True)
for source in catalogues:
entry = schedule.get(source["id"])
if entry and entry[1]:
source["refreshError"] = entry[1]
now = int(time.time())
return {
"sources": catalogues, "updated": updated,
"failed": [source["id"] for source in catalogues if source.get("refreshError")],
"refreshAfter": min((row[2] for row in schedule.values()), default=now + STORE_REFRESH_INTERVAL),
"githubRetryAt": max((row[3] for row in schedule.values() if row[3] > now), default=0),
}
def refresh_catalogues(db, entries):
if not entries:
return False
github_limit = None
limit_lock = threading.Lock()
def read(entry):
nonlocal github_limit
source_id, url = entry
if urlsplit(url).hostname == GITHUB_API_HOST:
with limit_lock:
if github_limit:
return source_id, None, github_limit
try:
return source_id, fetch_source(url)
except (ValueError, OSError, http.client.HTTPException):
return source_id, None
return source_id, fetch_source(url), None
except GitHubRateLimit as error:
with limit_lock:
if not github_limit or error.retry_at > github_limit.retry_at:
github_limit = error
return source_id, None, error
except (ValueError, OSError, http.client.HTTPException) as error:
return source_id, None, error
failed = []
changed = False
with ThreadPoolExecutor(max_workers=8) as pool:
for source_id, result in pool.map(read, entries):
if result is None:
failed.append(source_id)
continue
name, catalogue = result
for source_id, result, error in pool.map(read, entries):
with db:
changed |= bool(db.execute("""UPDATE ipa_sources
SET name=?, catalogue=?, checked_at=unixepoch() WHERE id=?""",
(name, json.dumps(catalogue), source_id)).rowcount)
return failed, changed
if error is not None:
message = (str(error)[:200] if isinstance(error, ValueError) else
"The publisher couldn’t be reached.")
blocked_until = error.retry_at if isinstance(error, GitHubRateLimit) else 0
db.execute("""INSERT INTO ipa_store_failures
SELECT id, ?, unixepoch(), ? FROM ipa_sources WHERE id=?
ON CONFLICT(source_id) DO UPDATE SET message=excluded.message,
tried_at=excluded.tried_at, github_retry_at=excluded.github_retry_at""",
(message, blocked_until, source_id))
else:
name, catalogue = result
changed |= bool(db.execute("""UPDATE ipa_sources
SET name=?, catalogue=?, checked_at=unixepoch() WHERE id=?""",
(name, json.dumps(catalogue), source_id)).rowcount)
db.execute("DELETE FROM ipa_store_failures WHERE source_id=?", (source_id,))
return changed
def store_artwork(db, source_id, address):
@@ -680,30 +755,34 @@ def command(db, root, port, action, first=None, second=None, third=None):
return prepare_top_shelf_update(db, root, port, second, first) or {}
if action == "store":
seed_store(db)
catalogues = sources(db, with_revision=True)
refresh_after = min((source["checkedAt"] for source in catalogues), default=0) + STORE_REFRESH_INTERVAL
return {"sources": catalogues, "refreshAfter": refresh_after}
return store_snapshot(db)
if action == "refresh-store":
seed_store(db)
return refresh_store(db, force=first == "all")
entries = refreshable_sources(store_schedule(db), force=first == "all")
return store_snapshot(db, updated=refresh_catalogues(db, entries))
if action == "store-image":
return store_image(db, first, second)
if action == "add":
name, catalogue = fetch_source(first)
store_schedule(db)
with db:
db.execute("""
INSERT INTO ipa_sources (id,url,name,catalogue,checked_at) VALUES (?,?,?,?,unixepoch())
ON CONFLICT(url) DO UPDATE SET name=excluded.name,catalogue=excluded.catalogue,checked_at=excluded.checked_at
""", (str(uuid4()), first, name, json.dumps(catalogue)))
db.execute("DELETE FROM ipa_store_failures WHERE source_id=(SELECT id FROM ipa_sources WHERE url=?)",
(first,))
elif action == "refresh":
url, _, _, _ = load_source(db, first)
name, catalogue = fetch_source(url)
with db:
db.execute("UPDATE ipa_sources SET name=?, catalogue=?, checked_at=unixepoch() WHERE id=?",
(name, json.dumps(catalogue), first))
schedule = store_schedule(db)
if first not in schedule:
raise ValueError("This source is no longer in SideRelay.")
entries = refreshable_sources({first: schedule[first]}, force=True)
return store_snapshot(db, updated=refresh_catalogues(db, entries))
elif action == "remove":
store_schedule(db)
with db:
db.execute("DELETE FROM ipa_sources WHERE id = ?", (first,))
db.execute("DELETE FROM ipa_store_failures WHERE source_id=?", (first,))
elif action == "download":
return download(db, root, port, first, second, third)
elif action == "import-build":
@@ -730,4 +809,4 @@ def command(db, root, port, action, first=None, second=None, third=None):
return {"png": b64encode(image).decode("ascii")} if image else {}
else:
raise ValueError("Unknown catalogue action.")
return {"sources": sources(db)}
return store_snapshot(db)

View File

@@ -9,12 +9,12 @@ import re
import sqlite3
import sys
import tempfile
import time
from uuid import UUID
from zipfile import ZipFile
from .CompagnonIPA import enabled, tailnet_ip
from .CatalogueIPA import download, main_ipa_plist, private_work, refresh_catalogues, tv_sources, upload_archive
from .CatalogueIPA import (download, main_ipa_plist, private_work, refresh_catalogues,
refreshable_sources, store_schedule, tv_sources, upload_archive)
from .CompagnonMisesAJour import engine_request
from .ImportLiveContainer import tailscale
@@ -90,14 +90,12 @@ def tv_editions(db):
yield source, app, release
def refresh_tv_sources(db, root):
cutoff = int(time.time()) - 3600
entries = [entry for entry in db.execute("SELECT id,url FROM ipa_sources WHERE checked_at<=?", (cutoff,))
if entry[1] in tv_sources()]
if entries:
uri = (root / "signature.db").as_uri() + "?mode=rw"
with closing(sqlite3.connect(uri, uri=True, timeout=2)) as writer:
refresh_catalogues(writer, entries)
def refresh_tv_sources(root):
uri = (root / "signature.db").as_uri() + "?mode=rw"
with closing(sqlite3.connect(uri, uri=True, timeout=2)) as writer:
definitions = tv_sources()
entries = [entry for entry in refreshable_sources(store_schedule(writer)) if entry[1] in definitions]
refresh_catalogues(writer, entries)
def installed_tv_app(db, device, bundle):
@@ -165,7 +163,7 @@ def tv_store_action(installs, release):
def store(db, root, device):
refresh_tv_sources(db, root)
refresh_tv_sources(root)
items = []
for _, app, release in tv_editions(db):
installs = installed_tv_app(db, device, app["bundleId"])

View File

@@ -155,7 +155,8 @@
window.addEventListener("scrollend", globalThis.sideRelaySaveStoreHistory, { passive: true });
}
globalThis.sideRelayStore = function ({ node, button, feedback, catalogue, formatDate, prepare, review, manage, failure }) {
globalThis.sideRelayStore = function ({ node, button, feedback, catalogue, formatDate, githubRetryMessage,
prepare, review, manage, failure }) {
const view = node("section", "", "sr-store");
view.setAttribute("aria-label", "Store");
const header = node("header", "", "sr-store-header");
@@ -192,6 +193,10 @@
tabs.setAttribute("role", "tablist");
tabs.setAttribute("aria-label", "Store platform");
const banner = feedback();
const sourceNotice = node("div", "", "sr-store-source-notice");
const sourceStatus = feedback();
sourceNotice.append(sourceStatus, button("Manage Sources…", trigger => manage(trigger), "sr-link"));
sourceNotice.hidden = true;
const body = node("div", "", "sr-store-body");
const platforms = [["ios", "iPhone & iPad"], ["tvos", "Apple TV"]].map(([id, label], index) => {
const tab = button(label, () => selectPlatform(index), "btn");
@@ -381,7 +386,7 @@
function mountPlatform() {
const { panel, label, featuredSection } = platforms[activePlatform];
panel.prepend(banner);
panel.prepend(sourceNotice, banner);
featuredSection.after(body);
search.placeholder = activePlatform === 1 ? "Search Apple TV apps" : "Search apps";
search.setAttribute("aria-label", `Search ${label} apps`);
@@ -842,8 +847,13 @@
return items.filter(({ primary }) => !primary.preview && !primary.release.restricted && date(primary.release.date))
.sort((a, b) => date(b.primary.release.date) - date(a.primary.release.date));
}
function update(next) {
function update({ sources: next, githubRetryAt }) {
sources = next;
failed = sources.filter(source => source.refreshError);
sourceStatus.textContent = githubRetryMessage(githubRetryAt) || (failed.length === 1
? `${failed[0].name} couldn’t refresh.`
: failed.length ? `${failed.length} sources couldn’t refresh.` : "");
sourceNotice.hidden = !sourceStatus.textContent;
const revision = next.every(source => source.revision) ? JSON.stringify(next.map(
source => [source.id, source.name, source.curated, source.revision])) : undefined;
if (revision !== undefined && catalogueRevision === revision && !pendingHistory) return;
@@ -866,13 +876,12 @@
try {
if (!sources.length) {
const cached = await catalogue("store");
update(cached.sources);
update(cached);
if (!force && cached.refreshAfter * 1000 > Date.now()) return;
}
const result = await catalogue("refresh-store", force ? { force: "yes" } : {});
failed = result.failed || [];
update(result.sources);
if (view.isConnected) banner.textContent = failed.length ? "Some sources couldn’t load. Open More → Manage Sources." : "";
update(result);
if (view.isConnected) banner.textContent = "";
} catch (error) {
if (view.isConnected) banner.textContent = failure(error, "Could not load the Store.");
} finally {