feat: remove craft_apps APIs and statically generate signed launcher-catalog releases (#439)

## Summary

- Remove the unused legacy `craft_apps` APIs, cache and poller. The
maintainer confirmed these APIs were never used and complete removal is
the intended outcome. The new signed static catalog is the source for
release metadata.
- Statically generate release metadata (stable, prerelease, and nightly
channels + `SHA256SUMS.txt` assets) into `out/launcher-catalog.toml`
during `npm run build:cloudflare`, mirroring how the static Linux
repositories work (`scripts/generate-static-repos.mjs`):
- Add `scripts/generate-launcher-catalog.mjs` to enrich
`public/launcher-catalog.toml` into `out/launcher-catalog.toml` with
top-level `generated_at`, `[launcher.releases.*]`, and per-app
`[apps.releases.*]` tables while staying within `MAX_CATALOG_BYTES` (1
MiB) and keeping `public/launcher-catalog.toml` untouched for
`sync-launcher-catalog.py --check`.
- Run `scripts/generate-launcher-catalog.mjs` in
`scripts/build-cloudflare.mjs` immediately before
`signLauncherCatalog(out)` so `out/launcher-catalog.toml.sig` is an
Ed25519 signature over the final generated bytes using
`LAUNCHER_CATALOG_SIGNING_KEY`.
- Extend `src/lib/crafting-app-releases.ts` and
`.github/workflows/update-craft-release-versions.yml` to also track
`CRAFT_PRERELEASE_RELEASES` and `CRAFT_COMMUNITY_RELEASES` alongside
`CRAFT_APP_RELEASES`, `CRAFT_LAUNCHER_RELEASE`, and
`CRAFT_NIGHTLY_RELEASES`.
- Add unit tests in `scripts/generate-launcher-catalog.test.mjs` and
update `scripts/LAUNCHER-CATALOG.md`.

## Verification

- `SQLX_OFFLINE=true cargo check -p artcraft_api_defs -p redis_schema -p
storyteller-web --tests`
- `cd frontend/apps/artcraft-website-next && npm run typecheck`
- `cd frontend/apps/artcraft-website-next && npm run
test:launcher-catalog` (8/8 passing)
- `cd frontend/apps/artcraft-website-next && python3 -m unittest
scripts/test_sync_launcher_catalog.py` (5/5 passing)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* The launcher catalog now includes available stable, prerelease, and
nightly releases for the launcher, configured apps, and community apps,
with release checksums.
* Launcher screenshots are served from the website and cached for faster
access.

* **Changes**
* Craft app release information and release-history endpoints are no
longer available. Release details are published through the generated
launcher catalog instead.
  * Updated community app repository information in the catalog.

* **Documentation**
* Updated Cloudflare build guidance to cover catalog generation and
signing.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
This commit is contained in:
Dylan M. TaylorandFredApps authored and GitHub committed 2026-11-27 09:23:17 -05:00
1 parent 961ce59dee
commit 73acbb9fe1
83 files changed
+966 -4086

No files matched your search

@@ -4,6 +4,10 @@ on:
schedule:
# Hourly, on the hour
- cron: "0 * * * *"
repository_dispatch:
# Triggered immediately when any Craft app or launcher release/prerelease is
# published, edited, unpublished, deleted, or changes prerelease state.
types: [craft-release-changed]
workflow_dispatch:
permissions:
@@ -417,6 +421,178 @@ jobs:
})
.join("\n")}\n}`;
content = content.replace(nightlyBlockPattern, (_, prefix) => `${prefix}${formattedNightlies};`);
// Update non-nightly prereleases (betas / RCs) and community app releases for
// static `launcher-catalog.toml` generation.
function isNightlyTag(tag) {
const stripped = tag.replace(/^[vV]/, "").split("+")[0];
const dashIdx = stripped.indexOf("-");
if (dashIdx === -1) return false;
return stripped
.slice(dashIdx + 1)
.split(".")
.some(part => part.toLowerCase() === "nightly");
}
function parseSemverTag(tag) {
const match = tag.match(
/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
);
if (!match) return null;
return {
major: Number(match[1]),
minor: Number(match[2]),
patch: Number(match[3]),
pre: match[4] ? match[4].split(".") : [],
version: tag.replace(/^[vV]/, ""),
};
}
function compareSemver(a, b) {
for (const key of ["major", "minor", "patch"]) {
if (a[key] !== b[key]) return a[key] - b[key];
}
if (a.pre.length === 0 && b.pre.length === 0) return 0;
if (a.pre.length === 0) return 1;
if (b.pre.length === 0) return -1;
const len = Math.min(a.pre.length, b.pre.length);
for (let i = 0; i < len; i++) {
const ai = a.pre[i];
const bi = b.pre[i];
if (ai === bi) continue;
const aNum = /^\d+$/.test(ai);
const bNum = /^\d+$/.test(bi);
if (aNum && bNum) return Number(ai) - Number(bi);
if (aNum) return -1;
if (bNum) return 1;
return ai < bi ? -1 : 1;
}
return a.pre.length - b.pre.length;
}
async function latestPrerelease(repoOwner, repoName) {
const releases = await github.paginate(
github.rest.repos.listReleases,
{ owner: repoOwner, repo: repoName, per_page: 50 },
response => response.data
);
let best = null;
for (const rel of releases) {
if (rel.draft || isNightlyTag(rel.tag_name)) continue;
const parsed = parseSemverTag(rel.tag_name);
if (!parsed) continue;
const isPre = rel.prerelease || parsed.pre.length > 0;
if (!isPre) continue;
if (!best || compareSemver(parsed, best.parsed) > 0) {
best = { parsed, tag: rel.tag_name, version: parsed.version };
}
}
return best ? { tag: best.tag, version: best.version } : null;
}
const prereleaseTargets = [
{ key: launcher.fileSlug, repo: launcher.repo },
...apps.map(app => ({ key: app, repo: app })),
];
const prereleaseEntries = {};
for (const target of prereleaseTargets) {
const found = await latestPrerelease(owner, target.repo);
if (found) {
prereleaseEntries[target.key] = found;
}
}
const prereleaseBlockPattern =
/(export const CRAFT_PRERELEASE_RELEASES:\s*Partial<[\s\S]*?>\s*=\s*)\{[\s\S]*?\};/;
if (!prereleaseBlockPattern.test(content)) {
throw new Error("Could not find CRAFT_PRERELEASE_RELEASES in crafting-app-releases.ts.");
}
const formattedPrereleases = Object.keys(prereleaseEntries).length === 0
? "{}"
: `{\n${Object.entries(prereleaseEntries)
.map(([k, v]) => {
const keyStr = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
return ` ${keyStr}: { tag: ${JSON.stringify(v.tag)}, version: ${JSON.stringify(v.version)} },`;
})
.join("\n")}\n}`;
content = content.replace(prereleaseBlockPattern, (_, prefix) => `${prefix}${formattedPrereleases};`);
// Track community apps listed in public/launcher-catalog.toml (non-fatal if an external repo fails).
const communityApps = [
{ id: "solidcraft", repo: "tangency-labs/solidcraft" },
{ id: "mailcraft", repo: "UCS-Care-Group/mailcraft" },
];
const communityEntries = {};
let communityQueryFailed = false;
for (const community of communityApps) {
const [cOwner, cRepo] = community.repo.split("/");
try {
const releases = await github.paginate(
github.rest.repos.listReleases,
{ owner: cOwner, repo: cRepo, per_page: 50 },
response => response.data
);
let bestStable = null;
let bestPre = null;
let newestNightly = null;
const published = releases
.filter(r => !r.draft)
.sort((a, b) => new Date(b.published_at || b.created_at) - new Date(a.published_at || a.created_at));
for (const rel of published) {
if (isNightlyTag(rel.tag_name)) {
if (!newestNightly) {
newestNightly = { tag: rel.tag_name, version: rel.tag_name.replace(/^[vV]/, "") };
}
continue;
}
const parsed = parseSemverTag(rel.tag_name);
if (!parsed) continue;
if (rel.prerelease || parsed.pre.length > 0) {
if (!bestPre || compareSemver(parsed, bestPre.parsed) > 0) {
bestPre = { parsed, tag: rel.tag_name, version: parsed.version };
}
} else if (!bestStable || compareSemver(parsed, bestStable.parsed) > 0) {
bestStable = { parsed, tag: rel.tag_name, version: parsed.version };
}
}
if (bestStable || bestPre || newestNightly) {
const entry = { repo: community.repo };
if (bestStable) entry.stable = { tag: bestStable.tag, version: bestStable.version };
if (bestPre) entry.prerelease = { tag: bestPre.tag, version: bestPre.version };
if (newestNightly) entry.nightly = newestNightly;
communityEntries[community.id] = entry;
}
} catch (err) {
communityQueryFailed = true;
core.warning(`Could not query community app ${community.repo}: ${err.message}`);
}
}
const communityBlockPattern =
/(export const CRAFT_COMMUNITY_RELEASES:\s*Record<string,\s*CraftCommunityAppReleases>\s*=\s*)\{[\s\S]*?\};/;
if (!communityBlockPattern.test(content)) {
throw new Error("Could not find CRAFT_COMMUNITY_RELEASES in crafting-app-releases.ts.");
}
const formattedCommunity = Object.keys(communityEntries).length === 0
? "{}"
: `{\n${Object.entries(communityEntries)
.map(([k, v]) => {
const keyStr = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
const fields = [`repo: ${JSON.stringify(v.repo)}`];
for (const ch of ["stable", "prerelease", "nightly"]) {
if (v[ch]) {
fields.push(`${ch}: { tag: ${JSON.stringify(v[ch].tag)}, version: ${JSON.stringify(v[ch].version)} }`);
}
}
return ` ${keyStr}: { ${fields.join(", ")} },`;
})
.join("\n")}\n}`;
if (communityQueryFailed) {
// A failed query must not erase what an earlier run recorded: keep the declaration as is.
core.warning("Keeping the recorded community releases because a query failed.");
} else {
content = content.replace(communityBlockPattern, (_, prefix) => `${prefix}${formattedCommunity};`);
}
fs.writeFileSync(file, content);
core.info("Release versions updated successfully.");
@@ -476,3 +652,17 @@ jobs:
echo "Unable to merge pull request $PR_NUMBER after 5 attempts." >&2
exit 1
# Release assets may change without a version change, and releases published with
# GITHUB_TOKEN may not trigger a release event workflow. Rebuild on dispatch,
# manual or scheduled reconciliation even when no version PR was needed.
- name: Trigger Cloudflare deploy when no version PR was needed
if: steps.create-pr.outputs.pull-request-number == ''
env:
DEPLOY_HOOK: ${{ secrets.CLOUDFLARE_DEPLOY_HOOK }}
run: |
if [ -z "$DEPLOY_HOOK" ]; then
echo "CLOUDFLARE_DEPLOY_HOOK is not configured; skipping direct deploy."
exit 0
fi
curl --fail --silent --show-error --connect-timeout 10 --max-time 30 --request POST "$DEPLOY_HOOK"
Generated
-1
View File
@@ -8687,7 +8687,6 @@ dependencies = [
"rootly_config",
"rust-s3",
"rustls 0.23.36",
"semver 1.0.23",
"serde",
"serde_derive",
"serde_json",
@@ -1,2 +0,0 @@
pub mod release_info;
pub mod releases;
@@ -1,256 +0,0 @@
use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use url::Url;
use utoipa::ToSchema;
// ── GET /v1/craft_apps/release_info ──
//
// The latest stable release, beta and nightly of every Craft App (PhotoCraft, VectorCraft, …,
// and ArtCraft Launcher itself) and its recent versions, as storyteller-web last fetched them
// from GitHub, plus renames and notices for the ArtCraft Launcher. The launcher polls this instead of GitHub; GitHub is its fallback.
//
// Compatibility: clients must ignore fields they don't know, and treat every field as optional.
// New fields may be added; existing ones keep their meaning.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GetCraftAppsReleaseInfoResponse {
pub success: bool,
pub release_info: CraftAppsReleaseInfo,
/// Apps that changed their name (for example PdfCraft → DocuCraft).
pub app_renames: Vec<CraftAppRename>,
/// Apps whose GitHub repository moved (for example `storytold/photocraft` → `art/photocraft`).
pub repo_renames: Vec<CraftAppRepoRename>,
pub important_notices: CraftAppsImportantNotices,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
pub struct CraftAppsReleaseInfo {
/// Keyed by app key: the app's lowercase machine name, as used in its binaries, asset file
/// names and `ai.storyteller.<key>` bundle id (`photocraft`, `cadcraft`, `artcraft-launcher`).
/// Not the display name and not the repo name. Clients should ignore keys they don't know.
pub apps: BTreeMap<String, CraftAppReleaseInfo>,
/// When the least recently fetched app was fetched: every app's data is at least this fresh.
/// Absent until every app has been fetched at least once.
pub last_fetched: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppReleaseInfo {
/// Display name (`PhotoCraft`).
pub name: String,
/// GitHub repository, `organization/project` (`storytold/photocraft`).
pub repo: String,
/// The published, non-draft, non-prerelease release with the highest version by semver
/// precedence (never a nightly, see `latest_nightly`), so a backport published after a newer
/// release isn't it. Absent when the repository has no release yet, or when it hasn't been
/// fetched yet (see `app_last_fetched`).
pub latest_release: Option<CraftAppRelease>,
/// When this app's release data was last fetched successfully. Absent if it never was; then
/// `latest_release` says nothing and clients should ask GitHub themselves.
pub app_last_fetched: Option<DateTime<Utc>>,
/// The beta or release candidate with the highest version: a pre-release that isn't a nightly. It may be older
/// than `latest_release`; clients compare versions. Absent when none is among the recent
/// releases (see `releases`).
#[serde(default)]
pub latest_prerelease: Option<CraftAppRelease>,
/// The newest nightly build: a release whose tag's pre-release part has a `nightly` identifier
/// (`v0.50.0-nightly.20261126.166.1`), whatever its pre-release flag says. Absent when none is
/// among the recent releases.
#[serde(default)]
pub latest_nightly: Option<CraftAppRelease>,
/// The 30 newest ordinary releases (stable ones and pre-releases, never nightlies), newest
/// first, without notes or files. The whole history, with files, is
/// `GET /v1/craft_apps/{app_key}/releases`.
#[serde(default)]
pub releases: Vec<CraftAppReleaseSummary>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppRelease {
/// Git tag (`v0.5.0`).
pub tag: String,
/// The tag without its leading `v` (`0.5.0`, `0.6.0-rc.1`).
pub version: String,
/// Release title (`PhotoCraft v0.5.0`).
pub name: String,
pub published_at: Option<DateTime<Utc>>,
/// The release's page on GitHub.
pub html_url: String,
pub prerelease: bool,
/// Release notes (Markdown), truncated to 64 KiB.
pub notes_markdown: String,
pub assets: Vec<CraftAppReleaseAsset>,
}
/// A release in an app's version list: what to show and where its page is, not its files.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct CraftAppReleaseSummary {
/// Git tag (`v0.5.0`).
pub tag: String,
/// The tag without its leading `v` (`0.5.0`, `0.6.0-rc.1`).
pub version: String,
/// Release title (`PhotoCraft v0.5.0`).
pub name: String,
pub published_at: Option<DateTime<Utc>>,
/// The release's page on GitHub.
pub html_url: String,
pub prerelease: bool,
}
impl From<&CraftAppRelease> for CraftAppReleaseSummary {
fn from(release: &CraftAppRelease) -> Self {
Self {
tag: release.tag.clone(),
version: release.version.clone(),
name: release.name.clone(),
published_at: release.published_at,
html_url: release.html_url.clone(),
prerelease: release.prerelease,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppReleaseAsset {
/// File name (`photocraft-0.5.0-windows-x64.msi`).
pub name: String,
pub size_bytes: u64,
/// `https://github.com/<repo>/releases/download/<tag>/<name>`.
pub download_url: String,
/// Lowercase hex SHA-256, when GitHub published one for the file.
pub sha256: Option<String>,
/// What the file name says it is, when it follows the Craft App naming scheme
/// (`<app>-<version>-<os>-<arch>[-portable].<ext>`).
pub platform: Option<CraftAppAssetPlatform>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppAssetPlatform {
pub os: CraftAppOs,
/// Absent for files that aren't for one CPU (the web build, checksums).
pub arch: Option<CraftAppArch>,
pub package_type: CraftAppPackageType,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CraftAppOs {
Windows,
Macos,
Linux,
Freebsd,
/// The browser build.
Web,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CraftAppArch {
X64,
X86,
Arm64,
/// macOS universal binary (Apple silicon and Intel).
Universal,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CraftAppPackageType {
/// Windows Installer.
Msi,
/// Windows portable zip.
PortableZip,
/// macOS disk image.
Dmg,
/// macOS command-line tools zip.
CliZip,
AppImage,
/// AppImage delta-update file.
AppImageZsync,
Deb,
Rpm,
Flatpak,
/// Linux or FreeBSD tarball.
TarGz,
/// The web (WebAssembly) build.
WebZip,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppRename {
/// User-facing name before (`PdfCraft`).
pub old_name: String,
/// Lowercase name before (`pdfcraft`).
pub old_name_lower: String,
/// User-facing name after (`DocuCraft`).
pub new_name: String,
/// Lowercase name after (`docucraft`).
pub new_name_lower: String,
/// A sentence or two to show beside the rename.
pub description: String,
pub renamed_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppRepoRename {
/// `organization/project` before.
pub old_name: String,
/// `organization/project` after.
pub new_name: String,
pub renamed_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
pub struct CraftAppsImportantNotices {
/// News, shown inline; the user can dismiss each.
pub announcements: Vec<CraftAppsAnnouncement>,
/// Shown as a popup the user acknowledges.
pub alerts: Vec<CraftAppsAlert>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppsAnnouncement {
pub title: String,
pub body: String,
pub created_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct CraftAppsAlert {
pub title: String,
pub body: String,
/// A page the popup can offer to open.
pub maybe_web_link: Option<Url>,
pub created_at: Option<DateTime<Utc>>,
}
@@ -1,46 +0,0 @@
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::craft_apps::release_info::CraftAppRelease;
// ── GET /v1/craft_apps/{app_key}/releases ──
//
// One Craft App's release history: every published release storyteller-web read from GitHub,
// newest first, nightlies included, each with its files and checksums. ArtCraft Launcher reads
// it to choose or go back to a version and to find nightlies; `release_info` carries only the
// latest of each kind, for every app at once.
//
// Compatibility: clients must ignore fields they don't know, and treat every field as optional.
// New fields may be added; existing ones keep their meaning.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GetCraftAppReleasesResponse {
pub success: bool,
/// The app's lowercase machine name (`photocraft`), as in `release_info.apps`.
pub app_key: String,
/// Display name (`PhotoCraft`).
pub name: String,
/// GitHub repository, `organization/project` (`storytold/photocraft`).
pub repo: String,
/// When this app's releases were last fetched successfully. Absent if they never were; then
/// `releases` says nothing.
pub app_last_fetched: Option<DateTime<Utc>>,
/// Whether `releases` is every release the repository has. When false, older ones exist that
/// aren't listed (storyteller-web reads at most the newest 1000).
pub complete: bool,
/// Newest first (as GitHub lists them). Release notes are truncated to 64 KiB.
pub releases: Vec<CraftAppRelease>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GetCraftAppReleasesError {
pub success: bool,
pub error_reason: String,
}
@@ -2,7 +2,6 @@ pub mod analytics;
pub mod api_keys;
pub mod characters;
pub mod common;
pub mod craft_apps;
pub mod credits;
pub mod folders;
pub mod generate;
@@ -1,37 +0,0 @@
//! The release history of one Craft App (every published release, with its files), shared by
//! every storyteller-web instance next to `CraftAppReleaseRedisKey`, and kept apart from it so
//! the fleet's every-tick read of the latest releases stays small.
//!
//! A Redis string (JSON), written by `poll_craft_app_releases_thread` (storyteller-web), which
//! documents it. Expires if nobody refreshes it for a week, which only happens if polling stops.
use chrono::Duration;
pub struct CraftAppReleaseHistoryRedisKey(pub String);
impl_string_key!(CraftAppReleaseHistoryRedisKey);
const REDIS_KEY_TTL_DURATION: Duration = Duration::milliseconds(1000 * 60 * 60 * 24 * 7);
impl CraftAppReleaseHistoryRedisKey {
/// `app_key` is the app's lowercase machine name (`photocraft`, `artcraft-launcher`).
pub fn new_for_app(app_key: &str) -> Self {
let key = format!("craftApps:releases:v2:history:{}", app_key);
Self(key)
}
pub fn get_redis_ttl() -> Duration {
REDIS_KEY_TTL_DURATION
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_for_app() {
let key = CraftAppReleaseHistoryRedisKey::new_for_app("photocraft");
assert_eq!(key.as_str(), "craftApps:releases:v2:history:photocraft");
}
}
@@ -1,44 +0,0 @@
//! The releases of one Craft App (stable, beta, nightly and the recent versions), shared by every
//! storyteller-web instance so the fleet polls GitHub once per app instead of once per pod.
//!
//! `v2`: the hash before it held only the latest release, under `craftApps:releases:app:<key>`.
//! A new key, so instances of either version never overwrite the other's during a rollout.
//!
//! A Redis hash, written by `poll_craft_app_releases_thread` (storyteller-web), which documents
//! the fields. Expires if nobody refreshes it for a week, which only happens if polling stops.
use chrono::Duration;
pub struct CraftAppReleaseRedisKey(pub String);
impl_string_key!(CraftAppReleaseRedisKey);
const REDIS_KEY_TTL_DURATION: Duration = Duration::milliseconds(1000 * 60 * 60 * 24 * 7);
impl CraftAppReleaseRedisKey {
/// `app_key` is the app's lowercase machine name (`photocraft`, `artcraft-launcher`).
pub fn new_for_app(app_key: &str) -> Self {
let key = format!("craftApps:releases:v2:app:{}", app_key);
Self(key)
}
pub fn get_redis_ttl() -> Duration {
REDIS_KEY_TTL_DURATION
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_for_app() {
let key = CraftAppReleaseRedisKey::new_for_app("photocraft");
assert_eq!(key.as_str(), "craftApps:releases:v2:app:photocraft");
}
#[test]
fn test_duration() {
assert_eq!(CraftAppReleaseRedisKey::get_redis_ttl().num_days(), 7);
}
}
@@ -1,39 +0,0 @@
//! The fleet-wide GitHub backoff for Craft App release polling: after GitHub rate-limits us (or
//! every request of a round fails), no storyteller-web instance asks GitHub again until it ends.
//!
//! A Redis hash, written by `poll_craft_app_releases_thread` (storyteller-web), which documents
//! the fields. It outlives the backoff itself so repeated trouble keeps growing the wait; it is
//! deleted after a good round.
use chrono::Duration;
pub struct CraftAppsReleaseBackoffRedisKey(pub String);
impl_string_key!(CraftAppsReleaseBackoffRedisKey);
const REDIS_KEY_TTL_DURATION: Duration = Duration::milliseconds(1000 * 60 * 60 * 24);
impl CraftAppsReleaseBackoffRedisKey {
pub fn new_for_fleet() -> Self {
Self("craftApps:releases:backoff".to_string())
}
pub fn get_redis_ttl() -> Duration {
REDIS_KEY_TTL_DURATION
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_for_fleet() {
assert_eq!(CraftAppsReleaseBackoffRedisKey::new_for_fleet().as_str(), "craftApps:releases:backoff");
}
#[test]
fn test_duration() {
assert_eq!(CraftAppsReleaseBackoffRedisKey::get_redis_ttl().num_hours(), 24);
}
}
@@ -1,3 +0,0 @@
pub mod craft_app_release_history_redis_key;
pub mod craft_app_release_redis_key;
pub mod craft_apps_release_backoff_redis_key;
@@ -1,3 +1,2 @@
pub mod craft_apps;
pub mod premium;
pub mod inference_job;
@@ -189,7 +189,6 @@ erased-serde.workspace = true
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
semver = "1"
toml.workspace = true
# Async traits
@@ -162,8 +162,6 @@ use artcraft_api_defs::moderation::user_daily_spends::user_daily_spends_list::*;
use artcraft_api_defs::moderation::top_spenders::list::*;
use artcraft_api_defs::moderation::user_spend_events::list::*;
use artcraft_api_defs::folders::subfolder::*;
use artcraft_api_defs::craft_apps::release_info::*;
use artcraft_api_defs::craft_apps::releases::*;
use artcraft_api_defs::tags::add_media_file_tags::*;
use artcraft_api_defs::tags::bulk_add_tags::*;
use artcraft_api_defs::tags::bulk_list_media_file_tags::*;
@@ -736,10 +734,6 @@ use crate::http_server::endpoints::media_files::list::list_batch_generated_redux
crate::http_server::endpoints::folders::media_files::bulk_move_folder_media_files_handler::bulk_move_folder_media_files_handler,
crate::http_server::endpoints::folders::media_files::bulk_remove_folder_media_files_handler::bulk_remove_folder_media_files_handler,
// Craft Apps
crate::http_server::endpoints::craft_apps::get_craft_apps_release_info_handler::get_craft_apps_release_info_handler,
crate::http_server::endpoints::craft_apps::get_craft_app_releases_handler::get_craft_app_releases_handler,
// Tags
crate::http_server::endpoints::tags::list_tags_handler::list_tags_handler,
crate::http_server::endpoints::tags::list_media_file_tags_handler::list_media_file_tags_handler,
@@ -1612,23 +1606,6 @@ use crate::http_server::endpoints::media_files::list::list_batch_generated_redux
ListTaggedMediaFilesSuccessResponse,
ListTagsQueryParams,
ListTagsSuccessResponse,
GetCraftAppsReleaseInfoResponse,
GetCraftAppReleasesResponse,
GetCraftAppReleasesError,
CraftAppsReleaseInfo,
CraftAppReleaseInfo,
CraftAppRelease,
CraftAppReleaseSummary,
CraftAppReleaseAsset,
CraftAppAssetPlatform,
CraftAppOs,
CraftAppArch,
CraftAppPackageType,
CraftAppRename,
CraftAppRepoRename,
CraftAppsImportantNotices,
CraftAppsAnnouncement,
CraftAppsAlert,
ListUntaggedMediaFilesQueryParams,
ListUntaggedMediaFilesSuccessResponse,
MediaFileTagsEntry,
@@ -1,107 +0,0 @@
use std::sync::Arc;
use actix_web::http::header::{CacheControl, CacheDirective};
use actix_web::{web, HttpResponse};
use artcraft_api_defs::craft_apps::releases::{GetCraftAppReleasesError, GetCraftAppReleasesResponse};
use crate::state::craft_apps_release_cache::CachedCraftApp;
use crate::state::server_state::ServerState;
/// Shared caches (Cloudflare) may serve the same answer for this long once the app has been
/// fetched: the data changes at most once per polling interval.
const CACHE_MAX_AGE_SECS: u32 = 60;
/// One Craft App's release history (every published release, with files and checksums), as
/// storyteller-web last fetched it from GitHub. `404` for an app it doesn't poll. Before the
/// first fetch the history is empty and `app_last_fetched` is absent.
#[utoipa::path(
get,
tag = "Craft Apps",
path = "/v1/craft_apps/{app_key}/releases",
params(("app_key" = String, Path, description = "The app's lowercase machine name, e.g. `photocraft`")),
responses(
(status = 200, body = GetCraftAppReleasesResponse),
(status = 404, body = GetCraftAppReleasesError),
),
)]
pub async fn get_craft_app_releases_handler(
path: web::Path<String>,
server_state: web::Data<Arc<ServerState>>,
) -> HttpResponse {
let app_key = path.into_inner().to_lowercase();
let Some(app) = server_state.craft_apps_release_cache.app(&app_key) else {
return HttpResponse::NotFound()
.insert_header(CacheControl(vec![CacheDirective::NoStore]))
.json(GetCraftAppReleasesError { success: false, error_reason: format!("no releases are known for app '{}'", truncate_key(&app_key)) });
};
let response = releases_response(app_key, &app);
let cache_control = if response.app_last_fetched.is_some() && !app.history_is_behind() {
CacheControl(vec![CacheDirective::Public, CacheDirective::MaxAge(CACHE_MAX_AGE_SECS)])
} else {
CacheControl(vec![CacheDirective::NoStore])
};
HttpResponse::Ok()
.insert_header(cache_control)
.json(response)
}
/// What the endpoint serves for `app`. A history still to be read from Redis (another instance
/// fetched newer releases) is served as it is, but never as complete, nor cached.
fn releases_response(app_key: String, app: &CachedCraftApp) -> GetCraftAppReleasesResponse {
GetCraftAppReleasesResponse {
success: true,
app_key,
name: app.name.clone(),
repo: app.repo.clone(),
app_last_fetched: app.app_last_fetched,
complete: app.history.complete && !app.history_is_behind(),
releases: app.history.releases.clone(),
}
}
/// The requested key, cut short for the error message (it comes from the URL).
fn truncate_key(key: &str) -> String {
key.chars().take(64).collect()
}
#[cfg(test)]
mod tests {
use chrono::Utc;
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases, CraftAppsReleaseCache};
use super::*;
#[test]
fn serves_the_history_of_a_fetched_app() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let unfetched = releases_response("photocraft".into(), &cache.app("photocraft").unwrap());
assert!(unfetched.app_last_fetched.is_none() && unfetched.releases.is_empty());
let history = CraftAppHistory { etag: None, complete: false, releases: Vec::new(), fetched_at: None };
cache.store("photocraft", CraftAppReleases::default(), history, None, Utc::now());
let fetched = releases_response("photocraft".into(), &cache.app("photocraft").unwrap());
assert!(fetched.app_last_fetched.is_some());
assert!(!fetched.complete, "an incomplete history says so");
assert_eq!(fetched.repo, "storytold/photocraft");
}
#[test]
fn a_history_behind_its_releases_is_never_called_complete() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let complete = CraftAppHistory { etag: Some("\"a\"".into()), complete: true, releases: Vec::new(), fetched_at: None };
cache.store("photocraft", CraftAppReleases::default(), complete, Some("\"a\"".into()), Utc::now());
assert!(releases_response("photocraft".into(), &cache.app("photocraft").unwrap()).complete);
// Another instance fetched newer releases; their history isn't read yet.
cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"b\"".into()), Utc::now() + chrono::Duration::seconds(5), None);
assert!(!releases_response("photocraft".into(), &cache.app("photocraft").unwrap()).complete);
}
#[test]
fn an_error_never_echoes_a_long_key() {
assert_eq!(truncate_key(&"x".repeat(500)).len(), 64);
}
}
@@ -1,102 +0,0 @@
use std::sync::Arc;
use actix_web::http::header::{CacheControl, CacheDirective};
use actix_web::{web, HttpResponse};
use artcraft_api_defs::craft_apps::release_info::{CraftAppsImportantNotices, CraftAppsReleaseInfo, GetCraftAppsReleaseInfoResponse};
use crate::state::server_state::ServerState;
/// Shared caches (Cloudflare) may serve the same answer for this long once every app has been
/// fetched: the data changes at most once per polling interval.
const CACHE_MAX_AGE_SECS: u32 = 60;
/// The latest release of every Craft App (and ArtCraft Launcher), as storyteller-web last fetched
/// it from GitHub, plus app/repo renames and notices for the launcher. Never fails: before the
/// first fetch, apps are listed without a release and without `app_last_fetched`.
#[utoipa::path(
get,
tag = "Craft Apps",
path = "/v1/craft_apps/release_info",
responses(
(status = 200, body = GetCraftAppsReleaseInfoResponse),
),
)]
pub async fn get_craft_apps_release_info_handler(
server_state: web::Data<Arc<ServerState>>,
) -> HttpResponse {
let release_info = server_state.craft_apps_release_cache.snapshot();
let cache_control = cache_control_for(&release_info);
let response = GetCraftAppsReleaseInfoResponse {
success: true,
release_info,
// None yet. When there are, they're listed here (newest first).
app_renames: Vec::new(),
repo_renames: Vec::new(),
important_notices: CraftAppsImportantNotices::default(),
};
HttpResponse::Ok()
.insert_header(cache_control)
.json(response)
}
/// Cacheable only once every app has been fetched (`last_fetched` is set). Until then (an
/// instance that just started, or one whose first fetch failed) the answer is `no-store`, so a
/// shared cache never keeps handing out "not fetched yet" after this instance has warmed up.
fn cache_control_for(release_info: &CraftAppsReleaseInfo) -> CacheControl {
if release_info.last_fetched.is_some() {
CacheControl(vec![CacheDirective::Public, CacheDirective::MaxAge(CACHE_MAX_AGE_SECS)])
} else {
CacheControl(vec![CacheDirective::NoStore])
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use chrono::Utc;
use artcraft_api_defs::craft_apps::release_info::CraftAppReleaseInfo;
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases, CraftAppsReleaseCache};
use super::*;
#[test]
fn a_fully_fetched_answer_is_cacheable() {
let release_info = CraftAppsReleaseInfo { apps: BTreeMap::new(), last_fetched: Some(Utc::now()) };
assert_eq!(cache_control_for(&release_info).to_string(), "public, max-age=60");
}
#[test]
fn an_answer_with_unfetched_apps_is_never_stored() {
let release_info = CraftAppsReleaseInfo { apps: BTreeMap::new(), last_fetched: None };
assert_eq!(cache_control_for(&release_info).to_string(), "no-store");
}
/// Deployed launchers read `latest_release` and `app_last_fetched` per app: the channels and
/// the version list are added beside them, never in their place.
#[test]
fn every_app_keeps_its_original_fields_beside_the_new_ones() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
cache.store("photocraft", CraftAppReleases::default(), CraftAppHistory::default(), None, Utc::now());
let json = serde_json::to_value(cache.snapshot()).unwrap();
let app = json["apps"]["photocraft"].as_object().unwrap();
for field in ["name", "repo", "latest_release", "app_last_fetched", "latest_prerelease", "latest_nightly", "releases"] {
assert!(app.contains_key(field), "{}", field);
}
assert_eq!(app["repo"], "storytold/photocraft");
assert!(app["releases"].as_array().unwrap().is_empty());
assert!(json["last_fetched"].is_string());
}
/// An answer from before the channels existed still reads, with them empty.
#[test]
fn an_app_without_the_new_fields_still_reads() {
let old = r#"{"name":"PhotoCraft","repo":"storytold/photocraft","latest_release":null,"app_last_fetched":null}"#;
let app: CraftAppReleaseInfo = serde_json::from_str(old).unwrap();
assert!(app.latest_prerelease.is_none() && app.latest_nightly.is_none() && app.releases.is_empty());
}
}
@@ -1,2 +0,0 @@
pub mod get_craft_app_releases_handler;
pub mod get_craft_apps_release_info_handler;
@@ -5,7 +5,6 @@ pub mod beta_keys;
pub mod billing_fakeyou;
pub mod characters;
pub mod comments;
pub mod craft_apps;
pub mod credits;
pub mod dev;
pub mod download_job;
@@ -63,7 +63,6 @@ use crate::startup::setup_inference_providers::{
use crate::startup::setup_pager::build_pager;
use crate::startup::setup_static_feature_flags::setup_static_feature_flags;
use crate::state::certs::google_sign_in_cert::GoogleSignInCert;
use crate::state::craft_apps_release_cache::CraftAppsReleaseCache;
use crate::state::memory_cache::model_token_to_info_cache::ModelTokenToInfoCache;
use crate::state::server_state::{
Dashboards, DataboxDashboards, DurableInMemoryCaches, EnvConfig, EphemeralInMemoryCaches,
@@ -705,7 +704,6 @@ pub(crate) fn build_test_server_state(pool: MySqlPool, media_cdn_override_url: S
sort_key_crypto: WebSortKeyCrypto::new("test-sort-key"),
opaque_cursors: WebOpaqueCursorEncoderV2::new("test-sort-key"),
ip_ban_list: IpBanList::new(),
craft_apps_release_cache: CraftAppsReleaseCache::new(),
cidr_ban_set: BannedCidrSet::new(),
troll_bans: TrollBans {
user_tokens: TrollUserBanList::new(),
@@ -3,7 +3,6 @@ use crate::http_server::routes::application_routes::api_keys_routes::add_api_key
use crate::http_server::routes::application_routes::billing_fakeyou_routes::add_billing_fakeyou_routes;
use crate::http_server::routes::application_routes::character_routes::add_character_routes;
use crate::http_server::routes::application_routes::comments_routes::add_comments_routes;
use crate::http_server::routes::application_routes::craft_apps_routes::add_craft_apps_routes;
use crate::http_server::routes::application_routes::credits_routes::add_credits_routes;
use crate::http_server::routes::application_routes::dev_routes::add_dev_routes;
use crate::http_server::routes::application_routes::featured_item_routes::add_featured_item_routes;
@@ -77,7 +76,6 @@ where
app = add_video_info_routes(app); // /v1/video_info/... (video provenance detection)
app = add_analytics_routes(app); // /v1/analytics/...
app = add_web_referrals_routes(app); // /v1/web_referrals/...
app = add_craft_apps_routes(app); // /v1/craft_apps/... (ArtCraft Launcher release info)
app = add_dev_routes(app); // /v1/dev/... — dev-only error/response shape probes
// User and user-adjacent routes
@@ -1,35 +0,0 @@
use actix_http::body::MessageBody;
use actix_service::ServiceFactory;
use actix_web::dev::{ServiceRequest, ServiceResponse};
use actix_web::{web, App, Error, HttpResponse};
use crate::http_server::endpoints::craft_apps::get_craft_app_releases_handler::get_craft_app_releases_handler;
use crate::http_server::endpoints::craft_apps::get_craft_apps_release_info_handler::get_craft_apps_release_info_handler;
pub fn add_craft_apps_routes<T, B>(app: App<T>) -> App<T>
where
B: MessageBody,
T: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
{
app.service(
web::scope("/v1/craft_apps")
// Release info for ArtCraft Launcher (polled instead of GitHub).
.service(
web::resource("/release_info")
.route(web::get().to(get_craft_apps_release_info_handler))
.route(web::head().to(|| HttpResponse::Ok())),
)
// One app's release history (choosing a version, going back, nightlies).
.service(
web::resource("/{app_key}/releases")
.route(web::get().to(get_craft_app_releases_handler))
.route(web::head().to(get_craft_app_releases_handler)),
),
)
}
@@ -3,7 +3,6 @@ mod api_keys_routes;
mod billing_fakeyou_routes;
mod character_routes;
mod comments_routes;
mod craft_apps_routes;
mod credits_routes;
mod dev_routes;
mod featured_item_routes;
@@ -37,7 +37,6 @@ use errors::AnyhowResult;
use log::{info, warn};
use server_environment::ServerEnvironment;
use shared_env_var_config::logging::DEFAULT_RUST_LOG;
use shared_env_var_config::redis::env_get_redis_0_connection_string_or_default;
use tokio::runtime::Runtime;
use user_traits_component::traits::internal_session_cache_purge::InternalSessionCachePurge;
@@ -56,9 +55,6 @@ use crate::startup::setup_disabled_endpoints::read_disabled_endpoints;
use crate::state::server_state::ServerState;
use crate::threads::db_health_checker_thread::db_health_checker_thread::db_health_checker_thread;
use crate::threads::expire_login_challenges::expire_login_challenges;
use crate::threads::poll_craft_app_releases_thread::config::CraftAppsPollConfig;
use crate::threads::poll_craft_app_releases_thread::poll_craft_app_releases::poll_craft_app_releases;
use crate::threads::poll_craft_app_releases_thread::shared_store::build_poller_redis_pool;
use crate::threads::poll_ip_banlist_thread::poll_ip_bans;
use crate::threads::poll_model_token_info_thread::poll_model_token_info_thread;
@@ -154,18 +150,6 @@ async fn main() -> AnyhowResult<()> {
poll_model_token_info_thread(model_token_info_cache_clone, mysql_pool_clone).await;
});
info!("Spawning craft app release polling thread.");
let craft_apps_release_cache_clone = server_state.craft_apps_release_cache.clone();
let craft_apps_poll_config = CraftAppsPollConfig::from_env();
// Its own small pool with I/O timeouts, so a hung Redis can't tie up the handlers' pool.
let craft_apps_redis_pool = build_poller_redis_pool(&env_get_redis_0_connection_string_or_default())?;
let hostname_clone = server_state.hostname.clone();
tokio_runtime.spawn(async move {
poll_craft_app_releases(craft_apps_release_cache_clone, craft_apps_poll_config, craft_apps_redis_pool, hostname_clone).await;
});
// ==================== Metrics worker ==================== //
let metrics_collector = server_state.metrics.clone();
@@ -43,7 +43,6 @@ use crate::startup::setup_static_feature_flags::setup_static_feature_flags;
use crate::startup::setup_stripe_artcraft::setup_stripe_artcraft;
use crate::startup::setup_stripe_fakeyou::setup_stripe_fakeyou;
use crate::state::certs::google_sign_in_cert::GoogleSignInCert;
use crate::state::craft_apps_release_cache::CraftAppsReleaseCache;
use crate::state::memory_cache::model_token_to_info_cache::ModelTokenToInfoCache;
use crate::state::server_state::{
DurableInMemoryCaches, EnvConfig, EphemeralInMemoryCaches,
@@ -267,7 +266,6 @@ pub async fn setup_dependencies(server_hostname: &str) -> AnyhowResult<SetupResu
}
},
ip_ban_list,
craft_apps_release_cache: CraftAppsReleaseCache::new(),
cidr_ban_set,
troll_bans: TrollBans {
user_tokens: user_token_troll_bans,
@@ -1,476 +0,0 @@
//! The releases of every Craft App, as last fetched from GitHub by
//! `poll_craft_app_releases_thread` (directly, or from the fleet's shared copy in Redis), served
//! by `GET /v1/craft_apps/release_info` and, each app's whole history,
//! `GET /v1/craft_apps/{app}/releases`. The endpoint always answers from this memory, so trouble
//! with Redis or GitHub never breaks it.
//!
//! ## App keys
//!
//! Apps are keyed by their **app key**: the app's lowercase machine name, the same string the
//! Craft Apps use for their binaries, asset file names and `ai.storyteller.<key>` bundle ids.
//! For example `photocraft`, `pdfcraft`, `cadcraft`, and `artcraft-launcher` for ArtCraft Launcher
//! itself. The key is not the display name (`PhotoCraft`) and not the GitHub repo
//! (`storytold/photocraft`, whose project name can differ: the launcher's repo is
//! `storytold/craft-launcher`).
//!
//! The keys come from the polling config (`poll_craft_app_releases_thread::config`: the built-in
//! list, or `CRAFT_APPS_RELEASE_APPS`) and are served unchanged as the keys of
//! `release_info.apps`, which ArtCraft Launcher matches against its own app ids.
use std::collections::BTreeMap;
use std::sync::{Arc, PoisonError, RwLock};
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use artcraft_api_defs::craft_apps::release_info::{CraftAppRelease, CraftAppReleaseInfo, CraftAppReleaseSummary, CraftAppsReleaseInfo};
/// Shared between the polling thread and the HTTP handlers. Cheap to clone.
#[derive(Clone, Default)]
pub struct CraftAppsReleaseCache {
/// App key (lowercase machine name, e.g. `photocraft`; see the module docs) → what's known
/// about that app. A `BTreeMap` so the endpoint lists apps in a stable order.
inner: Arc<RwLock<BTreeMap<String, CachedCraftApp>>>,
}
/// One app: what's known about it, and the ETag to revalidate it with.
#[derive(Clone, Debug)]
pub struct CachedCraftApp {
/// Display name (`PhotoCraft`).
pub name: String,
/// GitHub repository, `organization/project` (`storytold/photocraft`).
pub repo: String,
/// What the last fetch found. Empty both before the first fetch and when the repository has
/// no release; `app_last_fetched` tells the two apart.
pub releases: CraftAppReleases,
/// When this app's release was last fetched (or confirmed unchanged) successfully. `None`
/// until the first success.
pub app_last_fetched: Option<DateTime<Utc>>,
/// GitHub's ETag for the last successful answer, sent back as `If-None-Match` so an unchanged
/// release costs a `304`.
pub etag: Option<String>,
/// When a request for this app last failed. Only meaningful when newer than
/// `app_last_fetched`; it delays the next attempt so a broken repo isn't retried every tick.
pub last_failed_at: Option<DateTime<Utc>>,
/// How many requests in a row have failed since the last success (when `last_failed_at` is
/// newer than `app_last_fetched`).
pub consecutive_failures: u32,
/// The app's whole release history. Shared, since it can be large and `app` is cloned often.
pub history: Arc<CraftAppHistory>,
/// Whether `history` belongs to the fetch `releases` came from. False once another instance's
/// newer fetch was taken until its history is read from Redis; not the ETag's job, since a fetch
/// may have none.
pub history_current: bool,
/// The fleet's shared history for the current releases isn't in Redis (expired or evicted):
/// this instance fetches the app again in full, so the history is written anew.
pub history_missing: bool,
}
/// An app's release history: every published release, newest first, nightlies included, drafts
/// not. Also the JSON the fleet shares in Redis, apart from the rest (`shared_entry`).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CraftAppHistory {
/// GitHub's ETag for the first page of the fetch this history came from: it belongs with the
/// releases fetched under the same ETag, and is replaced when those are.
pub etag: Option<String>,
/// Whether `releases` is every release GitHub lists (the last page read wasn't full).
pub complete: bool,
pub releases: Vec<CraftAppRelease>,
/// When the whole list was last read from GitHub (a `200`, not a `304`). A `304` on the first
/// page says nothing about edits to older releases, so the list is read in full again after a
/// while (`FULL_REFRESH`).
#[serde(default)]
pub fetched_at: Option<DateTime<Utc>>,
}
/// Everything one fetch learns about an app's releases; the endpoint serves each field under the
/// same name. Also the JSON the fleet shares in Redis (`shared_entry`).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CraftAppReleases {
/// The stable release with the highest version (not a pre-release, not a nightly).
pub latest_release: Option<CraftAppRelease>,
/// The beta or release candidate with the highest version.
#[serde(default)]
pub latest_prerelease: Option<CraftAppRelease>,
/// The newest nightly build.
#[serde(default)]
pub latest_nightly: Option<CraftAppRelease>,
/// The recent stable releases and pre-releases, newest first.
#[serde(default)]
pub releases: Vec<CraftAppReleaseSummary>,
}
impl CraftAppsReleaseCache {
pub fn new() -> Self {
Self::default()
}
/// Makes sure every app in `apps` has an entry, so the endpoint reports apps that haven't been
/// fetched yet. Each tuple is `(app key, display name, repo)`, for example
/// `("photocraft", "PhotoCraft", "storytold/photocraft")`. Apps already present keep what
/// was fetched for them.
pub fn register_apps(&self, apps: &[(String, String, String)]) {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
for (key, name, repo) in apps {
map.entry(key.clone()).or_insert_with(|| CachedCraftApp {
name: name.clone(),
repo: repo.clone(),
releases: CraftAppReleases::default(),
app_last_fetched: None,
etag: None,
last_failed_at: None,
consecutive_failures: 0,
history: Arc::default(),
history_current: false,
history_missing: false,
});
}
}
/// The ETag of the last successful answer for the app with app key `key` (`photocraft`), to
/// send as `If-None-Match`.
pub fn etag(&self, key: &str) -> Option<String> {
let map = self.inner.read().unwrap_or_else(PoisonError::into_inner);
map.get(key).and_then(|app| app.etag.clone())
}
/// Records a complete, successful fetch of the app with app key `key` (`photocraft`): its
/// releases (empty if it has none) and history. Ignored for keys that were never registered.
pub fn store(&self, key: &str, releases: CraftAppReleases, history: CraftAppHistory, etag: Option<String>, fetched_at: DateTime<Utc>) {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
if let Some(app) = map.get_mut(key) {
app.releases = releases;
app.history = Arc::new(history);
app.history_current = true;
app.history_missing = false;
app.etag = etag;
app.app_last_fetched = Some(fetched_at);
}
}
/// Records that GitHub confirmed the app with app key `key` (`photocraft`) is unchanged
/// (`304 Not Modified`). Ignored for keys that were never registered.
pub fn confirm_unchanged(&self, key: &str, fetched_at: DateTime<Utc>) {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
if let Some(app) = map.get_mut(key) {
app.app_last_fetched = Some(fetched_at);
}
}
/// A copy of what's known about the app with app key `key` (`photocraft`).
pub fn app(&self, key: &str) -> Option<CachedCraftApp> {
let map = self.inner.read().unwrap_or_else(PoisonError::into_inner);
map.get(key).cloned()
}
/// Takes a fetch made elsewhere (another instance, through Redis) for the app with app key
/// `key`, if it is newer than what this instance has. Returns whether it was taken. Ignored for
/// keys that were never registered, so the registered app list stays authoritative.
pub fn merge_fetched(&self, key: &str, releases: CraftAppReleases, etag: Option<String>, fetched_at: DateTime<Utc>, history_at: Option<DateTime<Utc>>) -> bool {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
let Some(app) = map.get_mut(key) else {
return false;
};
if app.app_last_fetched.is_some_and(|mine| mine >= fetched_at) {
return false;
}
// A `304` elsewhere only moved the time: the history this instance has still belongs. A new or
// missing ETag may mean new releases, and a newer full read may have found edits to older ones
// (a `304` covers only the first page), so then the history is read from Redis.
let read_since = history_at.is_some_and(|shared| app.history.fetched_at.is_none_or(|mine| mine < shared));
if etag.is_none() || etag != app.etag || read_since {
app.history_current = false;
app.history_missing = false;
}
app.releases = releases;
app.etag = etag;
app.app_last_fetched = Some(fetched_at);
true
}
/// Takes a history shared elsewhere (another instance, through Redis) for the app with app key
/// `key`, when it belongs with the releases this instance has (the same ETag). Returns whether
/// it was taken.
pub fn merge_history(&self, key: &str, history: CraftAppHistory) -> bool {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
let Some(app) = map.get_mut(key) else {
return false;
};
if history.etag != app.etag || app.history_current {
return false;
}
app.history = Arc::new(history);
app.history_current = true;
app.history_missing = false;
true
}
/// Records that the shared history the app with app key `key` needs isn't in Redis.
pub fn mark_history_missing(&self, key: &str) {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
if let Some(app) = map.get_mut(key) {
app.history_missing = !app.history_current;
}
}
/// Records a failed request for the app with app key `key` (`photocraft`) and returns how many
/// have failed in a row since its last success. Ignored (returns 0) for unregistered keys.
pub fn record_failure(&self, key: &str, failed_at: DateTime<Utc>) -> u32 {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
let Some(app) = map.get_mut(key) else {
return 0;
};
app.consecutive_failures = if app.is_failing() { app.consecutive_failures.saturating_add(1) } else { 1 };
app.last_failed_at = Some(failed_at);
app.consecutive_failures
}
/// Takes a failure recorded elsewhere (another instance, through Redis) for the app with app
/// key `key`, if it is newer than the one this instance knows.
pub fn merge_failure(&self, key: &str, failed_at: DateTime<Utc>, consecutive_failures: u32) {
let mut map = self.inner.write().unwrap_or_else(PoisonError::into_inner);
if let Some(app) = map.get_mut(key) {
if app.last_failed_at.is_none_or(|mine| mine < failed_at) {
app.last_failed_at = Some(failed_at);
app.consecutive_failures = consecutive_failures;
}
}
}
/// Everything, as the endpoint serves it: `apps` keyed by app key.
pub fn snapshot(&self) -> CraftAppsReleaseInfo {
let map = self.inner.read().unwrap_or_else(PoisonError::into_inner);
let apps: BTreeMap<String, CraftAppReleaseInfo> = map
.iter()
.map(|(key, app)| {
(key.clone(), CraftAppReleaseInfo {
name: app.name.clone(),
repo: app.repo.clone(),
latest_release: app.releases.latest_release.clone(),
app_last_fetched: app.app_last_fetched,
latest_prerelease: app.releases.latest_prerelease.clone(),
latest_nightly: app.releases.latest_nightly.clone(),
releases: app.releases.releases.clone(),
})
})
.collect();
let last_fetched = least_recently_fetched(&apps);
CraftAppsReleaseInfo { apps, last_fetched }
}
}
impl CachedCraftApp {
/// Whether the history is not the one fetched with the current releases (it came from another
/// instance's fetch and is still to be read from Redis).
pub fn history_is_behind(&self) -> bool {
self.app_last_fetched.is_some() && !self.history_current
}
/// Whether the last request for this app failed (no success since).
pub fn is_failing(&self) -> bool {
match (self.last_failed_at, self.app_last_fetched) {
(Some(failed), Some(fetched)) => failed > fetched,
(Some(_), None) => true,
(None, _) => false,
}
}
}
/// The oldest `app_last_fetched`, or `None` while any app has never been fetched.
fn least_recently_fetched(apps: &BTreeMap<String, CraftAppReleaseInfo>) -> Option<DateTime<Utc>> {
if apps.is_empty() {
return None;
}
let mut oldest: Option<DateTime<Utc>> = None;
for app in apps.values() {
let fetched = app.app_last_fetched?;
oldest = Some(oldest.map_or(fetched, |o| o.min(fetched)));
}
oldest
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use super::*;
#[test]
fn the_snapshot_serves_every_channel() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let stable = release("v0.5.0", false);
let beta = release("v0.6.0-rc.1", true);
let releases = CraftAppReleases {
releases: vec![(&beta).into(), (&stable).into()],
latest_release: Some(stable),
latest_prerelease: Some(beta),
latest_nightly: Some(release("v0.6.0-nightly.20261126.1.1", true)),
};
cache.store("photocraft", releases, CraftAppHistory::default(), None, Utc::now());
let app = &cache.snapshot().apps["photocraft"];
assert_eq!(app.latest_release.as_ref().map(|r| r.tag.as_str()), Some("v0.5.0"));
assert_eq!(app.latest_prerelease.as_ref().map(|r| r.tag.as_str()), Some("v0.6.0-rc.1"));
assert_eq!(app.latest_nightly.as_ref().map(|r| r.tag.as_str()), Some("v0.6.0-nightly.20261126.1.1"));
let versions: Vec<&str> = app.releases.iter().map(|r| r.tag.as_str()).collect();
assert_eq!(versions, ["v0.6.0-rc.1", "v0.5.0"]);
}
fn release(tag: &str, prerelease: bool) -> CraftAppRelease {
CraftAppRelease {
tag: tag.into(),
version: tag.trim_start_matches('v').into(),
name: format!("PhotoCraft {tag}"),
published_at: None,
html_url: format!("https://github.com/storytold/photocraft/releases/tag/{tag}"),
prerelease,
notes_markdown: String::new(),
assets: Vec::new(),
}
}
#[test]
fn a_shared_history_is_taken_only_with_the_releases_it_belongs_to() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let at = Utc::now();
let history = |etag: &str| CraftAppHistory { etag: Some(etag.into()), complete: true, releases: vec![release("v0.5.0", false)], fetched_at: None };
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"b\"".into()), at, None));
assert!(cache.app("photocraft").unwrap().history_is_behind());
assert!(!cache.merge_history("photocraft", history("\"a\"")), "from an older fetch");
assert!(cache.merge_history("photocraft", history("\"b\"")));
assert!(!cache.app("photocraft").unwrap().history_is_behind());
assert!(!cache.merge_history("photocraft", history("\"b\"")), "already there");
assert_eq!(cache.app("photocraft").unwrap().history.releases.len(), 1);
}
/// A `304` elsewhere (same ETag, later time) keeps this instance's history; a new ETag doesn't.
#[test]
fn only_new_releases_send_an_instance_back_for_their_history() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let at = Utc::now();
let history = CraftAppHistory { etag: Some("\"a\"".into()), complete: true, releases: Vec::new(), fetched_at: Some(at) };
cache.store("photocraft", CraftAppReleases::default(), history, Some("\"a\"".into()), at);
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"a\"".into()), at + chrono::Duration::minutes(2), None));
assert!(!cache.app("photocraft").unwrap().history_is_behind(), "same ETag: nothing to read");
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"b\"".into()), at + chrono::Duration::minutes(4), None));
assert!(cache.app("photocraft").unwrap().history_is_behind());
cache.mark_history_missing("photocraft");
assert!(cache.app("photocraft").unwrap().history_missing);
}
/// Another instance's full read (same ETag: page 1 didn't change) may have found edits to older
/// releases, so a history read in full after this instance's own is read from Redis too.
#[test]
fn a_newer_full_read_elsewhere_sends_an_instance_back_for_the_history() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let at = Utc::now();
let history = CraftAppHistory { etag: Some("\"a\"".into()), complete: true, releases: Vec::new(), fetched_at: Some(at) };
cache.store("photocraft", CraftAppReleases::default(), history, Some("\"a\"".into()), at);
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"a\"".into()), at + chrono::Duration::minutes(2), Some(at)));
assert!(!cache.app("photocraft").unwrap().history_is_behind(), "the full read this instance already has");
let later = at + chrono::Duration::hours(6);
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"a\"".into()), later, Some(later)));
assert!(cache.app("photocraft").unwrap().history_is_behind());
}
/// A fetch without an ETag still has its history read from Redis: "none" is not "already here".
#[test]
fn a_shared_fetch_without_an_etag_still_takes_its_history() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), None, Utc::now(), None));
assert!(cache.app("photocraft").unwrap().history_is_behind());
let history = CraftAppHistory { etag: None, complete: true, releases: vec![release("v0.5.0", false)], fetched_at: None };
assert!(cache.merge_history("photocraft", history));
assert!(!cache.app("photocraft").unwrap().history_is_behind());
assert_eq!(cache.app("photocraft").unwrap().history.releases.len(), 1);
}
#[test]
fn last_fetched_is_the_oldest_app_and_absent_until_all_are_fetched() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[
("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into()),
("filmcraft".into(), "FilmCraft".into(), "storytold/filmcraft".into()),
]);
assert_eq!(cache.snapshot().apps.len(), 2);
assert_eq!(cache.snapshot().last_fetched, None);
let early = Utc.with_ymd_and_hms(2026, 10, 10, 1, 0, 0).unwrap();
let late = Utc.with_ymd_and_hms(2026, 10, 10, 2, 0, 0).unwrap();
cache.store("photocraft", CraftAppReleases::default(), CraftAppHistory::default(), Some("\"abc\"".into()), late);
assert_eq!(cache.snapshot().last_fetched, None, "filmcraft hasn't been fetched yet");
cache.confirm_unchanged("filmcraft", early);
assert_eq!(cache.snapshot().last_fetched, Some(early));
assert_eq!(cache.etag("photocraft").as_deref(), Some("\"abc\""));
}
#[test]
fn registering_again_keeps_what_was_fetched() {
let cache = CraftAppsReleaseCache::new();
let apps = [("photocraft".to_string(), "PhotoCraft".to_string(), "storytold/photocraft".to_string())];
cache.register_apps(&apps);
let now = Utc::now();
cache.confirm_unchanged("photocraft", now);
cache.register_apps(&apps);
assert_eq!(cache.snapshot().apps["photocraft"].app_last_fetched, Some(now));
}
#[test]
fn merging_takes_only_newer_fetches_of_registered_apps() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let early = Utc.with_ymd_and_hms(2026, 10, 10, 1, 0, 0).unwrap();
let late = Utc.with_ymd_and_hms(2026, 10, 10, 2, 0, 0).unwrap();
assert!(cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"new\"".into()), late, None));
assert!(!cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"old\"".into()), early, None), "older than ours");
assert!(!cache.merge_fetched("photocraft", CraftAppReleases::default(), Some("\"same\"".into()), late, None), "no newer than ours");
assert!(!cache.merge_fetched("unknowncraft", CraftAppReleases::default(), None, late, None), "not registered");
let snapshot = cache.snapshot();
assert_eq!(snapshot.apps.len(), 1);
assert_eq!(snapshot.apps["photocraft"].app_last_fetched, Some(late));
assert_eq!(cache.etag("photocraft").as_deref(), Some("\"new\""));
}
#[test]
fn failures_count_up_until_a_success() {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&[("photocraft".into(), "PhotoCraft".into(), "storytold/photocraft".into())]);
let t = |h| Utc.with_ymd_and_hms(2026, 10, 10, h, 0, 0).unwrap();
assert_eq!(cache.record_failure("photocraft", t(1)), 1);
assert_eq!(cache.record_failure("photocraft", t(2)), 2);
assert!(cache.app("photocraft").unwrap().is_failing());
cache.store("photocraft", CraftAppReleases::default(), CraftAppHistory::default(), None, t(3));
assert!(!cache.app("photocraft").unwrap().is_failing());
assert_eq!(cache.record_failure("photocraft", t(4)), 1, "counting restarts after a success");
cache.merge_failure("photocraft", t(3), 9);
assert_eq!(cache.app("photocraft").unwrap().consecutive_failures, 1, "older failure ignored");
cache.merge_failure("photocraft", t(5), 4);
assert_eq!(cache.app("photocraft").unwrap().consecutive_failures, 4);
}
}
@@ -1,6 +1,5 @@
pub mod cached_queries;
pub mod flags;
pub mod certs;
pub mod craft_apps_release_cache;
pub mod memory_cache;
pub mod server_state;
@@ -1,7 +1,6 @@
use std::collections::HashSet;
use crate::configs::app_startup::username_set::UsernameSet;
use crate::state::craft_apps_release_cache::CraftAppsReleaseCache;
use crate::configs::static_api_tokens::StaticApiTokenSet;
use crate::http_server::deprecated_endpoints::categories::tts::list_fully_computed_assigned_tts_categories::list_fully_computed_assigned_tts_categories::ModelTokensByCategoryToken;
use crate::http_server::endpoints::media_files::list::list_featured_media_files_handler::ListFeaturedMediaFilesQueryParams;
@@ -126,9 +125,6 @@ pub struct ServerState {
pub caches: InMemoryCaches,
/// The latest Craft App releases, kept fresh by `poll_craft_app_releases_thread`.
pub craft_apps_release_cache: CraftAppsReleaseCache,
pub google_sign_in_cert: GoogleSignInCert,
pub temp_dir_creator: ScopedTempDirCreator,
@@ -1,5 +1,4 @@
pub mod db_health_checker_thread;
pub mod expire_login_challenges;
pub mod poll_craft_app_releases_thread;
pub mod poll_ip_banlist_thread;
pub mod poll_model_token_info_thread;
@@ -1,177 +0,0 @@
//! How storyteller-web polls GitHub for Craft App releases, from the environment.
//!
//! | Variable | Default | Meaning |
//! |-------------------------------------------|-----------------------------|---------------------------------------------------------------|
//! | `CRAFT_APPS_RELEASE_POLLING_ENABLED` | `true` | Poll at all (the endpoint still answers) |
//! | `CRAFT_APPS_RELEASE_COORDINATION_ENABLED` | `true` | Share releases and backoff through Redis (see below) |
//! | `CRAFT_APPS_RELEASE_POLL_INTERVAL_SECS` | `120`; `1800` with no token | How old a release may get; at least `60`; `300` with no token |
//! | `CRAFT_APPS_RELEASE_MAX_BACKOFF_SECS` | `14400` (4 h) | Longest wait after repeated failures/rate limits |
//! | `CRAFT_APPS_RELEASE_GITHUB_TOKEN` | (none; optional) | Raises GitHub's limit from 60 to 5000 per hour |
//! | `CRAFT_APPS_RELEASE_APPS` | built-in list | `key=Name=org/repo,…` to replace the app list |
//!
//! The GitHub token is optional. Unset, empty or blank, polling still runs: requests go out
//! without an `Authorization` header, and the interval defaults to the slow no-token value.
//!
//! With coordination (the default), the fleet shares each app's release, ETag and fetch time in
//! Redis, so the whole fleet requests an app from GitHub about once per interval instead of every
//! pod doing so. That is what makes the 2 minute default safe with a token. Without a token
//! GitHub allows 60 requests an hour per IP address and also counts `304`s, so the interval stays
//! at 30 minutes (20 apps: about 40 requests an hour, nearly all `304`s; a new release of an app
//! with more than 100 releases costs one more request per further page of its history, up to
//! nine). While Redis is unreachable (or with coordination off) every pod polls on its own at the
//! same interval.
use std::time::Duration;
const DEFAULT_INTERVAL_SECS_WITH_TOKEN: u64 = 120;
const MIN_INTERVAL_SECS_WITH_TOKEN: u64 = 60;
const DEFAULT_INTERVAL_SECS_WITHOUT_TOKEN: u64 = 1800;
const MIN_INTERVAL_SECS_WITHOUT_TOKEN: u64 = 300;
const DEFAULT_MAX_BACKOFF_SECS: u64 = 14_400;
/// The Craft Apps the launcher knows: `(app key, display name, GitHub repo)`. The app key is
/// the app's lowercase machine name; it keys `CraftAppsReleaseCache` and the endpoint's
/// `release_info.apps`, and must match the app id ArtCraft Launcher uses. ArtCraft Launcher is
/// included (key `artcraft-launcher`, repo `storytold/craft-launcher`) so it can check for its
/// own updates. Community apps the launcher offers (SolidCraft, MailCraft) are listed with their
/// own repositories, which must be the ones in the launcher's catalog: it ignores an entry whose
/// repo differs.
const DEFAULT_APPS: &[(&str, &str, &str)] = &[
("photocraft", "PhotoCraft", "storytold/photocraft"),
("vectorcraft", "VectorCraft", "storytold/vectorcraft"),
("filmcraft", "FilmCraft", "storytold/filmcraft"),
("lightcraft", "LightCraft", "storytold/lightcraft"),
("pdfcraft", "PdfCraft", "storytold/pdfcraft"),
("effectcraft", "EffectCraft", "storytold/effectcraft"),
("designcraft", "DesignCraft", "storytold/designcraft"),
("wordcraft", "WordCraft", "storytold/wordcraft"),
("deckcraft", "DeckCraft", "storytold/deckcraft"),
("gridcraft", "GridCraft", "storytold/gridcraft"),
("craft-anything", "Craft Anything", "storytold/craft-anything"),
("cadcraft", "CADCraft", "storytold/cadcraft"),
("soundcraft", "SoundCraft", "storytold/soundcraft"),
("figcraft", "FigCraft", "storytold/figcraft"),
("texturecraft", "TextureCraft", "storytold/texturecraft"),
("materialcraft", "MaterialCraft", "storytold/materialcraft"),
("anicraft", "AniCraft", "storytold/anicraft"),
("solidcraft", "SolidCraft", "tangency-labs/solidcraft"),
("mailcraft", "MailCraft", "UCSLabs/mailcraft"),
("artcraft-launcher", "ArtCraft Launcher", "storytold/craft-launcher"),
];
#[derive(Clone, Debug)]
pub struct CraftAppsPollConfig {
pub enabled: bool,
/// Share releases and backoff with the fleet through Redis; when false (or while Redis is
/// unreachable) this pod polls on its own.
pub coordination_enabled: bool,
/// How old an app's release may get before it is requested from GitHub again.
pub interval: Duration,
pub max_backoff: Duration,
/// Never empty or blank: those are read as no token.
pub github_token: Option<String>,
/// `(app key, display name, repo)`; see [`DEFAULT_APPS`].
pub apps: Vec<(String, String, String)>,
}
impl CraftAppsPollConfig {
pub fn from_env() -> Self {
let github_token = non_blank_token(easyenv::get_env_string_optional("CRAFT_APPS_RELEASE_GITHUB_TOKEN"));
let has_token = github_token.is_some();
let default_interval = default_interval_secs(has_token);
let requested_interval = easyenv::get_env_num::<u64>("CRAFT_APPS_RELEASE_POLL_INTERVAL_SECS", default_interval)
.unwrap_or(default_interval);
let interval_secs = clamp_interval_secs(requested_interval, has_token);
let max_backoff_secs = easyenv::get_env_num::<u64>("CRAFT_APPS_RELEASE_MAX_BACKOFF_SECS", DEFAULT_MAX_BACKOFF_SECS)
.unwrap_or(DEFAULT_MAX_BACKOFF_SECS)
.max(interval_secs);
let apps = easyenv::get_env_string_optional("CRAFT_APPS_RELEASE_APPS")
.map(|v| parse_app_list(&v))
.filter(|apps| !apps.is_empty())
.unwrap_or_else(default_apps);
Self {
enabled: easyenv::get_env_bool_or_default("CRAFT_APPS_RELEASE_POLLING_ENABLED", true),
coordination_enabled: easyenv::get_env_bool_or_default("CRAFT_APPS_RELEASE_COORDINATION_ENABLED", true),
interval: Duration::from_secs(interval_secs),
max_backoff: Duration::from_secs(max_backoff_secs),
github_token,
apps,
}
}
}
pub fn default_apps() -> Vec<(String, String, String)> {
DEFAULT_APPS.iter().map(|(k, n, r)| (k.to_string(), n.to_string(), r.to_string())).collect()
}
/// The token, trimmed; `None` when unset, empty or blank.
fn non_blank_token(value: Option<String>) -> Option<String> {
value.map(|t| t.trim().to_string()).filter(|t| !t.is_empty())
}
fn default_interval_secs(has_token: bool) -> u64 {
if has_token { DEFAULT_INTERVAL_SECS_WITH_TOKEN } else { DEFAULT_INTERVAL_SECS_WITHOUT_TOKEN }
}
fn clamp_interval_secs(requested: u64, has_token: bool) -> u64 {
let min = if has_token { MIN_INTERVAL_SECS_WITH_TOKEN } else { MIN_INTERVAL_SECS_WITHOUT_TOKEN };
requested.max(min)
}
/// Reads `key=Name=org/repo,…` (app key, display name, repo). Keys are lowercased. Malformed
/// entries are skipped.
fn parse_app_list(value: &str) -> Vec<(String, String, String)> {
value
.split(',')
.filter_map(|entry| {
let mut parts = entry.trim().splitn(3, '=');
let key = parts.next()?.trim().to_lowercase();
let name = parts.next()?.trim().to_string();
let repo = parts.next()?.trim().to_string();
let valid_repo = repo.split('/').count() == 2 && !repo.starts_with('/') && !repo.ends_with('/');
(!key.is_empty() && !name.is_empty() && valid_repo).then_some((key, name, repo))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_an_app_list_and_skips_bad_entries() {
let apps = parse_app_list(" PhotoCraft=PhotoCraft=storytold/photocraft, junk, x=X=noslash, k=K=org/repo ");
assert_eq!(apps, vec![
("photocraft".to_string(), "PhotoCraft".to_string(), "storytold/photocraft".to_string()),
("k".to_string(), "K".to_string(), "org/repo".to_string()),
]);
}
#[test]
fn the_default_list_has_the_suite_and_the_launcher() {
let apps = default_apps();
assert_eq!(apps.len(), 20);
assert!(apps.iter().any(|(k, n, r)| k == "craft-anything" && n == "Craft Anything" && r == "storytold/craft-anything"));
assert!(apps.iter().any(|(k, _, r)| k == "artcraft-launcher" && r == "storytold/craft-launcher"));
assert!(apps.iter().any(|(k, _, r)| k == "solidcraft" && r == "tangency-labs/solidcraft"));
}
#[test]
fn a_missing_empty_or_blank_token_is_no_token() {
assert_eq!(non_blank_token(None), None);
assert_eq!(non_blank_token(Some(String::new())), None);
assert_eq!(non_blank_token(Some(" \n".to_string())), None);
assert_eq!(non_blank_token(Some(" ghp_x ".to_string())).as_deref(), Some("ghp_x"));
}
#[test]
fn the_interval_defaults_and_minimum_depend_on_the_token() {
assert_eq!(default_interval_secs(true), 120);
assert_eq!(default_interval_secs(false), 1800);
assert_eq!(clamp_interval_secs(10, true), 60);
assert_eq!(clamp_interval_secs(10, false), 300);
assert_eq!(clamp_interval_secs(90, true), 90);
assert_eq!(clamp_interval_secs(90, false), 300);
assert_eq!(clamp_interval_secs(3600, false), 3600);
}
}
@@ -1,97 +0,0 @@
//! Falling back to polling alone when Redis is unreachable, and saying so without flooding the
//! log every tick.
use std::time::{Duration, Instant};
use log::{info, warn};
/// While Redis keeps failing, repeat the warning at most this often.
const WARN_EVERY: Duration = Duration::from_secs(10 * 60);
/// How this tick works.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollMode {
/// With the fleet: shared releases, claims and backoff in Redis.
Coordinated,
/// Alone, from this instance's memory: coordination is off or Redis is unreachable. Same
/// interval and backoff rules, so a Redis outage never stops releases from refreshing.
Standalone,
}
/// Remembers Redis trouble so it is logged when it starts, every [`WARN_EVERY`] while it lasts,
/// and when it ends.
#[derive(Debug, Default)]
pub struct RedisTroubleLog {
failing_since: Option<Instant>,
last_warned: Option<Instant>,
suppressed: u32,
}
impl PollMode {
/// Coordinated only when coordination is on and the shared state could be read.
pub fn choose(coordination_enabled: bool, shared_state_readable: bool) -> Self {
if coordination_enabled && shared_state_readable { Self::Coordinated } else { Self::Standalone }
}
}
impl RedisTroubleLog {
/// Notes a Redis error; returns whether it was logged.
pub fn failed(&mut self, err: &anyhow::Error, now: Instant) -> bool {
self.failing_since.get_or_insert(now);
if self.last_warned.is_some_and(|last| now.duration_since(last) < WARN_EVERY) {
self.suppressed = self.suppressed.saturating_add(1);
return false;
}
warn!(
"Craft app releases: Redis unavailable ({:#}); polling GitHub on this instance alone until it is back ({} similar errors not logged).",
err, self.suppressed,
);
self.last_warned = Some(now);
self.suppressed = 0;
true
}
/// Notes that Redis works; logs the recovery once.
pub fn succeeded(&mut self, now: Instant) {
if let Some(since) = self.failing_since.take() {
info!("Craft app releases: Redis is back after {:?}; coordinating with the fleet again.", now.duration_since(since));
self.last_warned = None;
self.suppressed = 0;
}
}
pub fn is_failing(&self) -> bool {
self.failing_since.is_some()
}
}
#[cfg(test)]
mod tests {
use anyhow::anyhow;
use super::*;
#[test]
fn coordinates_only_when_enabled_and_redis_answers() {
assert_eq!(PollMode::choose(true, true), PollMode::Coordinated);
assert_eq!(PollMode::choose(true, false), PollMode::Standalone);
assert_eq!(PollMode::choose(false, true), PollMode::Standalone);
assert_eq!(PollMode::choose(false, false), PollMode::Standalone);
}
#[test]
fn warns_once_per_window_while_redis_keeps_failing() {
let mut log = RedisTroubleLog::default();
let start = Instant::now();
let err = anyhow!("connection refused");
assert!(log.failed(&err, start));
assert!(!log.failed(&err, start + Duration::from_secs(30)));
assert!(!log.failed(&err, start + Duration::from_secs(599)));
assert!(log.failed(&err, start + Duration::from_secs(600)));
assert!(log.is_failing());
log.succeeded(start + Duration::from_secs(700));
assert!(!log.is_failing());
assert!(log.failed(&err, start + Duration::from_secs(730)), "a new outage warns right away");
}
}
@@ -1,652 +0,0 @@
//! The requests to GitHub for an app's releases, and reading the answers.
//!
//! `GET /repos/{repo}/releases?per_page=100`, revalidated with the ETag: one request per app and
//! interval while nothing changed. When the first page changed (a `200`), the next pages are read
//! too while each is full, up to [`MAX_PAGES`]: the app's whole release history, which
//! `GET /v1/craft_apps/{app}/releases` serves (choosing a version, going back to one, nightly
//! discovery). [`sort_releases`] picks from it the stable release and the beta or release
//! candidate with the highest version, the newest nightly and the recent version list that
//! `release_info` serves.
//! Not `/releases/latest`: it never returns a pre-release, and GitHub lets a nightly without the
//! pre-release flag be the latest release.
use std::time::Duration;
use chrono::{DateTime, Utc};
use wreq::header::{ACCEPT, AUTHORIZATION, ETAG, IF_NONE_MATCH, RETRY_AFTER, USER_AGENT};
use wreq::StatusCode;
use serde_derive::Deserialize;
use artcraft_api_defs::craft_apps::release_info::{
CraftAppArch, CraftAppAssetPlatform, CraftAppOs, CraftAppPackageType, CraftAppRelease, CraftAppReleaseAsset,
};
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases};
const API_BASE: &str = "https://api.github.com";
/// Releases asked for in one request, GitHub's most. A page is up to 10 MB from GitHub today
/// (each release carries its notes and ~50 files), for an app with daily nightlies.
pub const RELEASES_PER_PAGE: usize = 100;
const MAX_NOTES_BYTES: usize = 64 * 1024;
const MAX_ASSETS: usize = 200;
/// The most pages read: the history stops (and is marked incomplete) after this many releases.
pub const MAX_PAGES: usize = 10;
/// The most entries in the version list `release_info` serves; the whole history is per app.
pub const MAX_VERSION_LIST: usize = 30;
/// A page of releases.
const MAX_LIST_BODY_BYTES: usize = 32 * 1024 * 1024;
/// What one fetch produced.
#[derive(Debug)]
pub enum FetchOutcome {
/// The app's releases (empty: the repository has no published release) and its history.
Fetched { releases: CraftAppReleases, history: CraftAppHistory, etag: Option<String> },
/// `If-None-Match` matched: what we have is current.
NotModified,
/// GitHub refused: out of quota until this time, if it said.
RateLimited { retry_at: Option<DateTime<Utc>> },
/// Network error, unexpected status or unreadable answer. Nothing is stored.
Failed(String),
}
/// What one request to GitHub produced, before reading the body.
enum Response {
Body { body: Vec<u8>, etag: Option<String> },
NotFound,
NotModified,
RateLimited { retry_at: Option<DateTime<Utc>> },
Failed(String),
}
pub fn build_client() -> wreq::Result<wreq::Client> {
wreq::Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.build()
}
/// `repo`'s releases: the first page, revalidated with `etag`, then the next pages while
/// [`read_more`] says so. `token` is optional: without one the requests are unauthenticated. All
/// or nothing: if a later page fails, so does the fetch, and [`settle`] fails one that found no
/// stable release in an incomplete history, rather than storing "no release" for an app that has
/// one further back.
pub async fn fetch_releases(client: &wreq::Client, repo: &str, etag: Option<&str>, token: Option<&str>) -> FetchOutcome {
let (body, etag) = match send(client, &list_url(repo, 1), etag, token).await {
Response::Body { body, etag } => (body, etag),
Response::NotFound => {
let history = CraftAppHistory { etag: None, complete: true, releases: Vec::new(), fetched_at: Some(Utc::now()) };
return FetchOutcome::Fetched { releases: CraftAppReleases::default(), history, etag: None };
}
Response::NotModified => return FetchOutcome::NotModified,
Response::RateLimited { retry_at } => return FetchOutcome::RateLimited { retry_at },
Response::Failed(why) => return FetchOutcome::Failed(why),
};
let (mut all, mut listed) = match parse_release_list(&body, repo) {
Ok(read) => read,
Err(why) => return FetchOutcome::Failed(why),
};
let mut page = 1;
while read_more(listed, page) {
page += 1;
let body = match send(client, &list_url(repo, page), None, token).await {
Response::Body { body, .. } => body,
// An empty page ends the list; a missing one leaves it unknown, so nothing is stored.
Response::NotFound => return FetchOutcome::Failed(format!("page {page} of the release list is missing")),
Response::NotModified => return FetchOutcome::Failed("unexpected 304 for a later page".into()),
Response::RateLimited { retry_at } => return FetchOutcome::RateLimited { retry_at },
Response::Failed(why) => return FetchOutcome::Failed(why),
};
match parse_release_list(&body, repo) {
Ok((more, n)) => {
all.extend(more);
listed = n;
}
Err(why) => return FetchOutcome::Failed(why),
}
}
match settle(all, listed) {
Ok((releases, history)) => {
let history = CraftAppHistory { etag: etag.clone(), fetched_at: Some(Utc::now()), ..history };
FetchOutcome::Fetched { releases, history, etag }
}
Err(why) => FetchOutcome::Failed(why),
}
}
/// Whether to read the page after `page`: the last one read held `listed` releases, so a full one
/// may have more behind it, up to [`MAX_PAGES`].
pub fn read_more(listed: usize, page: usize) -> bool {
listed >= RELEASES_PER_PAGE && page < MAX_PAGES
}
/// What the pages read say, newest first, the last of them holding `listed` releases: the
/// channels and the history (complete when the last page wasn't full). Fails when the history is
/// incomplete and has no stable release, which is then further back.
pub fn settle(mut all: Vec<CraftAppRelease>, listed: usize) -> Result<(CraftAppReleases, CraftAppHistory), String> {
// A release published between two page reads moves the last one of a page onto the next: keep
// each tag once, where it first appeared.
let mut seen = std::collections::HashSet::new();
all.retain(|release| seen.insert(release.tag.clone()));
let complete = listed < RELEASES_PER_PAGE;
let releases = sort_releases(&all);
if releases.latest_release.is_none() && !complete {
return Err(format!("no stable release among the newest {} releases", MAX_PAGES * RELEASES_PER_PAGE));
}
Ok((releases, CraftAppHistory { etag: None, complete, releases: all, fetched_at: None }))
}
/// Sends one GET to GitHub and sorts out the answer. A body larger than a page may be fails.
async fn send(client: &wreq::Client, url: &str, etag: Option<&str>, token: Option<&str>) -> Response {
let request = build_request(client, url, etag, token);
let mut response = match request.send().await {
Ok(r) => r,
Err(err) => return Response::Failed(format!("request failed: {err}")),
};
let status = response.status();
let header = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_string);
match status {
StatusCode::NOT_MODIFIED => Response::NotModified,
StatusCode::NOT_FOUND => Response::NotFound,
StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS => {
let remaining = header("x-ratelimit-remaining");
let reset = header("x-ratelimit-reset").and_then(|r| r.parse::<i64>().ok()).and_then(|s| DateTime::from_timestamp(s, 0));
let retry_after = header(RETRY_AFTER.as_str())
.and_then(|r| r.parse::<i64>().ok())
.map(|s| Utc::now() + chrono::Duration::seconds(s.clamp(0, 86_400)));
if status == StatusCode::TOO_MANY_REQUESTS || remaining.as_deref() == Some("0") || retry_after.is_some() {
Response::RateLimited { retry_at: retry_after.or(reset) }
} else {
Response::Failed(format!("HTTP {status}"))
}
}
StatusCode::OK => {
let etag = header(ETAG.as_str());
// Read in pieces and stopped at the cap: a compressed answer announces no decoded length.
let mut body = Vec::new();
loop {
match response.chunk().await {
Ok(Some(piece)) if body.len().saturating_add(piece.len()) <= MAX_LIST_BODY_BYTES => body.extend_from_slice(&piece),
Ok(Some(_)) => return Response::Failed(format!("answer larger than {MAX_LIST_BODY_BYTES} bytes")),
Ok(None) => return Response::Body { body, etag },
Err(err) => return Response::Failed(format!("unreadable answer: {err}")),
}
}
}
other => Response::Failed(format!("HTTP {other}")),
}
}
/// Page `page` (from 1) of `repo`'s releases. The first page's URL is the one its ETag is for.
fn list_url(repo: &str, page: usize) -> String {
if page <= 1 {
format!("{API_BASE}/repos/{repo}/releases?per_page={RELEASES_PER_PAGE}")
} else {
format!("{API_BASE}/repos/{repo}/releases?per_page={RELEASES_PER_PAGE}&page={page}")
}
}
/// The request for `url`. Sends `Authorization: Bearer` only for a non-blank token (an
/// authenticated `304` doesn't count against the rate limit); never an empty header.
fn build_request(client: &wreq::Client, url: &str, etag: Option<&str>, token: Option<&str>) -> wreq::RequestBuilder {
let mut request = client
.get(url)
.header(USER_AGENT, "storyteller-web (craft apps release poller)")
.header(ACCEPT, "application/vnd.github+json")
.header("X-GitHub-Api-Version", "2022-11-28");
if let Some(etag) = etag {
request = request.header(IF_NONE_MATCH, etag);
}
if let Some(token) = token.map(str::trim).filter(|t| !t.is_empty()) {
request = request.header(AUTHORIZATION, format!("Bearer {token}"));
}
request
}
/// The parts of GitHub's release object we use. Everything optional: GitHub's answer is input.
#[derive(Deserialize)]
struct GithubRelease {
#[serde(default)]
tag_name: Option<String>,
#[serde(default)]
name: Option<String>,
#[serde(default)]
html_url: Option<String>,
#[serde(default)]
published_at: Option<DateTime<Utc>>,
#[serde(default)]
prerelease: bool,
#[serde(default)]
draft: bool,
#[serde(default)]
body: Option<String>,
#[serde(default)]
assets: Vec<GithubAsset>,
}
#[derive(Deserialize)]
struct GithubAsset {
#[serde(default)]
name: Option<String>,
#[serde(default)]
size: u64,
#[serde(default)]
browser_download_url: Option<String>,
/// `sha256:<hex>` on assets uploaded since mid-2025.
#[serde(default)]
digest: Option<String>,
}
/// Reads a page of releases (newest first), and says how many the page listed. A release that
/// can't be read (a draft, no tag, the wrong shape) is skipped; only an answer that isn't a list
/// fails.
pub fn parse_release_list(body: &[u8], repo: &str) -> Result<(Vec<CraftAppRelease>, usize), String> {
let raw: Vec<serde_json::Value> = serde_json::from_slice(body).map_err(|e| format!("unreadable release list: {e}"))?;
let listed = raw.len();
let releases = raw
.into_iter()
.take(RELEASES_PER_PAGE)
.filter_map(|value| serde_json::from_value::<GithubRelease>(value).ok().and_then(|r| read_release(r, repo).ok()))
.collect();
Ok((releases, listed))
}
/// Sorts an app's releases (newest first, as GitHub lists them) into what `release_info` serves:
/// the stable release and beta with the highest version (as ArtCraft Launcher ranks them, so a
/// backport published after a newer release doesn't become the latest), the most recently
/// published nightly, and the first [`MAX_VERSION_LIST`] ordinary releases.
pub fn sort_releases(all: &[CraftAppRelease]) -> CraftAppReleases {
let mut releases = CraftAppReleases::default();
for release in all {
if is_nightly_tag(&release.tag) {
releases.latest_nightly.get_or_insert_with(|| release.clone());
continue;
}
if releases.releases.len() < MAX_VERSION_LIST {
releases.releases.push(release.into());
}
let slot = if release.prerelease { &mut releases.latest_prerelease } else { &mut releases.latest_release };
if slot.as_ref().is_none_or(|kept| is_higher(release, kept)) {
*slot = Some(release.clone());
}
}
releases
}
/// Whether `a`'s version is higher than `b`'s, by semver precedence (build metadata doesn't count).
/// A tag that isn't a version never outranks one that is, and between two that rank the same the
/// one listed first stays.
fn is_higher(a: &CraftAppRelease, b: &CraftAppRelease) -> bool {
match (version_of(&a.tag), version_of(&b.tag)) {
(Some(a), Some(b)) => a.cmp_precedence(&b).is_gt(),
(Some(_), None) => true,
_ => false,
}
}
fn version_of(tag: &str) -> Option<semver::Version> {
semver::Version::parse(tag.strip_prefix(['v', 'V']).unwrap_or(tag)).ok()
}
/// Whether the tag's pre-release part has a `nightly` identifier, as ArtCraft Launcher reads it
/// (`v0.50.0-nightly.20261126.166.1`, `v1.0.0-dev.nightly.1`). Not `v1.0.0-nightlyish`, and not
/// build metadata (`v1.0.0+nightly`).
pub fn is_nightly_tag(tag: &str) -> bool {
let version = tag.strip_prefix(['v', 'V']).unwrap_or(tag);
let version = version.split_once('+').map_or(version, |(v, _)| v);
version.split_once('-').is_some_and(|(_, pre)| pre.split('.').any(|part| part.eq_ignore_ascii_case("nightly")))
}
/// Reads a release, keeping only downloads that really belong to `repo`.
#[cfg(test)]
fn parse_release(body: &[u8], repo: &str) -> Result<CraftAppRelease, String> {
let raw: GithubRelease = serde_json::from_slice(body).map_err(|e| format!("unreadable release: {e}"))?;
read_release(raw, repo)
}
/// A release GitHub described, keeping only downloads that really belong to `repo`.
fn read_release(raw: GithubRelease, repo: &str) -> Result<CraftAppRelease, String> {
if raw.draft {
return Err("the release is a draft".into());
}
let tag = raw.tag_name.filter(|t| !t.is_empty() && t.len() <= 64).ok_or("the release has no tag")?;
let releases_page = format!("https://github.com/{repo}/releases/");
let html_url = raw.html_url.filter(|u| u.starts_with(&releases_page)).unwrap_or_else(|| format!("{releases_page}tag/{tag}"));
let download_prefix = format!("https://github.com/{repo}/releases/download/");
let assets = raw
.assets
.into_iter()
.filter_map(|a| {
let name = a.name.filter(|n| valid_file_name(n))?;
let download_url = a.browser_download_url.filter(|u| u.starts_with(&download_prefix))?;
let sha256 = a.digest.as_deref().and_then(|d| d.strip_prefix("sha256:")).filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())).map(str::to_ascii_lowercase);
let platform = parse_platform(&name);
Some(CraftAppReleaseAsset { name, size_bytes: a.size, download_url, sha256, platform })
})
.take(MAX_ASSETS)
.collect();
// A pre-release tag (`v0.7.0-rc.1`) is a pre-release even when GitHub's flag wasn't set.
let prerelease = raw.prerelease || version_of(&tag).is_some_and(|v| !v.pre.is_empty());
Ok(CraftAppRelease {
version: tag.strip_prefix(['v', 'V']).unwrap_or(&tag).to_string(),
name: raw.name.filter(|n| !n.is_empty()).map(|n| truncate(&n, 200)).unwrap_or_else(|| tag.clone()),
tag,
published_at: raw.published_at,
html_url,
prerelease,
notes_markdown: raw.body.map(|b| truncate(&b, MAX_NOTES_BYTES)).unwrap_or_default(),
assets,
})
}
/// Reads `<app>-<version>-<os>-<arch>[-portable].<ext>`, `<app>-cli-<version>-macos-universal.zip`
/// and `<app>-web-<version>.zip`. `None` for anything else (checksums, unknown files).
pub fn parse_platform(name: &str) -> Option<CraftAppAssetPlatform> {
if name.contains("-web-") && name.ends_with(".zip") {
return Some(CraftAppAssetPlatform { os: CraftAppOs::Web, arch: None, package_type: CraftAppPackageType::WebZip });
}
const KINDS: [(&str, CraftAppPackageType); 10] = [
("-portable.zip", CraftAppPackageType::PortableZip),
(".AppImage.zsync", CraftAppPackageType::AppImageZsync),
(".AppImage", CraftAppPackageType::AppImage),
(".tar.gz", CraftAppPackageType::TarGz),
(".msi", CraftAppPackageType::Msi),
(".dmg", CraftAppPackageType::Dmg),
(".deb", CraftAppPackageType::Deb),
(".rpm", CraftAppPackageType::Rpm),
(".flatpak", CraftAppPackageType::Flatpak),
(".zip", CraftAppPackageType::CliZip),
];
let (base, package_type) = KINDS.iter().find_map(|(suffix, kind)| name.strip_suffix(suffix).map(|b| (b, *kind)))?;
let mut parts = base.rsplitn(3, '-');
let (arch, os) = (parts.next()?, parts.next()?);
let os = match os {
"windows" => CraftAppOs::Windows,
"macos" => CraftAppOs::Macos,
"linux" => CraftAppOs::Linux,
"freebsd" => CraftAppOs::Freebsd,
_ => return None,
};
let arch = match arch {
"x64" | "x86_64" => CraftAppArch::X64,
"x86" => CraftAppArch::X86,
"arm64" | "aarch64" => CraftAppArch::Arm64,
"universal" => CraftAppArch::Universal,
_ => return None,
};
// A bare `.zip` is only the macOS command-line tools.
if package_type == CraftAppPackageType::CliZip && !(os == CraftAppOs::Macos && base.contains("-cli-")) {
return None;
}
Some(CraftAppAssetPlatform { os, arch: Some(arch), package_type })
}
fn valid_file_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 200
&& !name.starts_with('.')
&& !name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))
}
fn truncate(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &s[..end])
}
#[cfg(test)]
mod tests {
use super::*;
const REPO: &str = "storytold/photocraft";
const HASH: &str = "8a5edab282632443219e051e4ade2d1d5bbc671c781051bf1437897cbdfea0f1";
fn release_json(download_url: &str) -> String {
format!(
r#"{{"tag_name":"v0.5.0","name":"PhotoCraft v0.5.0","draft":false,"prerelease":false,
"html_url":"https://github.com/storytold/photocraft/releases/tag/v0.5.0",
"published_at":"2026-10-08T14:52:50Z","body":"Notes","unknown_field":[1,2,3],
"assets":[{{"name":"photocraft-0.5.0-windows-x64.msi","size":7,"browser_download_url":"{download_url}","digest":"sha256:{HASH}"}}]}}"#
)
}
#[test]
fn sends_the_token_as_a_bearer_header() {
let client = build_client().unwrap();
let request = build_request(&client, &list_url(REPO, 1), Some("\"etag\""), Some("ghp_x")).build().unwrap();
assert_eq!(request.headers().get(AUTHORIZATION).unwrap(), "Bearer ghp_x");
assert_eq!(request.headers().get(IF_NONE_MATCH).unwrap(), "\"etag\"");
}
#[test]
fn without_a_token_the_request_is_unauthenticated() {
let client = build_client().unwrap();
for token in [None, Some(""), Some(" ")] {
let request = build_request(&client, &list_url(REPO, 1), None, token).build().unwrap();
assert!(request.headers().get(AUTHORIZATION).is_none(), "{:?}", token);
assert!(request.headers().get(IF_NONE_MATCH).is_none());
}
}
#[test]
fn asks_for_a_page_of_releases_and_later_pages_by_number() {
assert_eq!(list_url(REPO, 1), "https://api.github.com/repos/storytold/photocraft/releases?per_page=100");
assert_eq!(list_url(REPO, 2), "https://api.github.com/repos/storytold/photocraft/releases?per_page=100&page=2");
}
mod release_lists {
use super::*;
#[test]
fn sorts_a_page_into_stable_beta_nightly_and_the_version_list() {
let page = list(&[
entry("v0.6.0-nightly.20261126.2.1", true),
entry("v0.6.0-rc.2", true),
entry("v0.6.0-nightly.20261125.1.1", true),
entry("v0.5.1", false),
entry("v0.6.0-rc.1", true),
entry("v0.5.0", false),
]);
let (all, listed) = parse_release_list(page.as_bytes(), REPO).unwrap();
assert_eq!(listed, 6);
assert_eq!(all.len(), 6, "the history keeps every release, nightlies too");
let releases = sort_releases(&all);
assert_eq!(tag(&releases.latest_release), Some("v0.5.1"));
assert_eq!(tag(&releases.latest_prerelease), Some("v0.6.0-rc.2"));
assert_eq!(tag(&releases.latest_nightly), Some("v0.6.0-nightly.20261126.2.1"));
let versions: Vec<&str> = releases.releases.iter().map(|r| r.tag.as_str()).collect();
assert_eq!(versions, ["v0.6.0-rc.2", "v0.5.1", "v0.6.0-rc.1", "v0.5.0"], "newest first, no nightlies");
assert!(releases.releases[0].prerelease && !releases.releases[1].prerelease);
assert_eq!(releases.latest_release.as_ref().unwrap().assets.len(), 1, "the latest ones keep their files");
}
#[test]
fn a_release_candidate_without_the_prerelease_flag_is_a_beta_never_the_stable_release() {
let page = list(&[entry("v0.7.0-rc.1", false), entry("v0.6.0", false)]);
let (all, _) = parse_release_list(page.as_bytes(), REPO).unwrap();
assert!(all[0].prerelease, "the history says so too");
let releases = sort_releases(&all);
assert_eq!(tag(&releases.latest_release), Some("v0.6.0"));
assert_eq!(tag(&releases.latest_prerelease), Some("v0.7.0-rc.1"));
}
#[test]
fn build_metadata_does_not_rank_a_release() {
let page = list(&[entry("v0.6.0+a", false), entry("v0.6.0+z", false), entry("v0.5.0", false)]);
let releases = sort_releases(&parse_release_list(page.as_bytes(), REPO).unwrap().0);
assert_eq!(tag(&releases.latest_release), Some("v0.6.0+a"), "the same version: the one listed first stays");
}
#[test]
fn a_nightly_without_the_prerelease_flag_is_still_a_nightly_never_the_stable_release() {
let page = list(&[entry("v0.6.0-nightly.20261126.2.1", false), entry("v0.5.0", false)]);
let releases = sort_releases(&parse_release_list(page.as_bytes(), REPO).unwrap().0);
assert_eq!(tag(&releases.latest_release), Some("v0.5.0"));
assert_eq!(tag(&releases.latest_nightly), Some("v0.6.0-nightly.20261126.2.1"));
assert_eq!(releases.releases.len(), 1);
}
#[test]
fn drafts_and_unreadable_entries_are_skipped_not_fatal() {
let page = format!(
"[{}, {}, {}, {}]",
r#"{"tag_name":"v0.7.0","draft":true,"prerelease":false}"#,
r#"{"tag_name":7}"#,
r#""not a release""#,
entry("v0.5.0", false),
);
let (all, listed) = parse_release_list(page.as_bytes(), REPO).unwrap();
assert_eq!(listed, 4, "a skipped entry still counts toward a full page");
assert_eq!(all.len(), 1);
assert_eq!(tag(&sort_releases(&all).latest_release), Some("v0.5.0"));
}
#[test]
fn an_answer_that_is_not_a_list_fails() {
assert!(parse_release_list(b"<html>", REPO).is_err());
assert!(parse_release_list(entry("v0.5.0", false).as_bytes(), REPO).is_err());
}
#[test]
fn an_empty_page_is_a_complete_history_without_releases() {
let (all, listed) = parse_release_list(b"[]", REPO).unwrap();
assert!(!read_more(listed, 1));
let (releases, history) = settle(all, listed).unwrap();
assert!(releases.latest_release.is_none() && releases.releases.is_empty());
assert!(history.complete && history.releases.is_empty());
}
#[test]
fn later_pages_are_read_while_each_is_full_up_to_the_cap() {
assert!(read_more(RELEASES_PER_PAGE, 1));
assert!(!read_more(RELEASES_PER_PAGE - 1, 1), "a page that isn't full is the last one");
assert!(read_more(RELEASES_PER_PAGE, MAX_PAGES - 1));
assert!(!read_more(RELEASES_PER_PAGE, MAX_PAGES), "the cap");
}
/// Nightlies without the pre-release flag (one of which GitHub may call the latest release)
/// don't count as stable: with the history cut off and no stable release in it, the fetch
/// fails instead of storing "no release"; with the whole history read, there truly is none.
#[test]
fn no_stable_release_fails_only_when_the_history_is_cut_off() {
let nightlies: Vec<String> = (0..RELEASES_PER_PAGE).map(|i| entry(&format!("v0.6.0-nightly.202611{:02}.{i}.1", i % 28 + 1), false)).collect();
let (all, listed) = parse_release_list(list(&nightlies).as_bytes(), REPO).unwrap();
assert!(settle(all.clone(), listed).is_err());
let (releases, history) = settle(all, 3).unwrap();
assert!(releases.latest_release.is_none() && history.complete);
}
/// A backport published after a newer release doesn't replace it as the latest, and the same
/// holds for betas; the version list keeps GitHub's order.
#[test]
fn the_latest_stable_release_and_beta_are_the_highest_versions() {
let page = list(&[entry("v0.4.3", false), entry("v0.6.0-rc.1", true), entry("v0.5.0", false), entry("v0.6.0-rc.2", true), entry("latest", false)]);
let releases = sort_releases(&parse_release_list(page.as_bytes(), REPO).unwrap().0);
assert_eq!(tag(&releases.latest_release), Some("v0.5.0"));
assert_eq!(tag(&releases.latest_prerelease), Some("v0.6.0-rc.2"));
assert_eq!(releases.releases[0].tag, "v0.4.3");
}
#[test]
fn a_release_seen_on_two_pages_is_kept_once() {
let (mut all, _) = parse_release_list(list(&[entry("v0.6.0", false), entry("v0.5.0", false)]).as_bytes(), REPO).unwrap();
let (next, listed) = parse_release_list(list(&[entry("v0.5.0", false), entry("v0.4.0", false)]).as_bytes(), REPO).unwrap();
all.extend(next);
let (releases, history) = settle(all, listed).unwrap();
let tags: Vec<&str> = history.releases.iter().map(|r| r.tag.as_str()).collect();
assert_eq!(tags, ["v0.6.0", "v0.5.0", "v0.4.0"]);
assert_eq!(releases.releases.len(), 3);
}
#[test]
fn the_version_list_is_capped_but_the_history_is_not() {
let many: Vec<String> = (0..MAX_VERSION_LIST + 5).map(|i| entry(&format!("v0.{i}.0"), false)).collect();
let (all, listed) = parse_release_list(list(&many).as_bytes(), REPO).unwrap();
let (releases, history) = settle(all, listed).unwrap();
assert_eq!(releases.releases.len(), MAX_VERSION_LIST);
assert_eq!(history.releases.len(), MAX_VERSION_LIST + 5);
}
#[test]
fn reads_at_most_one_page_however_long_the_answer() {
let many: Vec<String> = (0..RELEASES_PER_PAGE + 5).map(|i| entry(&format!("v0.{i}.0"), false)).collect();
let (all, listed) = parse_release_list(list(&many).as_bytes(), REPO).unwrap();
assert_eq!(listed, RELEASES_PER_PAGE + 5);
assert_eq!(all.len(), RELEASES_PER_PAGE);
}
fn entry(tag: &str, prerelease: bool) -> String {
format!(
r#"{{"tag_name":"{tag}","name":"PhotoCraft {tag}","draft":false,"prerelease":{prerelease},
"html_url":"https://github.com/storytold/photocraft/releases/tag/{tag}","body":"Notes",
"assets":[{{"name":"photocraft-x-windows-x64.msi","size":7,"browser_download_url":"https://github.com/storytold/photocraft/releases/download/{tag}/photocraft-x-windows-x64.msi"}}]}}"#
)
}
fn list(entries: &[String]) -> String {
format!("[{}]", entries.join(","))
}
fn tag(release: &Option<CraftAppRelease>) -> Option<&str> {
release.as_ref().map(|r| r.tag.as_str())
}
}
#[test]
fn reads_nightly_tags_as_the_launcher_does() {
for tag in ["v0.50.0-nightly.20261126.166.1", "v1.0.0-dev.nightly.1", "1.0.0-NIGHTLY.3", "v1.0.0-nightly+build.5"] {
assert!(is_nightly_tag(tag), "{}", tag);
}
for tag in ["v0.5.0", "v0.6.0-rc.1", "v1.0.0-nightlyish.1", "v1.0.0+nightly", "nightly", "artcraft-v0.41.1"] {
assert!(!is_nightly_tag(tag), "{}", tag);
}
}
#[test]
fn reads_a_release() {
let r = parse_release(release_json("https://github.com/storytold/photocraft/releases/download/v0.5.0/photocraft-0.5.0-windows-x64.msi").as_bytes(), REPO).unwrap();
assert_eq!((r.tag.as_str(), r.version.as_str(), r.name.as_str()), ("v0.5.0", "0.5.0", "PhotoCraft v0.5.0"));
assert_eq!(r.assets.len(), 1);
assert_eq!(r.assets[0].sha256.as_deref(), Some(HASH));
let p = r.assets[0].platform.as_ref().unwrap();
assert_eq!((p.os, p.arch, p.package_type), (CraftAppOs::Windows, Some(CraftAppArch::X64), CraftAppPackageType::Msi));
}
#[test]
fn drops_downloads_that_point_elsewhere_and_rejects_garbage() {
for url in ["https://evil.example/x.msi", "https://github.com/storytold/other/releases/download/v1/x.msi"] {
assert!(parse_release(release_json(url).as_bytes(), REPO).unwrap().assets.is_empty(), "{url}");
}
assert!(parse_release(b"<html>", REPO).is_err());
assert!(parse_release(br#"{"assets":[]}"#, REPO).is_err());
assert!(parse_release(br#"{"tag_name":"v1.0.0","draft":true}"#, REPO).is_err());
}
#[test]
fn reads_every_asset_name_the_suite_publishes() {
let cases = [
("photocraft-0.5.0-macos-universal.dmg", Some((CraftAppOs::Macos, Some(CraftAppArch::Universal), CraftAppPackageType::Dmg))),
("photocraft-cli-0.5.0-macos-universal.zip", Some((CraftAppOs::Macos, Some(CraftAppArch::Universal), CraftAppPackageType::CliZip))),
("photocraft-0.5.0-windows-arm64-portable.zip", Some((CraftAppOs::Windows, Some(CraftAppArch::Arm64), CraftAppPackageType::PortableZip))),
("photocraft-0.5.0-windows-x86.msi", Some((CraftAppOs::Windows, Some(CraftAppArch::X86), CraftAppPackageType::Msi))),
("photocraft-0.5.0-linux-aarch64.AppImage", Some((CraftAppOs::Linux, Some(CraftAppArch::Arm64), CraftAppPackageType::AppImage))),
("photocraft-0.5.0-linux-x86_64.AppImage.zsync", Some((CraftAppOs::Linux, Some(CraftAppArch::X64), CraftAppPackageType::AppImageZsync))),
("photocraft-0.5.0-linux-x86_64.deb", Some((CraftAppOs::Linux, Some(CraftAppArch::X64), CraftAppPackageType::Deb))),
("photocraft-0.5.0-linux-x86_64.rpm", Some((CraftAppOs::Linux, Some(CraftAppArch::X64), CraftAppPackageType::Rpm))),
("photocraft-0.5.0-linux-x86_64.flatpak", Some((CraftAppOs::Linux, Some(CraftAppArch::X64), CraftAppPackageType::Flatpak))),
("photocraft-0.5.0-freebsd-x86_64.tar.gz", Some((CraftAppOs::Freebsd, Some(CraftAppArch::X64), CraftAppPackageType::TarGz))),
("photocraft-0.2.0-rc.1-linux-x86_64.tar.gz", Some((CraftAppOs::Linux, Some(CraftAppArch::X64), CraftAppPackageType::TarGz))),
("photocraft-web-0.5.0.zip", Some((CraftAppOs::Web, None, CraftAppPackageType::WebZip))),
("SHA256SUMS.txt", None),
("photocraft-0.5.0-plan9-x64.msi", None),
];
for (name, want) in cases {
let got = parse_platform(name).map(|p| (p.os, p.arch, p.package_type));
assert_eq!(got, want, "{name}");
}
}
}
@@ -1,7 +0,0 @@
pub mod config;
pub mod fallback;
pub mod github;
pub mod poll_craft_app_releases;
pub mod scheduling;
pub mod shared_entry;
pub mod shared_store;
@@ -1,537 +0,0 @@
//! Keeps [`CraftAppsReleaseCache`] holding the releases of every Craft App (the latest stable
//! release, beta and nightly, and the recent versions), which `GET /v1/craft_apps/release_info`
//! serves to ArtCraft Launcher (so thousands of launchers don't each poll GitHub).
//!
//! Every instance runs this loop, waking every [`TICK`] (30 s, with jitter). At startup it first
//! takes the fleet's shared releases from Redis, so a new instance serves them at once without
//! asking GitHub. With coordination (the default) the fleet shares its work through Redis
//! (`shared_entry` documents the keys):
//!
//! 1. Read every app's shared entry and the fleet's backoff; take anything newer into memory.
//! The endpoint always serves memory, so it keeps answering whatever Redis does.
//! 2. If the fleet is backing off (GitHub rate limited us, or a whole round failed), stop.
//! 3. For each app that is due (its shared fetch is `interval - CLOCK_SKEW_MARGIN` old, and any
//! failure retry has waited), read its entry again (another instance may just have fetched
//! it), claim it so instances ticking at the same moment don't all ask, then ask GitHub with
//! the shared ETag and share the answer. Shared writes never go back in time.
//! 4. After a round with requests, update the fleet's backoff (a good round clears it).
//!
//! Each app is all-or-nothing: either its releases are stored with a fresh `app_last_fetched`,
//! or nothing about it changes.
//!
//! If Redis is unreachable (or coordination is off) the instance does the same from its own
//! memory, as every instance did before coordination, and returns to coordinating when Redis
//! answers again. Nothing here panics; trouble is logged and retried.
use std::time::{Duration, Instant};
use chrono::Utc;
use log::{error, info, warn};
use crate::state::craft_apps_release_cache::CraftAppsReleaseCache;
use crate::threads::poll_craft_app_releases_thread::config::CraftAppsPollConfig;
use crate::threads::poll_craft_app_releases_thread::fallback::{PollMode, RedisTroubleLog};
use crate::threads::poll_craft_app_releases_thread::github;
use crate::threads::poll_craft_app_releases_thread::github::FetchOutcome;
use crate::threads::poll_craft_app_releases_thread::scheduling::{backoff_after, is_due, jittered, Backoff, RoundResult, TICK};
use crate::threads::poll_craft_app_releases_thread::shared_entry::{SharedAppEntry, SharedFailure};
use crate::threads::poll_craft_app_releases_thread::shared_store::{PollerRedisPool, SharedStore};
/// Spreads a fleet's first tick over this window, so a deploy doesn't hit GitHub all at once.
const STARTUP_JITTER: Duration = Duration::from_secs(15);
/// Pause between the requests of one round.
const BETWEEN_REQUESTS: Duration = Duration::from_millis(1_000);
pub async fn poll_craft_app_releases(cache: CraftAppsReleaseCache, config: CraftAppsPollConfig, redis_pool: PollerRedisPool, hostname: String) {
cache.register_apps(&config.apps);
if !config.enabled {
info!("Craft app release polling is disabled (CRAFT_APPS_RELEASE_POLLING_ENABLED=false).");
return;
}
let client = match github::build_client() {
Ok(client) => client,
Err(err) => {
error!("Craft app release polling can't start: no HTTP client: {:?}", err);
return;
}
};
info!(
"Polling GitHub for {} craft app releases, each at most every {:?} (GitHub token: {}; coordinated through Redis: {}).",
config.apps.len(), config.interval, config.github_token.is_some(), config.coordination_enabled,
);
let store = config.coordination_enabled.then(|| SharedStore::new(redis_pool, hostname));
let mut poller = Poller::new(client, cache, config, store);
// Warm memory from the fleet's shared copy right away: it costs no GitHub quota, and the
// jitter below only needs to spread out requests to GitHub.
if poller.refresh_from_shared().await {
info!("Craft app releases: took the fleet's shared releases from Redis at startup.");
}
tokio::time::sleep(jittered(STARTUP_JITTER, 1.0)).await;
loop {
poller.tick().await;
tokio::time::sleep(jittered(TICK, 0.1)).await;
}
}
/// The polling loop's state.
struct Poller {
client: wreq::Client,
cache: CraftAppsReleaseCache,
config: CraftAppsPollConfig,
/// `None` when coordination is off.
store: Option<SharedStore>,
/// The backoff this instance knows: the fleet's while Redis answers, its own otherwise.
backoff: Backoff,
redis_log: RedisTroubleLog,
}
/// What one tick did.
#[derive(Debug)]
struct TickReport {
mode: PollMode,
round: RoundResult,
}
/// Whether to ask GitHub for an app, after looking at its shared entry once more.
enum SharedCheck {
Ask,
/// Fresh after all, or another instance is asking right now.
Skip,
/// The fleet started backing off.
StopRound,
}
impl Poller {
fn new(client: wreq::Client, cache: CraftAppsReleaseCache, config: CraftAppsPollConfig, store: Option<SharedStore>) -> Self {
Self { client, cache, config, store, backoff: Backoff::default(), redis_log: RedisTroubleLog::default() }
}
async fn tick(&mut self) -> TickReport {
let shared_state_readable = self.refresh_from_shared().await;
let mode = PollMode::choose(self.store.is_some(), shared_state_readable);
let mut report = TickReport { mode, round: RoundResult::default() };
let now = Utc::now();
if self.backoff.is_active(now) {
return report;
}
let due: Vec<(String, String)> = self
.config
.apps
.iter()
.filter(|(key, _, _)| self.cache.app(key).is_some_and(|app| is_due(&app, now, self.config.interval)))
.map(|(key, _, repo)| (key.clone(), repo.clone()))
.collect();
if due.is_empty() {
return report;
}
let (round, mode) = self.poll_round(&due, mode).await;
report.round = round;
report.mode = mode;
if report.round.requests() == 0 {
return report;
}
self.update_backoff(&report.round, mode).await;
info!(
"Craft app releases ({:?}): {} fetched, {} unchanged, {} failed{}{}.",
mode, report.round.fetched, report.round.unchanged, report.round.failed,
if report.round.rate_limited.is_some() { ", rate limited" } else { "" },
self.backoff.until.map(|until| format!("; backing off until {until}")).unwrap_or_default(),
);
report
}
/// Takes the fleet's shared state into memory. False when coordination is off or Redis
/// couldn't be read (this tick then works alone).
async fn refresh_from_shared(&mut self) -> bool {
let Some(store) = self.store.clone() else {
return false;
};
let keys: Vec<String> = self.config.apps.iter().map(|(key, _, _)| key.clone()).collect();
match store.read(&keys).await {
Ok((entries, backoff)) => {
self.redis_log.succeeded(Instant::now());
for (key, entry) in keys.iter().zip(entries) {
if let Some(entry) = entry {
merge_shared_entry(&self.cache, key, entry);
}
}
self.backoff = backoff;
self.sync_histories(&store, &keys).await;
true
}
Err(err) => {
self.redis_log.failed(&err, Instant::now());
false
}
}
}
/// Reads the shared history of every app whose history is behind its releases (another
/// instance fetched it). Only those: a history is large, and changes only with a new release.
async fn sync_histories(&mut self, store: &SharedStore, keys: &[String]) {
for key in keys {
if !self.cache.app(key).is_some_and(|app| app.history_is_behind()) {
continue;
}
match store.read_history(key).await {
Ok(Some(history)) => {
if !self.cache.merge_history(key, history) {
// Redis holds another fetch's history (its write lost a race, or it is older).
self.cache.mark_history_missing(key);
}
}
Ok(None) => self.cache.mark_history_missing(key),
Err(err) => {
self.redis_log.failed(&err, Instant::now());
return;
}
}
}
}
/// Asks GitHub about each due app. Returns what happened and the mode it ended in (a Redis
/// error mid-round finishes the round alone).
async fn poll_round(&mut self, due: &[(String, String)], mut mode: PollMode) -> (RoundResult, PollMode) {
let mut round = RoundResult::default();
for (key, repo) in due {
if let Some(store) = self.coordinated_store(mode) {
match self.check_shared(&store, key).await {
Ok(SharedCheck::Ask) => {}
Ok(SharedCheck::Skip) => continue,
Ok(SharedCheck::StopRound) => break,
Err(err) => {
self.redis_log.failed(&err, Instant::now());
mode = PollMode::Standalone;
}
}
}
if round.requests() > 0 {
tokio::time::sleep(BETWEEN_REQUESTS).await;
}
// Revalidated with the ETag, unless the list must be read in full: the shared history is
// missing, or it hasn't been read whole for `FULL_REFRESH` (a `304` on the first page hides
// edits to older releases).
let etag = self.cache.app(key).filter(|app| !needs_full_read(app, Utc::now())).and_then(|app| app.etag);
let outcome = github::fetch_releases(&self.client, repo, etag.as_deref(), self.config.github_token.as_deref()).await;
let now = Utc::now();
match outcome {
FetchOutcome::Fetched { releases, history, etag } => {
round.fetched += 1;
if let Some(store) = self.coordinated_store(mode) {
let shared = store.write_fetched(key, &releases, &history, etag.as_deref(), now).await;
mode = self.after_shared_write(shared, mode);
}
self.cache.store(key, releases, history, etag, now);
}
FetchOutcome::NotModified => {
round.unchanged += 1;
self.cache.confirm_unchanged(key, now);
if let (Some(store), Some(etag)) = (self.coordinated_store(mode), etag.as_deref()) {
let shared = store.write_unchanged(key, etag, now).await;
mode = self.after_shared_write(shared, mode);
}
}
FetchOutcome::RateLimited { retry_at } => {
warn!("GitHub rate limit reached polling {repo}; retry after {:?}.", retry_at);
round.rate_limited = Some(retry_at);
// The rest of the round would be refused too.
break;
}
FetchOutcome::Failed(why) => {
warn!("Couldn't fetch the releases of {repo}: {why}");
round.failed += 1;
let consecutive_failures = self.cache.record_failure(key, now);
if let Some(store) = self.coordinated_store(mode) {
let failure = SharedFailure { failed_at: now, consecutive_failures };
let shared = store.write_failure(key, failure).await;
mode = self.after_shared_write(shared, mode);
}
}
}
}
(round, mode)
}
/// Right before asking GitHub about `key`: takes its latest shared entry, and claims it if it
/// is still due and the fleet isn't backing off.
async fn check_shared(&mut self, store: &SharedStore, key: &str) -> anyhow::Result<SharedCheck> {
let (mut entries, backoff) = store.read(&[key.to_string()]).await?;
if let Some(entry) = entries.pop().flatten() {
merge_shared_entry(&self.cache, key, entry);
}
self.backoff = backoff;
let now = Utc::now();
if backoff.is_active(now) {
return Ok(SharedCheck::StopRound);
}
if !self.cache.app(key).is_some_and(|app| is_due(&app, now, self.config.interval)) {
return Ok(SharedCheck::Skip);
}
Ok(if store.claim(key, now).await? { SharedCheck::Ask } else { SharedCheck::Skip })
}
/// Sets the backoff after a round with requests, and shares it if it changed.
async fn update_backoff(&mut self, round: &RoundResult, mode: PollMode) {
let previous = self.backoff;
self.backoff = backoff_after(&self.config, round, previous, Utc::now());
if self.backoff == previous {
return;
}
if let Some(store) = self.coordinated_store(mode) {
if let Err(err) = store.write_backoff(self.backoff).await {
self.redis_log.failed(&err, Instant::now());
}
}
}
/// Logs a failed shared write; the rest of the round then works alone.
fn after_shared_write(&mut self, result: anyhow::Result<bool>, mode: PollMode) -> PollMode {
match result {
Ok(_) => mode,
Err(err) => {
self.redis_log.failed(&err, Instant::now());
PollMode::Standalone
}
}
}
/// The shared store, in [`PollMode::Coordinated`].
fn coordinated_store(&self, mode: PollMode) -> Option<SharedStore> {
self.store.clone().filter(|_| mode == PollMode::Coordinated)
}
}
/// How long a history may go without the whole list being read from GitHub.
const FULL_REFRESH: chrono::Duration = chrono::Duration::hours(6);
/// Whether `app`'s next fetch must read the whole list (no ETag).
fn needs_full_read(app: &crate::state::craft_apps_release_cache::CachedCraftApp, now: chrono::DateTime<Utc>) -> bool {
app.history_missing || app.history.fetched_at.is_none_or(|at| now - at >= FULL_REFRESH)
}
/// Takes a shared entry into memory (only what is newer than what this instance has).
fn merge_shared_entry(cache: &CraftAppsReleaseCache, key: &str, entry: SharedAppEntry) {
if let Some(fetched) = entry.fetched {
cache.merge_fetched(key, fetched.releases, fetched.etag, fetched.fetched_at, fetched.history_at);
}
if let Some(failure) = entry.failure {
cache.merge_failure(key, failure.failed_at, failure.consecutive_failures);
}
}
#[cfg(test)]
mod tests {
use chrono::DateTime;
use redis_schema::keys::craft_apps::craft_app_release_history_redis_key::CraftAppReleaseHistoryRedisKey;
use redis_schema::keys::craft_apps::craft_app_release_redis_key::CraftAppReleaseRedisKey;
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases};
use crate::threads::poll_craft_app_releases_thread::config::default_apps;
use crate::threads::poll_craft_app_releases_thread::shared_entry::{decode_app_entry, encode_fetch};
use crate::threads::poll_craft_app_releases_thread::shared_store::build_poller_redis_pool;
use super::*;
/// Live: real rounds against GitHub (two apps), then the endpoint's response, written to
/// `CRAFT_APPS_SAMPLE_OUT` when set (ArtCraft Launcher's parser reads it back). Uses
/// `CRAFT_APPS_RELEASE_GITHUB_TOKEN` if set, and works without it.
/// `cargo test -p storyteller-web --bin storyteller-web live_round -- --ignored`
#[tokio::test]
#[ignore = "needs network access"]
async fn live_round_fetches_real_releases() {
use artcraft_api_defs::craft_apps::release_info::{CraftAppsImportantNotices, GetCraftAppsReleaseInfoResponse};
let mut config = config();
config.github_token = std::env::var("CRAFT_APPS_RELEASE_GITHUB_TOKEN").ok().filter(|t| !t.trim().is_empty());
// SolidCraft publishes nightlies daily and has more than one page of releases.
config.apps.retain(|(key, _, _)| key == "photocraft" || key == "artcraft-launcher" || key == "solidcraft");
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&config.apps);
let mut poller = Poller::new(github::build_client().unwrap(), cache.clone(), config.clone(), None);
let due: Vec<(String, String)> = config.apps.iter().map(|(k, _, r)| (k.clone(), r.clone())).collect();
let (round, _) = poller.poll_round(&due, PollMode::Standalone).await;
assert_eq!(round.fetched + round.unchanged, 3, "{round:?}");
// A second round revalidates with ETags.
let (again, _) = poller.poll_round(&due, PollMode::Standalone).await;
assert_eq!(again.fetched + again.unchanged, 3, "{again:?}");
let info = cache.snapshot();
assert!(info.last_fetched.is_some());
let photocraft = &info.apps["photocraft"];
let latest = photocraft.latest_release.as_ref().unwrap();
assert!(latest.assets.iter().any(|a| a.platform.is_some() && a.sha256.is_some()));
assert!(!latest.prerelease);
let solidcraft = cache.app("solidcraft").unwrap();
assert!(solidcraft.history.complete, "every page was read");
assert!(solidcraft.history.releases.len() > github::RELEASES_PER_PAGE, "more than one page");
assert!(solidcraft.releases.latest_nightly.is_some());
assert!(solidcraft.history.releases.iter().any(|r| r.tag == latest_tag(&solidcraft)), "the history has the stable release");
// The version list comes from the first page only and may be empty (all nightlies) while
// the stable release comes from a later one; its sorting is tested in `github`.
let response = GetCraftAppsReleaseInfoResponse {
success: true,
release_info: info,
app_renames: Vec::new(),
repo_renames: Vec::new(),
important_notices: CraftAppsImportantNotices::default(),
};
let json = serde_json::to_string_pretty(&response).unwrap();
if let Ok(path) = std::env::var("CRAFT_APPS_SAMPLE_OUT") {
std::fs::write(path, &json).unwrap();
}
}
/// Against a real Redis (`CRAFT_APPS_TEST_REDIS_URL`, default `redis://127.0.0.1:6379/`): an
/// instance takes another's fresh fetches from Redis instead of asking GitHub.
/// `cargo test -p storyteller-web --bin storyteller-web takes_fresh -- --ignored`
#[tokio::test]
#[ignore = "needs a Redis server"]
async fn takes_fresh_releases_from_redis_instead_of_github() {
let url = std::env::var("CRAFT_APPS_TEST_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379/".to_string());
let pool = build_poller_redis_pool(&url).unwrap();
let mut config = config();
let prefix = format!("test-craft-{}", rand::random::<u32>());
config.apps = vec![(format!("{prefix}-a"), "A".into(), "storytold/a".into()), (format!("{prefix}-b"), "B".into(), "storytold/b".into())];
let pod_a = SharedStore::new(pool.clone(), "pod-a".into());
let now = Utc::now();
for (key, _, _) in &config.apps {
assert!(pod_a.write_fetched(key, &CraftAppReleases::default(), &history(), Some("\"e\""), now).await.unwrap());
}
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&config.apps);
let mut pod_b = Poller::new(github::build_client().unwrap(), cache.clone(), config.clone(), Some(SharedStore::new(pool.clone(), "pod-b".into())));
let report = pod_b.tick().await;
assert_eq!(report.mode, PollMode::Coordinated);
assert_eq!(report.round.requests(), 0, "fresh in Redis, so GitHub isn't asked");
for (key, _, _) in &config.apps {
assert_eq!(fetched_at(&cache, key).map(|t| t.timestamp_millis()), Some(now.timestamp_millis()));
assert_eq!(cache.etag(key).as_deref(), Some("\"e\""));
assert_eq!(cache.app(key).unwrap().history.releases.len(), 1, "the history comes along");
}
let mut keys: Vec<String> = config.apps.iter().map(|(k, _, _)| CraftAppReleaseRedisKey::new_for_app(k).to_string()).collect();
keys.extend(config.apps.iter().map(|(k, _, _)| CraftAppReleaseHistoryRedisKey::new_for_app(k).to_string()));
let mut conn = pool.get().unwrap();
redis::cmd("DEL").arg(&keys).query::<()>(&mut *conn).unwrap();
}
/// Against a real Redis, as above: a new instance serves the fleet's releases right after
/// startup, before its startup jitter ends, without asking GitHub.
/// `cargo test -p storyteller-web --bin storyteller-web warm -- --ignored`
#[tokio::test]
#[ignore = "needs a Redis server"]
async fn a_new_instance_is_warm_from_redis_at_startup() {
let url = std::env::var("CRAFT_APPS_TEST_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379/".to_string());
let pool = build_poller_redis_pool(&url).unwrap();
let mut config = config();
let prefix = format!("test-craft-{}", rand::random::<u32>());
config.apps = vec![(format!("{prefix}-a"), "A".into(), "storytold/a".into()), (format!("{prefix}-b"), "B".into(), "storytold/b".into())];
let fetched_by_another_pod = Utc::now();
let other_pod = SharedStore::new(pool.clone(), "other-pod".into());
for (key, _, _) in &config.apps {
assert!(other_pod.write_fetched(key, &CraftAppReleases::default(), &history(), Some("\"e\""), fetched_by_another_pod).await.unwrap());
}
let cache = CraftAppsReleaseCache::new();
let poller = tokio::spawn(poll_craft_app_releases(cache.clone(), config.clone(), pool.clone(), "new-pod".into()));
let deadline = Instant::now() + Duration::from_secs(2);
while config.apps.iter().any(|(key, _, _)| fetched_at(&cache, key).is_none()) && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(20)).await;
}
poller.abort();
for (key, _, _) in &config.apps {
assert_eq!(fetched_at(&cache, key).map(|t| t.timestamp_millis()), Some(fetched_by_another_pod.timestamp_millis()), "{}", key);
}
let keys: Vec<String> = config.apps.iter().map(|(k, _, _)| CraftAppReleaseRedisKey::new_for_app(k).to_string()).collect();
let mut conn = pool.get().unwrap();
redis::cmd("DEL").arg(&keys).query::<()>(&mut *conn).unwrap();
}
#[tokio::test]
async fn an_unreachable_redis_falls_back_to_polling_alone() {
let pool = build_poller_redis_pool("redis://127.0.0.1:1/").unwrap();
let mut poller = fresh_poller(Some(SharedStore::new(pool, "pod".into())));
let report = poller.tick().await;
assert_eq!(report.mode, PollMode::Standalone);
assert_eq!(report.round.requests(), 0, "everything was fresh");
assert!(poller.redis_log.is_failing());
}
#[tokio::test]
async fn with_coordination_off_redis_is_never_used() {
let mut poller = fresh_poller(None);
let report = poller.tick().await;
assert_eq!(report.mode, PollMode::Standalone);
assert!(!poller.redis_log.is_failing());
}
#[tokio::test]
async fn an_active_backoff_skips_github_even_when_apps_are_due() {
let mut poller = Poller::new(github::build_client().unwrap(), registered_cache(), config(), None);
poller.backoff = Backoff { until: Some(Utc::now() + chrono::Duration::minutes(5)), trouble: 1 };
let report = poller.tick().await;
assert_eq!(report.round.requests(), 0);
assert_eq!(fetched_at(&poller.cache, "photocraft"), None);
}
#[test]
fn shared_entries_merge_into_memory() {
let cache = registered_cache();
let at = Utc::now();
let fields = encode_fetch(&CraftAppReleases::default(), Some("\"e\""), at, None, "pod").unwrap();
let map = fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
merge_shared_entry(&cache, "photocraft", decode_app_entry(&map).unwrap());
assert_eq!(fetched_at(&cache, "photocraft").map(|t| t.timestamp_millis()), Some(at.timestamp_millis()));
assert_eq!(cache.etag("photocraft").as_deref(), Some("\"e\""));
}
fn latest_tag(app: &crate::state::craft_apps_release_cache::CachedCraftApp) -> String {
app.releases.latest_release.as_ref().map(|r| r.tag.clone()).unwrap_or_default()
}
/// A history from the fetch with ETag `"e"`, holding one release.
fn history() -> CraftAppHistory {
let release = artcraft_api_defs::craft_apps::release_info::CraftAppRelease {
tag: "v0.5.0".into(),
version: "0.5.0".into(),
name: "A v0.5.0".into(),
published_at: None,
html_url: String::new(),
prerelease: false,
notes_markdown: String::new(),
assets: Vec::new(),
};
CraftAppHistory { etag: Some("\"e\"".into()), complete: true, releases: vec![release], fetched_at: None }
}
fn config() -> CraftAppsPollConfig {
CraftAppsPollConfig {
enabled: true,
coordination_enabled: true,
interval: Duration::from_secs(1800),
max_backoff: Duration::from_secs(14_400),
github_token: None,
apps: default_apps(),
}
}
fn registered_cache() -> CraftAppsReleaseCache {
let cache = CraftAppsReleaseCache::new();
cache.register_apps(&config().apps);
cache
}
/// A poller whose apps were all just fetched, so a tick makes no GitHub requests.
fn fresh_poller(store: Option<SharedStore>) -> Poller {
let cache = registered_cache();
for (key, _, _) in &config().apps {
cache.store(key, CraftAppReleases::default(), CraftAppHistory::default(), None, Utc::now());
}
Poller::new(github::build_client().unwrap(), cache, config(), store)
}
fn fetched_at(cache: &CraftAppsReleaseCache, app_key: &str) -> Option<DateTime<Utc>> {
cache.app(app_key).and_then(|app| app.app_last_fetched)
}
}
@@ -1,303 +0,0 @@
//! When to ask GitHub: per-app freshness, retries after failures, and the backoff after rate
//! limits. Pure functions of what's known, so the same rules apply whether this instance works
//! from the fleet's shared state in Redis or (as a fallback) only from its own memory.
use std::time::Duration;
use chrono::{DateTime, Utc};
use crate::state::craft_apps_release_cache::CachedCraftApp;
use crate::threads::poll_craft_app_releases_thread::config::CraftAppsPollConfig;
/// How often every instance wakes up to look at the shared state (with jitter).
pub const TICK: Duration = Duration::from_secs(30);
/// Allowance for clocks that differ between instances: an app fetched by another instance
/// counts as fresh until `interval - CLOCK_SKEW_MARGIN` has passed.
pub const CLOCK_SKEW_MARGIN: Duration = Duration::from_secs(30);
/// First wait after a failed request (or a round where every request failed); doubles up to the
/// normal interval.
const FIRST_FAILURE_RETRY: Duration = Duration::from_secs(60);
/// Extra margin after GitHub's announced rate-limit reset.
const RESET_MARGIN: Duration = Duration::from_secs(60);
/// What one round did.
#[derive(Debug, Default)]
pub struct RoundResult {
pub fetched: usize,
pub unchanged: usize,
pub failed: usize,
/// GitHub refused; `Some(Some(t))` when it said when to come back.
pub rate_limited: Option<Option<DateTime<Utc>>>,
}
/// Don't ask GitHub before `until`. `trouble` counts the rounds in a row that were rate limited
/// or failed entirely; each one makes the next wait longer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Backoff {
pub until: Option<DateTime<Utc>>,
pub trouble: u32,
}
impl RoundResult {
/// How many requests reached a conclusion (a rate limit counts as one).
pub fn requests(&self) -> usize {
self.fetched + self.unchanged + self.failed + usize::from(self.rate_limited.is_some())
}
}
impl Backoff {
pub fn is_active(&self, now: DateTime<Utc>) -> bool {
self.until.is_some_and(|until| until > now)
}
}
/// Whether `app` should be requested from GitHub now. An app is due once its last fetch (by any
/// instance) is `interval - CLOCK_SKEW_MARGIN` old, or at once when the fleet's history for it is
/// missing from Redis (only a full fetch writes it). After a failure it waits a minute, then two,
/// four, … up to the interval, so one broken repository is never retried every tick.
pub fn is_due(app: &CachedCraftApp, now: DateTime<Utc>, interval: Duration) -> bool {
if let Some(fetched) = app.app_last_fetched {
if age(fetched, now) < interval.saturating_sub(CLOCK_SKEW_MARGIN) && !app.history_missing {
return false;
}
}
if app.is_failing() {
if let Some(failed) = app.last_failed_at {
let retry = scaled(FIRST_FAILURE_RETRY, app.consecutive_failures).min(interval);
if age(failed, now) < retry.saturating_sub(CLOCK_SKEW_MARGIN) {
return false;
}
}
}
true
}
/// The backoff after a round that made at least one request, starting from `previous`. A good
/// round clears it.
pub fn backoff_after(config: &CraftAppsPollConfig, round: &RoundResult, previous: Backoff, now: DateTime<Utc>) -> Backoff {
let mut trouble = previous.trouble;
let wait = next_wait(config, round, &mut trouble, now);
if trouble == 0 {
return Backoff::default();
}
let wait = chrono::Duration::from_std(wait).unwrap_or(chrono::Duration::MAX);
Backoff { until: now.checked_add_signed(wait), trouble }
}
/// How long to wait before the next round. Rate limits wait for GitHub's reset and back off
/// further each time; rounds where everything failed retry sooner, but never faster than a
/// minute, doubling up to the normal interval.
fn next_wait(config: &CraftAppsPollConfig, round: &RoundResult, consecutive_trouble: &mut u32, now: DateTime<Utc>) -> Duration {
let base = if let Some(retry_at) = round.rate_limited {
*consecutive_trouble = consecutive_trouble.saturating_add(1);
let until_reset = retry_at
.and_then(|t| (t - now).to_std().ok())
.map(|d| d + RESET_MARGIN)
.unwrap_or(Duration::ZERO);
let backoff = scaled(config.interval, *consecutive_trouble);
until_reset.max(backoff).min(config.max_backoff)
} else if round.fetched == 0 && round.unchanged == 0 && round.failed > 0 {
*consecutive_trouble = consecutive_trouble.saturating_add(1);
scaled(FIRST_FAILURE_RETRY, *consecutive_trouble).min(config.interval)
} else {
*consecutive_trouble = 0;
config.interval
};
jittered(base, 0.1)
}
/// `base` ± `fraction`, so a fleet doesn't poll in lockstep. With `fraction == 1.0`, anywhere in
/// `0..=2×base`; used for the startup spread.
pub fn jittered(base: Duration, fraction: f64) -> Duration {
let factor = 1.0 + fraction * (rand::random::<f64>() * 2.0 - 1.0);
base.mul_f64(factor.max(0.0))
}
/// `base × 2^(n-1)`, without overflow.
fn scaled(base: Duration, n: u32) -> Duration {
base.saturating_mul(1u32 << n.saturating_sub(1).min(16))
}
/// How long ago `then` was; zero if it is in the future (another instance's clock runs ahead).
fn age(then: DateTime<Utc>, now: DateTime<Utc>) -> Duration {
(now - then).to_std().unwrap_or(Duration::ZERO)
}
#[cfg(test)]
mod tests {
use crate::threads::poll_craft_app_releases_thread::config::default_apps;
use super::*;
mod freshness {
use super::*;
#[test]
fn an_app_never_fetched_is_due() {
assert!(is_due(&app(None, None, 0), Utc::now(), Duration::from_secs(120)));
}
#[test]
fn a_fetch_counts_as_fresh_until_the_interval_minus_the_skew_margin() {
let now = Utc::now();
let interval = Duration::from_secs(120);
assert!(!is_due(&app(Some(now - secs(89)), None, 0), now, interval));
assert!(is_due(&app(Some(now - secs(90)), None, 0), now, interval));
assert!(is_due(&app(Some(now - secs(600)), None, 0), now, interval));
}
#[test]
fn a_fetch_from_a_clock_ahead_of_ours_is_fresh() {
let now = Utc::now();
assert!(!is_due(&app(Some(now + secs(20)), None, 0), now, Duration::from_secs(120)));
}
#[test]
fn a_failing_app_waits_longer_after_each_failure_up_to_the_interval() {
let now = Utc::now();
let interval = Duration::from_secs(1800);
// 1st failure: retry after 60 s (less the margin); 3rd: 240 s.
assert!(!is_due(&app(None, Some(now - secs(29)), 1), now, interval));
assert!(is_due(&app(None, Some(now - secs(30)), 1), now, interval));
assert!(!is_due(&app(None, Some(now - secs(200)), 3), now, interval));
assert!(is_due(&app(None, Some(now - secs(210)), 3), now, interval));
// Many failures: never longer than the interval.
assert!(is_due(&app(None, Some(now - secs(1770)), 30), now, interval));
}
#[test]
fn a_missing_shared_history_makes_a_fresh_app_due_but_keeps_the_failure_wait() {
let now = Utc::now();
let interval = Duration::from_secs(120);
let mut missing = app(Some(now - secs(10)), None, 0);
assert!(!is_due(&missing, now, interval));
missing.history_missing = true;
assert!(is_due(&missing, now, interval));
let mut failing = app(Some(now - secs(20)), Some(now - secs(10)), 1);
failing.history_missing = true;
assert!(!is_due(&failing, now, interval), "a failed full fetch still waits before the next");
}
#[test]
fn a_failure_older_than_the_last_fetch_is_ignored() {
let now = Utc::now();
let app = app(Some(now - secs(200)), Some(now - secs(300)), 5);
assert!(is_due(&app, now, Duration::from_secs(120)));
}
}
mod backoff {
use super::*;
#[test]
fn a_good_round_clears_the_backoff() {
let now = Utc::now();
let round = RoundResult { fetched: 1, unchanged: 3, failed: 1, ..RoundResult::default() };
let previous = Backoff { until: Some(now), trouble: 3 };
assert_eq!(backoff_after(&config(), &round, previous, now), Backoff::default());
}
#[test]
fn a_rate_limit_backs_off_the_fleet_until_after_the_reset() {
let now = Utc::now();
let round = RoundResult { rate_limited: Some(Some(now + chrono::Duration::minutes(50))), ..RoundResult::default() };
let b = backoff_after(&config(), &round, Backoff::default(), now);
assert_eq!(b.trouble, 1);
assert!(b.is_active(now + chrono::Duration::minutes(45)));
assert!(!b.is_active(now + chrono::Duration::minutes(57)));
}
#[test]
fn trouble_carries_over_between_rounds_and_instances() {
let now = Utc::now();
let round = RoundResult { failed: 2, ..RoundResult::default() };
let first = backoff_after(&config(), &round, Backoff::default(), now);
let second = backoff_after(&config(), &round, first, now);
assert_eq!((first.trouble, second.trouble), (1, 2));
assert!(second.until.unwrap() - now >= chrono::Duration::seconds(107), "{:?}", second);
}
#[test]
fn an_expired_backoff_is_not_active() {
let now = Utc::now();
assert!(!Backoff::default().is_active(now));
assert!(!Backoff { until: Some(now - secs(1)), trouble: 4 }.is_active(now));
assert!(Backoff { until: Some(now + secs(1)), trouble: 4 }.is_active(now));
}
}
mod waits {
use super::*;
#[test]
fn a_good_round_waits_the_interval_and_resets_trouble() {
let mut trouble = 3;
let round = RoundResult { fetched: 5, unchanged: 8, ..RoundResult::default() };
assert!(within(next_wait(&config(), &round, &mut trouble, Utc::now()), Duration::from_secs(1800)));
assert_eq!(trouble, 0);
}
#[test]
fn rate_limits_wait_for_the_reset_and_back_off_further_each_time() {
let now = Utc::now();
let mut trouble = 0;
// GitHub says come back in 50 minutes: wait that (plus margin), more than the interval.
let round = RoundResult { rate_limited: Some(Some(now + chrono::Duration::minutes(50))), ..RoundResult::default() };
assert!(within(next_wait(&config(), &round, &mut trouble, now), Duration::from_secs(51 * 60)));
// Again and again, with no reset time: 2×, 4×, … the interval, capped at the maximum.
let round = RoundResult { rate_limited: Some(None), ..RoundResult::default() };
assert!(within(next_wait(&config(), &round, &mut trouble, now), Duration::from_secs(3600)));
assert!(within(next_wait(&config(), &round, &mut trouble, now), Duration::from_secs(7200)));
for _ in 0..10 {
assert!(next_wait(&config(), &round, &mut trouble, now) <= Duration::from_secs(14_400).mul_f64(1.11));
}
}
#[test]
fn a_round_where_everything_failed_retries_sooner_but_not_in_a_tight_loop() {
let now = Utc::now();
let mut trouble = 0;
let round = RoundResult { failed: 13, ..RoundResult::default() };
assert!(within(next_wait(&config(), &round, &mut trouble, now), Duration::from_secs(60)));
assert!(within(next_wait(&config(), &round, &mut trouble, now), Duration::from_secs(120)));
for _ in 0..20 {
let w = next_wait(&config(), &round, &mut trouble, now);
assert!(w >= Duration::from_secs(53) && w <= Duration::from_secs(1800).mul_f64(1.11), "{:?}", w);
}
}
}
fn config() -> CraftAppsPollConfig {
CraftAppsPollConfig {
enabled: true,
coordination_enabled: true,
interval: Duration::from_secs(1800),
max_backoff: Duration::from_secs(14_400),
github_token: None,
apps: default_apps(),
}
}
fn app(fetched: Option<DateTime<Utc>>, failed: Option<DateTime<Utc>>, failures: u32) -> CachedCraftApp {
CachedCraftApp {
name: "PhotoCraft".into(),
repo: "storytold/photocraft".into(),
releases: Default::default(),
app_last_fetched: fetched,
etag: None,
last_failed_at: failed,
consecutive_failures: failures,
history: Default::default(),
history_current: true,
history_missing: false,
}
}
fn secs(n: i64) -> chrono::Duration {
chrono::Duration::seconds(n)
}
fn within(d: Duration, around: Duration) -> bool {
d >= around.mul_f64(0.89) && d <= around.mul_f64(1.11)
}
}
@@ -1,346 +0,0 @@
//! What the fleet shares in Redis about Craft App releases, and how it is encoded. Pure: the
//! Redis I/O is in `shared_store`.
//!
//! ## `craftApps:releases:v2:app:<app key>` (hash, 7 day TTL, refreshed on every write)
//!
//! `v2` since the entry holds every channel (`releases`). Instances still running the code that
//! knew only the latest release keep `craftApps:releases:app:<app key>`, so during a rollout the
//! two never overwrite each other's entries.
//!
//! | Field | Meaning |
//! |--------------|--------------------------------------------------------------------------------|
//! | `v` | Format version, `1`. Entries with another version are ignored (and replaced) |
//! | `fetched_ms` | When the release was last fetched or confirmed by GitHub (Unix ms) |
//! | `etag` | GitHub's ETag for that answer; empty for none |
//! | `releases` | What the fetch found, as JSON (`CraftAppReleases`) |
//! | `history_ms` | When the shared history was last read in full from GitHub (Unix ms); 0 unknown |
//! | `failed_ms` | When a request for the app last failed (Unix ms); stale once `fetched_ms` newer |
//! | `failures` | Failed requests in a row as of `failed_ms` |
//! | `claimed_ms` | When an instance last started a request for the app (Unix ms), to skip doubles; |
//! | | `0` once a result (fetch, `304` or failure) is shared, so the next can start |
//! | `by` | Hostname of the instance that wrote last, for debugging |
//!
//! ## `craftApps:releases:v2:history:<app key>` (string, 7 day TTL, refreshed with the hash)
//!
//! The app's whole release history as JSON (`CraftAppHistory`), written right after a fetch wins
//! the hash above. Its `etag` says which fetch it belongs to: an instance takes it only while the
//! hash holds the same ETag, and reads it only when its own history is behind, so the every-tick
//! read of the hashes stays small.
//!
//! ## `craftApps:releases:backoff` (hash, 1 day TTL; deleted after a good round)
//!
//! | Field | Meaning |
//! |------------|-----------------------------------------------------------------|
//! | `v` | Format version, `1` |
//! | `until_ms` | No instance asks GitHub before this time (Unix ms) |
//! | `trouble` | Rounds in a row that were rate limited or failed entirely |
//! | `by` | Hostname of the instance that wrote last, for debugging |
//!
//! Anything unreadable (wrong version, bad numbers, bad JSON) reads as absent, so it is
//! refetched and overwritten rather than trusted.
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases};
use crate::threads::poll_craft_app_releases_thread::scheduling::Backoff;
pub const FORMAT_VERSION: &str = "1";
pub const FIELD_VERSION: &str = "v";
pub const FIELD_FETCHED_MS: &str = "fetched_ms";
pub const FIELD_ETAG: &str = "etag";
pub const FIELD_RELEASES: &str = "releases";
pub const FIELD_FAILED_MS: &str = "failed_ms";
pub const FIELD_FAILURES: &str = "failures";
pub const FIELD_CLAIMED_MS: &str = "claimed_ms";
pub const FIELD_HISTORY_MS: &str = "history_ms";
pub const FIELD_BY: &str = "by";
pub const FIELD_UNTIL_MS: &str = "until_ms";
pub const FIELD_TROUBLE: &str = "trouble";
/// One app's shared entry, as read from Redis.
#[derive(Clone, Debug, Default)]
pub struct SharedAppEntry {
pub fetched: Option<SharedFetch>,
pub failure: Option<SharedFailure>,
}
/// A successful fetch (or `304` confirmation) by some instance.
#[derive(Clone, Debug)]
pub struct SharedFetch {
pub releases: CraftAppReleases,
pub etag: Option<String>,
pub fetched_at: DateTime<Utc>,
/// When the shared history was last read in full; `None` when not known.
pub history_at: Option<DateTime<Utc>>,
}
/// A request's result is shared, so its claim is over: the next request may start at once.
const RELEASED_CLAIM: (&str, &str) = (FIELD_CLAIMED_MS, "0");
/// The last failed request by some instance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SharedFailure {
pub failed_at: DateTime<Utc>,
pub consecutive_failures: u32,
}
/// Reads an app's hash. `None` for an empty hash or another format version.
pub fn decode_app_entry(fields: &HashMap<String, String>) -> Option<SharedAppEntry> {
if fields.get(FIELD_VERSION).map(String::as_str) != Some(FORMAT_VERSION) {
return None;
}
let fetched = decode_fetch(fields);
let failure = time_field(fields, FIELD_FAILED_MS).map(|failed_at| SharedFailure {
failed_at,
consecutive_failures: fields.get(FIELD_FAILURES).and_then(|f| f.parse().ok()).unwrap_or(1).max(1),
});
Some(SharedAppEntry { fetched, failure })
}
/// The fields written for a successful fetch, whose history was read in full at `history_at`.
pub fn encode_fetch(releases: &CraftAppReleases, etag: Option<&str>, fetched_at: DateTime<Utc>, history_at: Option<DateTime<Utc>>, by: &str) -> Result<Vec<(&'static str, String)>, serde_json::Error> {
Ok(vec![
(FIELD_VERSION, FORMAT_VERSION.to_string()),
(FIELD_FETCHED_MS, fetched_at.timestamp_millis().to_string()),
(FIELD_ETAG, etag.unwrap_or_default().to_string()),
(FIELD_RELEASES, serde_json::to_string(releases)?),
(FIELD_HISTORY_MS, history_at.map(|at| at.timestamp_millis()).unwrap_or(0).to_string()),
(RELEASED_CLAIM.0, RELEASED_CLAIM.1.to_string()),
(FIELD_BY, by.to_string()),
])
}
/// The fields written for a `304`: only the time moves.
pub fn encode_unchanged(fetched_at: DateTime<Utc>, by: &str) -> Vec<(&'static str, String)> {
vec![
(FIELD_VERSION, FORMAT_VERSION.to_string()),
(FIELD_FETCHED_MS, fetched_at.timestamp_millis().to_string()),
(RELEASED_CLAIM.0, RELEASED_CLAIM.1.to_string()),
(FIELD_BY, by.to_string()),
]
}
/// The fields written for a failed request.
pub fn encode_failure(failure: SharedFailure, by: &str) -> Vec<(&'static str, String)> {
vec![
(FIELD_VERSION, FORMAT_VERSION.to_string()),
(FIELD_FAILED_MS, failure.failed_at.timestamp_millis().to_string()),
(FIELD_FAILURES, failure.consecutive_failures.to_string()),
(RELEASED_CLAIM.0, RELEASED_CLAIM.1.to_string()),
(FIELD_BY, by.to_string()),
]
}
/// The JSON shared for an app's history.
pub fn encode_history(history: &CraftAppHistory) -> Result<String, serde_json::Error> {
serde_json::to_string(history)
}
/// Reads a shared history; `None` when it is unreadable (it is then read again next time).
pub fn decode_history(json: &str) -> Option<CraftAppHistory> {
serde_json::from_str(json).ok()
}
/// Reads the backoff hash; anything absent or unreadable is no backoff.
pub fn decode_backoff(fields: &HashMap<String, String>) -> Backoff {
if fields.get(FIELD_VERSION).map(String::as_str) != Some(FORMAT_VERSION) {
return Backoff::default();
}
Backoff {
until: time_field(fields, FIELD_UNTIL_MS),
trouble: fields.get(FIELD_TROUBLE).and_then(|t| t.parse().ok()).unwrap_or(0),
}
}
pub fn encode_backoff(backoff: Backoff, by: &str) -> Vec<(&'static str, String)> {
vec![
(FIELD_VERSION, FORMAT_VERSION.to_string()),
(FIELD_UNTIL_MS, backoff.until.map(|u| u.timestamp_millis()).unwrap_or(0).to_string()),
(FIELD_TROUBLE, backoff.trouble.to_string()),
(FIELD_BY, by.to_string()),
]
}
/// The fetch part of an app's hash; `None` unless the time, the ETag and the releases all read.
fn decode_fetch(fields: &HashMap<String, String>) -> Option<SharedFetch> {
let fetched_at = time_field(fields, FIELD_FETCHED_MS)?;
let releases: CraftAppReleases = serde_json::from_str(fields.get(FIELD_RELEASES)?).ok()?;
let etag = fields.get(FIELD_ETAG)?;
Some(SharedFetch {
releases,
etag: (!etag.is_empty()).then(|| etag.clone()),
fetched_at,
history_at: time_field(fields, FIELD_HISTORY_MS),
})
}
/// A Unix-milliseconds field; `None` when absent, unreadable or zero.
fn time_field(fields: &HashMap<String, String>, name: &str) -> Option<DateTime<Utc>> {
let ms = fields.get(name)?.parse::<i64>().ok().filter(|ms| *ms > 0)?;
DateTime::from_timestamp_millis(ms)
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use artcraft_api_defs::craft_apps::release_info::CraftAppRelease;
use super::*;
const BY: &str = "storyteller-web-abc";
mod app_entries {
use super::*;
#[test]
fn a_fetch_round_trips() {
let at = time();
let fields = to_map(encode_fetch(&releases(), Some("\"e1\""), at, Some(at), BY).unwrap());
let entry = decode_app_entry(&fields).unwrap();
let fetched = entry.fetched.unwrap();
assert_eq!((fetched.etag.as_deref(), fetched.fetched_at, fetched.history_at), (Some("\"e1\""), at, Some(at)));
assert_eq!(json(&fetched.releases), json(&releases()));
assert_eq!(entry.failure, None);
}
/// The claim only keeps a second instance from asking while the first one is; once its result
/// is shared, whatever it was, the next request (when due) needn't wait out the window.
#[test]
fn every_result_releases_the_claim() {
let released = |fields: Vec<(&'static str, String)>| to_map(fields).get(FIELD_CLAIMED_MS).map(String::as_str) == Some("0");
assert!(released(encode_fetch(&releases(), Some("\"e1\""), time(), None, BY).unwrap()));
assert!(released(encode_unchanged(time(), BY)));
assert!(released(encode_failure(SharedFailure { failed_at: time(), consecutive_failures: 1 }, BY)));
}
#[test]
fn a_repo_without_release_or_etag_round_trips() {
let fields = to_map(encode_fetch(&CraftAppReleases::default(), None, time(), None, BY).unwrap());
let fetched = decode_app_entry(&fields).unwrap().fetched.unwrap();
assert!(fetched.releases.latest_release.is_none());
assert!(fetched.releases.releases.is_empty());
assert_eq!(fetched.etag, None);
}
#[test]
fn a_304_moves_only_the_time() {
let mut fields = to_map(encode_fetch(&releases(), Some("\"e1\""), time(), None, BY).unwrap());
let later = time() + chrono::Duration::minutes(2);
fields.extend(to_map(encode_unchanged(later, BY)));
let fetched = decode_app_entry(&fields).unwrap().fetched.unwrap();
assert_eq!((fetched.fetched_at, fetched.etag.as_deref()), (later, Some("\"e1\"")));
assert_eq!(json(&fetched.releases), json(&releases()));
}
#[test]
fn a_failure_round_trips_alongside_a_fetch() {
let mut fields = to_map(encode_fetch(&CraftAppReleases::default(), None, time(), None, BY).unwrap());
let failure = SharedFailure { failed_at: time() + chrono::Duration::minutes(1), consecutive_failures: 3 };
fields.extend(to_map(encode_failure(failure, BY)));
let entry = decode_app_entry(&fields).unwrap();
assert_eq!(entry.failure, Some(failure));
assert!(entry.fetched.is_some());
}
#[test]
fn garbage_reads_as_absent() {
assert!(decode_app_entry(&HashMap::new()).is_none());
let good = to_map(encode_fetch(&releases(), Some("\"e1\""), time(), None, BY).unwrap());
let with = |field: &str, value: &str| {
let mut fields = good.clone();
fields.insert(field.to_string(), value.to_string());
fields
};
assert!(decode_app_entry(&with(FIELD_VERSION, "2")).is_none(), "unknown version");
assert!(decode_app_entry(&with(FIELD_RELEASES, "{not json")).unwrap().fetched.is_none());
assert!(decode_app_entry(&with(FIELD_RELEASES, "{\"latest_release\":{\"tag\":1}}")).unwrap().fetched.is_none());
assert!(decode_app_entry(&with(FIELD_FETCHED_MS, "yesterday")).unwrap().fetched.is_none());
assert!(decode_app_entry(&with(FIELD_FAILED_MS, "-5")).unwrap().failure.is_none());
}
#[test]
fn an_entry_with_only_the_latest_release_is_no_fetch() {
// What the code before every channel was shared wrote: refetched, not served half-empty.
let mut fields = to_map(encode_fetch(&releases(), Some("\"e1\""), time(), None, BY).unwrap());
fields.remove(FIELD_RELEASES);
fields.insert("release".into(), serde_json::to_string(&releases().latest_release).unwrap());
assert!(decode_app_entry(&fields).unwrap().fetched.is_none());
}
}
mod histories {
use super::*;
#[test]
fn a_history_round_trips_and_garbage_reads_as_absent() {
let history = CraftAppHistory { etag: Some("\"e1\"".into()), complete: true, releases: vec![release("v0.5.0", false)], fetched_at: None };
let read = decode_history(&encode_history(&history).unwrap()).unwrap();
assert_eq!((read.etag.as_deref(), read.complete, read.releases.len()), (Some("\"e1\""), true, 1));
assert!(decode_history("{not json").is_none());
assert!(decode_history(r#"{"releases": [{"tag": 1}]}"#).is_none());
}
}
mod backoffs {
use super::*;
#[test]
fn a_backoff_round_trips() {
let backoff = Backoff { until: Some(time()), trouble: 4 };
assert_eq!(decode_backoff(&to_map(encode_backoff(backoff, BY))), backoff);
}
#[test]
fn garbage_reads_as_no_backoff() {
assert_eq!(decode_backoff(&HashMap::new()), Backoff::default());
let mut fields = to_map(encode_backoff(Backoff { until: Some(time()), trouble: 4 }, BY));
fields.insert(FIELD_VERSION.into(), "zz".into());
assert_eq!(decode_backoff(&fields), Backoff::default());
fields.insert(FIELD_VERSION.into(), FORMAT_VERSION.into());
fields.insert(FIELD_UNTIL_MS.into(), "soon".into());
fields.insert(FIELD_TROUBLE.into(), "-1".into());
assert_eq!(decode_backoff(&fields), Backoff::default());
}
}
fn time() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 10, 10, 12, 0, 0).unwrap()
}
fn release(tag: &str, prerelease: bool) -> CraftAppRelease {
CraftAppRelease {
tag: tag.into(),
version: tag.trim_start_matches('v').into(),
name: format!("PhotoCraft {tag}"),
published_at: Some(time()),
html_url: format!("https://github.com/storytold/photocraft/releases/tag/{tag}"),
prerelease,
notes_markdown: "Notes".into(),
assets: Vec::new(),
}
}
/// Every channel filled.
fn releases() -> CraftAppReleases {
let stable = release("v0.5.0", false);
let beta = release("v0.6.0-rc.1", true);
CraftAppReleases {
releases: vec![(&beta).into(), (&stable).into()],
latest_release: Some(stable),
latest_prerelease: Some(beta),
latest_nightly: Some(release("v0.6.0-nightly.20261126.1.1", true)),
}
}
fn json(releases: &CraftAppReleases) -> String {
serde_json::to_string(releases).unwrap()
}
fn to_map(fields: Vec<(&'static str, String)>) -> HashMap<String, String> {
fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
}
}
@@ -1,717 +0,0 @@
//! Reads and writes the fleet's shared Craft App release state in Redis (keys and fields are
//! documented in `shared_entry`).
//!
//! Writes are last-write-wins but guarded by time: a Lua script compares a timestamp field
//! before writing, so a slow instance never replaces a newer fetch with an older one. A `304`
//! moves only `fetched_ms`, and only if the stored ETag is still the one that was revalidated.
//!
//! Some Redis setups refuse scripts (scripting disabled, an ACL without `EVAL`, a proxy). The
//! first time Redis refuses the script, this store switches to applying the same rule itself:
//! it `WATCH`es the hash, reads and decodes the guarding fields, decides, and writes in a
//! `MULTI`/`EXEC` that Redis drops if another instance wrote in between (then it decides again).
//!
//! The pool is r2d2 (blocking), so every call runs on tokio's blocking pool with a timeout:
//! Redis trouble costs the polling loop a few seconds at most, never a stuck thread of the
//! async runtime. The poller gets its own small pool ([`build_poller_redis_pool`]) whose
//! connections time out reads and writes, so a hung Redis can neither strand blocking threads
//! nor take connections from the request handlers' pool.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use log::warn;
use r2d2::{ManageConnection, Pool};
use redis::{Client, Connection, ConnectionLike, ErrorKind, RedisError, RedisResult, Script, ServerErrorKind, Value};
use redis_schema::keys::craft_apps::craft_app_release_history_redis_key::CraftAppReleaseHistoryRedisKey;
use redis_schema::keys::craft_apps::craft_app_release_redis_key::CraftAppReleaseRedisKey;
use redis_schema::keys::craft_apps::craft_apps_release_backoff_redis_key::CraftAppsReleaseBackoffRedisKey;
use crate::state::craft_apps_release_cache::{CraftAppHistory, CraftAppReleases};
use crate::threads::poll_craft_app_releases_thread::scheduling::Backoff;
use crate::threads::poll_craft_app_releases_thread::shared_entry;
use crate::threads::poll_craft_app_releases_thread::shared_entry::{SharedAppEntry, SharedFailure};
/// Connections in the poller's pool: one per instance is all the loop uses at a time.
const POOL_MAX_SIZE: u32 = 2;
/// Longest wait for a pooled connection.
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
/// Longest wait for one read or write on a connection; after it, the connection gives up
/// instead of holding its blocking thread until the operating system notices a dead peer.
const IO_TIMEOUT: Duration = Duration::from_secs(5);
/// Longest wait for a whole call, connection included.
const CALL_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a claim on an app keeps other instances from requesting it too: longer than one fetch
/// can take (up to 10 pages, each at most 10 s to connect and 30 s for the answer), plus a margin.
pub const CLAIM_WINDOW: Duration = Duration::from_secs(7 * 60);
/// Without scripts: how many times a guarded write decides again after another instance wrote
/// between its read and its write, before giving up (as if it lost the race).
const WATCH_ATTEMPTS: usize = 3;
/// Writes `ARGV[6..]` (field/value pairs) to the hash `KEYS[1]` and sets its TTL to `ARGV[4]` ms,
/// unless the hash's time field `ARGV[1]` already holds a value greater than
/// `ARGV[2] - ARGV[3]` (new time minus a minimum gap; a gap of 0 means "never go back in time"),
/// or `ARGV[5]` is non-empty and differs from the hash's `etag`. Returns 1 if written, else 0.
/// Unreadable stored times don't block the write, so garbage gets overwritten.
const GUARDED_HSET_LUA: &str = r#"
local current = tonumber(redis.call('HGET', KEYS[1], ARGV[1]))
if current and current + tonumber(ARGV[3]) > tonumber(ARGV[2]) then
return 0
end
if ARGV[5] ~= '' and redis.call('HGET', KEYS[1], 'etag') ~= ARGV[5] then
return 0
end
redis.call('HSET', KEYS[1], unpack(ARGV, 6))
redis.call('PEXPIRE', KEYS[1], ARGV[4])
return 1
"#;
static GUARDED_HSET: LazyLock<Script> = LazyLock::new(|| Script::new(GUARDED_HSET_LUA));
/// [`GUARDED_HSET_LUA`] with a companion: by the same rule and in the same step, also sets the
/// string `KEYS[2]` to `ARGV[6]` with the same TTL (the hash's fields then start at `ARGV[7]`).
/// The history of a fetch is written only together with the fetch it belongs to.
const GUARDED_HSET_WITH_COMPANION_LUA: &str = r#"
local current = tonumber(redis.call('HGET', KEYS[1], ARGV[1]))
if current and current + tonumber(ARGV[3]) > tonumber(ARGV[2]) then
return 0
end
if ARGV[5] ~= '' and redis.call('HGET', KEYS[1], 'etag') ~= ARGV[5] then
return 0
end
redis.call('HSET', KEYS[1], unpack(ARGV, 7))
redis.call('PEXPIRE', KEYS[1], ARGV[4])
redis.call('SET', KEYS[2], ARGV[6], 'PX', ARGV[4])
return 1
"#;
static GUARDED_HSET_WITH_COMPANION: LazyLock<Script> = LazyLock::new(|| Script::new(GUARDED_HSET_WITH_COMPANION_LUA));
/// Handle on the shared state. Cheap to clone.
#[derive(Clone)]
pub struct SharedStore {
pool: PollerRedisPool,
/// Written as `by`, for debugging.
hostname: String,
/// Set once Redis refuses the guarded-write script; from then on guarded writes use `WATCH`.
scripts_refused: Arc<AtomicBool>,
}
/// The poller's Redis pool; see [`build_poller_redis_pool`].
pub type PollerRedisPool = Pool<PollerRedisConnections>;
/// Makes the poller's Redis connections, every one of them with I/O timeouts.
pub struct PollerRedisConnections {
client: Client,
}
/// A guarded write: which time field guards it, and what to write.
struct GuardedWrite {
key: String,
time_field: &'static str,
time: DateTime<Utc>,
min_gap: Duration,
required_etag: Option<String>,
fields: Vec<(&'static str, String)>,
/// A string key set to a value only when, and in the same step as, the hash is written.
companion: Option<(String, String)>,
}
impl SharedStore {
pub fn new(pool: PollerRedisPool, hostname: String) -> Self {
Self { pool, hostname, scripts_refused: Arc::new(AtomicBool::new(false)) }
}
/// The shared entries of `app_keys` (in order; `None` for absent or unreadable ones) and the
/// fleet's backoff, in one round trip.
pub async fn read(&self, app_keys: &[String]) -> anyhow::Result<(Vec<Option<SharedAppEntry>>, Backoff)> {
let keys: Vec<String> = app_keys.iter().map(|k| CraftAppReleaseRedisKey::new_for_app(k).to_string()).collect();
let mut hashes: Vec<HashMap<String, String>> = self
.run(move |conn| {
let mut pipe = redis::pipe();
for key in &keys {
pipe.hgetall(key);
}
pipe.hgetall(CraftAppsReleaseBackoffRedisKey::new_for_fleet().as_str());
pipe.query(conn)
})
.await?;
let backoff = hashes.pop().map(|fields| shared_entry::decode_backoff(&fields)).unwrap_or_default();
let entries = hashes.iter().map(shared_entry::decode_app_entry).collect();
Ok((entries, backoff))
}
/// Claims the next request for `app_key` at `now`. False when another instance claimed it
/// within [`CLAIM_WINDOW`]: it is asking GitHub already, so this one doesn't. Not a lock: it
/// is never released and simply lapses, so a crashed instance can't block anyone.
pub async fn claim(&self, app_key: &str, now: DateTime<Utc>) -> anyhow::Result<bool> {
self.guarded_write(GuardedWrite {
key: CraftAppReleaseRedisKey::new_for_app(app_key).to_string(),
time_field: shared_entry::FIELD_CLAIMED_MS,
time: now,
min_gap: CLAIM_WINDOW,
required_etag: None,
fields: vec![
(shared_entry::FIELD_VERSION, shared_entry::FORMAT_VERSION.to_string()),
(shared_entry::FIELD_CLAIMED_MS, now.timestamp_millis().to_string()),
(shared_entry::FIELD_BY, self.hostname.clone()),
],
companion: None,
}).await
}
/// Shares a successful fetch and its history, in one step, unless a newer fetch is already
/// shared. Returns whether written.
pub async fn write_fetched(&self, app_key: &str, releases: &CraftAppReleases, history: &CraftAppHistory, etag: Option<&str>, fetched_at: DateTime<Utc>) -> anyhow::Result<bool> {
self.guarded_write(GuardedWrite {
key: CraftAppReleaseRedisKey::new_for_app(app_key).to_string(),
time_field: shared_entry::FIELD_FETCHED_MS,
time: fetched_at,
min_gap: Duration::ZERO,
required_etag: None,
fields: shared_entry::encode_fetch(releases, etag, fetched_at, history.fetched_at, &self.hostname)?,
companion: Some((CraftAppReleaseHistoryRedisKey::new_for_app(app_key).to_string(), shared_entry::encode_history(history)?)),
}).await
}
/// Extends the shared history's TTL to the entry's.
async fn touch_history(&self, app_key: &str) -> anyhow::Result<()> {
let key = CraftAppReleaseHistoryRedisKey::new_for_app(app_key).to_string();
let ttl_ms = CraftAppReleaseHistoryRedisKey::get_redis_ttl().num_milliseconds();
self.run(move |conn| redis::cmd("PEXPIRE").arg(&key).arg(ttl_ms).query::<()>(conn)).await
}
/// The shared history of `app_key`, `None` when absent or unreadable.
pub async fn read_history(&self, app_key: &str) -> anyhow::Result<Option<CraftAppHistory>> {
let key = CraftAppReleaseHistoryRedisKey::new_for_app(app_key).to_string();
let value: Option<String> = self.run(move |conn| redis::cmd("GET").arg(&key).query(conn)).await?;
Ok(value.as_deref().and_then(shared_entry::decode_history))
}
/// Shares a `304` for the release with ETag `etag`: moves only the fetch time, and only if
/// that release is still the shared one and nothing newer was shared. Returns whether written.
pub async fn write_unchanged(&self, app_key: &str, etag: &str, fetched_at: DateTime<Utc>) -> anyhow::Result<bool> {
if etag.is_empty() {
return Ok(false);
}
let written = self.guarded_write(GuardedWrite {
key: CraftAppReleaseRedisKey::new_for_app(app_key).to_string(),
time_field: shared_entry::FIELD_FETCHED_MS,
time: fetched_at,
min_gap: Duration::ZERO,
required_etag: Some(etag.to_string()),
fields: shared_entry::encode_unchanged(fetched_at, &self.hostname),
companion: None,
}).await?;
if written {
// The history lives as long as the hash it belongs with.
let key = CraftAppReleaseHistoryRedisKey::new_for_app(app_key).to_string();
let ttl_ms = CraftAppReleaseHistoryRedisKey::get_redis_ttl().num_milliseconds();
self.run(move |conn| redis::cmd("PEXPIRE").arg(&key).arg(ttl_ms).query::<()>(conn)).await?;
}
Ok(written)
}
/// Shares a failed request, unless a newer failure is already shared. Returns whether written.
pub async fn write_failure(&self, app_key: &str, failure: SharedFailure) -> anyhow::Result<bool> {
let written = self.guarded_write(GuardedWrite {
key: CraftAppReleaseRedisKey::new_for_app(app_key).to_string(),
time_field: shared_entry::FIELD_FAILED_MS,
time: failure.failed_at,
min_gap: Duration::ZERO,
required_etag: None,
fields: shared_entry::encode_failure(failure, &self.hostname),
companion: None,
}).await?;
// Failures keep the entry alive; the history lives as long, so it isn't the one to expire. Not
// extending it loses nothing yet, so it doesn't make the failure unshared.
if written {
if let Err(err) = self.touch_history(app_key).await {
warn!("Craft app releases: couldn't extend the shared history of {}: {}", app_key, err);
}
}
Ok(written)
}
/// Shares the fleet's backoff; no trouble deletes it.
pub async fn write_backoff(&self, backoff: Backoff) -> anyhow::Result<()> {
let key = CraftAppsReleaseBackoffRedisKey::new_for_fleet().to_string();
if backoff.trouble == 0 {
return self.run(move |conn| redis::cmd("DEL").arg(&key).query::<()>(conn)).await;
}
let fields = shared_entry::encode_backoff(backoff, &self.hostname);
let ttl_ms = CraftAppsReleaseBackoffRedisKey::get_redis_ttl().num_milliseconds();
self
.run(move |conn| {
redis::pipe()
.hset_multiple(&key, &fields).ignore()
.pexpire(&key, ttl_ms).ignore()
.query::<()>(conn)
})
.await
}
/// Applies `write` with the script, or (once Redis has refused the script) with `WATCH`.
async fn guarded_write(&self, write: GuardedWrite) -> anyhow::Result<bool> {
let ttl_ms = CraftAppReleaseRedisKey::get_redis_ttl().num_milliseconds();
let scripts_refused = self.scripts_refused.clone();
self
.run(move |conn| {
if !scripts_refused.load(Ordering::Relaxed) {
match guarded_write_with_script(conn, &write, ttl_ms) {
Err(err) if is_script_refusal(&err) => {
if !scripts_refused.swap(true, Ordering::Relaxed) {
warn!("Craft app releases: Redis refused the guarded-write script ({err}); writing with WATCH/MULTI/EXEC instead.");
}
}
result => return result,
}
}
guarded_write_with_watch(conn, &write, ttl_ms)
})
.await
}
/// Runs `call` on a pooled connection, off the async runtime, within [`CALL_TIMEOUT`].
async fn run<T, F>(&self, call: F) -> anyhow::Result<T>
where
T: Send + 'static,
F: FnOnce(&mut Connection) -> RedisResult<T> + Send + 'static,
{
let pool = self.pool.clone();
let task = tokio::task::spawn_blocking(move || -> anyhow::Result<T> {
let mut conn = pool.get_timeout(CONNECTION_TIMEOUT)?;
Ok(call(&mut conn)?)
});
match tokio::time::timeout(CALL_TIMEOUT, task).await {
Ok(Ok(result)) => result,
Ok(Err(join_err)) => Err(anyhow!("redis task failed: {join_err}")),
Err(_) => Err(anyhow!("redis call timed out after {CALL_TIMEOUT:?}")),
}
}
}
/// The poller's own Redis pool, apart from the one the request handlers use. Built without
/// connecting, so an unreachable Redis at startup doesn't stop the server: the poller then
/// works alone until Redis answers.
pub fn build_poller_redis_pool(redis_url: &str) -> RedisResult<PollerRedisPool> {
let manager = PollerRedisConnections { client: Client::open(redis_url)? };
Ok(Pool::builder()
.max_size(POOL_MAX_SIZE)
.min_idle(Some(0))
.connection_timeout(CONNECTION_TIMEOUT)
.build_unchecked(manager))
}
impl ManageConnection for PollerRedisConnections {
type Connection = Connection;
type Error = RedisError;
/// Connects (handshake included) within [`CONNECTION_TIMEOUT`], then makes every later read
/// and write give up after [`IO_TIMEOUT`], before the connection is ever used.
fn connect(&self) -> RedisResult<Connection> {
let conn = self.client.get_connection_with_timeout(CONNECTION_TIMEOUT)?;
conn.set_read_timeout(Some(IO_TIMEOUT))?;
conn.set_write_timeout(Some(IO_TIMEOUT))?;
Ok(conn)
}
/// The pool's check before lending a connection; bounded by [`IO_TIMEOUT`] like any command.
fn is_valid(&self, conn: &mut Connection) -> RedisResult<()> {
redis::cmd("PING").query::<()>(conn)
}
fn has_broken(&self, conn: &mut Connection) -> bool {
!conn.is_open()
}
}
/// [`GUARDED_HSET_LUA`] decides and writes on the server, in one step.
fn guarded_write_with_script(conn: &mut Connection, write: &GuardedWrite, ttl_ms: i64) -> RedisResult<bool> {
let mut invocation = match &write.companion {
Some((key, _)) => {
let mut invocation = GUARDED_HSET_WITH_COMPANION.key(&write.key);
invocation.key(key);
invocation
}
None => GUARDED_HSET.key(&write.key),
};
invocation
.arg(write.time_field)
.arg(write.time.timestamp_millis())
.arg(write.min_gap.as_millis() as u64)
.arg(ttl_ms)
.arg(write.required_etag.as_deref().unwrap_or_default());
if let Some((_, value)) = &write.companion {
invocation.arg(value);
}
for (field, value) in &write.fields {
invocation.arg(*field).arg(value);
}
let written: i64 = invocation.invoke(conn)?;
Ok(written == 1)
}
/// The same rule without scripts: `WATCH` the hash, read and decode its guarding fields, decide
/// with [`write_wins`], then write in a transaction. If another instance wrote the hash in
/// between, Redis drops the transaction and this decides again with what it wrote.
fn guarded_write_with_watch(conn: &mut Connection, write: &GuardedWrite, ttl_ms: i64) -> RedisResult<bool> {
for _ in 0..WATCH_ATTEMPTS {
redis::cmd("WATCH").arg(&write.key).query::<()>(conn)?;
let stored: RedisResult<(Option<String>, Option<String>)> = redis::cmd("HMGET")
.arg(&write.key)
.arg(write.time_field)
.arg(shared_entry::FIELD_ETAG)
.query(conn);
let (stored_time, stored_etag) = match stored {
Ok(stored) => stored,
Err(err) => {
// The connection goes back to the shared pool; don't leave it watching.
let _ = redis::cmd("UNWATCH").query::<()>(conn);
return Err(err);
}
};
if !write_wins(write, stored_time.as_deref(), stored_etag.as_deref()) {
redis::cmd("UNWATCH").query::<()>(conn)?;
return Ok(false);
}
// `EXEC` ends the watch either way; `None` means another write got in first.
let mut pipe = redis::pipe();
pipe.atomic().hset_multiple(&write.key, &write.fields).pexpire(&write.key, ttl_ms);
if let Some((key, value)) = &write.companion {
pipe.cmd("SET").arg(key).arg(value).arg("PX").arg(ttl_ms);
}
let committed: Option<Value> = pipe.query(conn)?;
if committed.is_some() {
return Ok(true);
}
}
Ok(false)
}
/// Whether `write` may replace what the hash holds, by the script's rule: not if the stored time
/// plus the minimum gap is later than the new time, nor if an ETag is required and the stored
/// one differs. An unreadable stored time doesn't block the write, so garbage gets overwritten.
fn write_wins(write: &GuardedWrite, stored_time: Option<&str>, stored_etag: Option<&str>) -> bool {
let new_ms = write.time.timestamp_millis();
let gap_ms = write.min_gap.as_millis().min(i64::MAX as u128) as i64;
if let Some(current_ms) = stored_time.and_then(|t| t.parse::<i64>().ok()) {
if current_ms.saturating_add(gap_ms) > new_ms {
return false;
}
}
match write.required_etag.as_deref().filter(|etag| !etag.is_empty()) {
Some(required) => stored_etag == Some(required),
None => true,
}
}
/// Whether Redis answered that it won't run the script (as opposed to being unreachable, busy,
/// out of memory or read-only, which the `WATCH` path wouldn't get past either): an ACL
/// refusal, an unknown `EVALSHA`/`EVAL`/`SCRIPT` command, or scripting switched off.
fn is_script_refusal(err: &RedisError) -> bool {
if err.is_io_error() || err.is_timeout() || err.is_connection_dropped() || err.is_connection_refusal() {
return false;
}
match err.kind() {
ErrorKind::Server(ServerErrorKind::NoPerm) => true,
ErrorKind::Server(ServerErrorKind::ResponseError) | ErrorKind::Extension => {
if err.code() == Some("BUSY") {
return false;
}
let detail = err.detail().unwrap_or_default().to_ascii_lowercase();
detail.contains("unknown command") || detail.contains("eval") || detail.contains("script")
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use chrono::TimeZone;
use url::Url;
use super::*;
const DEFAULT_TEST_REDIS_URL: &str = "redis://127.0.0.1:6379/";
/// Against a real Redis (`CRAFT_APPS_TEST_REDIS_URL`, default `redis://127.0.0.1:6379/`). Each
/// test uses app keys of its own, deletes them afterwards, and leaves the fleet backoff key
/// alone unless it was absent.
/// `cargo test -p storyteller-web --bin storyteller-web shared_store -- --ignored`
mod live_redis_tests {
use super::*;
#[tokio::test]
#[ignore = "needs a Redis server"]
async fn guarded_writes_with_the_script() {
let pool = test_pool(&test_redis_url());
let (pod_a, pod_b) = (SharedStore::new(pool.clone(), "pod-a".into()), SharedStore::new(pool, "pod-b".into()));
exercise_guarded_writes(&pod_a, &pod_b).await;
assert!(!pod_a.scripts_refused.load(Ordering::Relaxed));
}
#[tokio::test]
#[ignore = "needs a Redis server"]
async fn guarded_writes_with_watch() {
let pool = test_pool(&test_redis_url());
let (pod_a, pod_b) = (SharedStore::new(pool.clone(), "pod-a".into()), SharedStore::new(pool, "pod-b".into()));
pod_a.scripts_refused.store(true, Ordering::Relaxed);
pod_b.scripts_refused.store(true, Ordering::Relaxed);
exercise_guarded_writes(&pod_a, &pod_b).await;
}
/// A Redis user without scripting permissions: the first guarded write is refused, and the
/// store switches to `WATCH` and still applies every rule.
#[tokio::test]
#[ignore = "needs a Redis server that supports ACLs"]
async fn a_refused_script_falls_back_to_watch() {
let admin_url = test_redis_url();
let admin = test_pool(&admin_url);
let user = format!("craft-test-{}", rand::random::<u32>());
let password = format!("pw-{}", rand::random::<u64>());
let mut conn = admin.get().unwrap();
redis::cmd("ACL").arg("SETUSER").arg(&user).arg("reset").arg("on").arg(format!(">{password}")).arg("~*").arg("&*").arg("+@all").arg("-@scripting")
.query::<()>(&mut *conn).unwrap();
let mut url = Url::parse(&admin_url).unwrap();
url.set_username(&user).unwrap();
url.set_password(Some(&password)).unwrap();
let pool = test_pool(url.as_str());
let (pod_a, pod_b) = (SharedStore::new(pool.clone(), "pod-a".into()), SharedStore::new(pool, "pod-b".into()));
exercise_guarded_writes(&pod_a, &pod_b).await;
redis::cmd("ACL").arg("DELUSER").arg(&user).query::<()>(&mut *conn).unwrap();
assert!(pod_a.scripts_refused.load(Ordering::Relaxed), "the script should have been refused");
assert!(pod_b.scripts_refused.load(Ordering::Relaxed), "the script should have been refused");
}
}
/// An unreachable Redis fails fast, so the loop can fall back to polling on its own.
#[tokio::test]
async fn an_unreachable_redis_fails_fast() {
let pool = build_poller_redis_pool("redis://127.0.0.1:1/").unwrap();
let store = SharedStore::new(pool, "pod".into());
let started = std::time::Instant::now();
assert!(store.read(&["photocraft".to_string()]).await.is_err());
assert!(started.elapsed() < CALL_TIMEOUT + Duration::from_secs(1));
}
/// A Redis that completes the connection handshake and then stops answering (a wedged server,
/// a half-open connection): the call fails by itself, before [`CALL_TIMEOUT`] gives up on it,
/// so its blocking thread and connection are released rather than stranded until the
/// operating system notices. Without I/O timeouts the pool's `PING` would hang here forever.
#[tokio::test]
async fn a_redis_that_stops_answering_releases_the_blocking_thread() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("redis://{}/", listener.local_addr().unwrap());
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
std::thread::spawn(move || answer_handshake_then_go_silent(stream));
}
});
let store = SharedStore::new(build_poller_redis_pool(&url).unwrap(), "pod".into());
let started = std::time::Instant::now();
let err = store.read(&["photocraft".to_string()]).await.unwrap_err();
assert!(started.elapsed() < CALL_TIMEOUT, "{:?} after {:?}", err, started.elapsed());
}
/// [`write_wins`] must decide exactly as [`GUARDED_HSET_LUA`] does.
mod write_rule_tests {
use super::*;
#[test]
fn a_write_never_goes_back_in_time() {
let write = guarded_write_at(t(2), Duration::ZERO, None);
assert!(write_wins(&write, None, None), "nothing stored");
assert!(write_wins(&write, Some(&ms(t(1))), None), "newer than stored");
assert!(write_wins(&write, Some(&ms(t(2))), None), "same time, as the script allows");
assert!(!write_wins(&write, Some(&ms(t(3))), None), "older than stored");
}
#[test]
fn a_claim_waits_for_the_window() {
let window = chrono::Duration::from_std(CLAIM_WINDOW).unwrap();
let claim = guarded_write_at(t(0) + window, CLAIM_WINDOW, None);
assert!(!write_wins(&claim, Some(&ms(t(0) + chrono::Duration::seconds(30))), None));
assert!(write_wins(&claim, Some(&ms(t(0))), None), "exactly one window later");
}
#[test]
fn a_required_etag_must_match() {
let write = guarded_write_at(t(2), Duration::ZERO, Some("\"e2\""));
assert!(write_wins(&write, Some(&ms(t(1))), Some("\"e2\"")));
assert!(!write_wins(&write, Some(&ms(t(1))), Some("\"e1\"")), "another release is shared");
assert!(!write_wins(&write, Some(&ms(t(1))), None), "no release is shared");
assert!(write_wins(&guarded_write_at(t(2), Duration::ZERO, Some("")), None, None), "empty means none required");
}
#[test]
fn an_unreadable_stored_time_is_overwritten() {
let write = guarded_write_at(t(2), Duration::ZERO, None);
assert!(write_wins(&write, Some("soon"), None));
assert!(write_wins(&write, Some(""), None));
}
}
mod script_refusal_tests {
use redis::make_extension_error;
use super::*;
#[test]
fn redis_refusing_scripts_is_a_refusal() {
let refusals = [
server_error(ServerErrorKind::NoPerm, "this user has no permissions to run the 'evalsha' command"),
server_error(ServerErrorKind::ResponseError, "unknown command 'EVALSHA', with args beginning with: "),
server_error(ServerErrorKind::ResponseError, "This Redis instance has scripting disabled"),
make_extension_error("ERR".to_string(), Some("unknown command 'SCRIPT'".to_string())),
];
for err in refusals {
assert!(is_script_refusal(&err), "{:?}", err);
}
}
#[test]
fn redis_being_unavailable_is_not_a_refusal() {
let unavailable = [
RedisError::from(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "refused")),
RedisError::from(std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out")),
make_extension_error("OOM".to_string(), Some("command not allowed when used memory > 'maxmemory'.".to_string())),
make_extension_error("BUSY".to_string(), Some("Redis is busy running a script.".to_string())),
server_error(ServerErrorKind::ReadOnly, "You can't write against a read only replica."),
server_error(ServerErrorKind::ResponseError, "wrong number of arguments for 'hset' command"),
];
for err in unavailable {
assert!(!is_script_refusal(&err), "{:?}", err);
}
}
fn server_error(kind: ServerErrorKind, detail: &str) -> RedisError {
RedisError::from((ErrorKind::Server(kind), "server error", detail.to_string()))
}
}
/// Every guarded-write rule, as two instances sharing one Redis see it.
async fn exercise_guarded_writes(pod_a: &SharedStore, pod_b: &SharedStore) {
let app = format!("test-craft-{}", rand::random::<u32>());
let other = format!("{app}-other");
let keys = vec![app.clone(), other.clone()];
let read_app = |store: SharedStore, keys: Vec<String>| async move { store.read(&keys).await.unwrap().0.remove(0) };
// Nothing yet.
let (entries, _) = pod_a.read(&keys).await.unwrap();
assert!(entries.iter().all(Option::is_none));
// Two instances tick together: only one gets to ask GitHub; the claim lapses after the window.
assert!(pod_a.claim(&app, t(0)).await.unwrap());
assert!(!pod_b.claim(&app, t(0) + chrono::Duration::seconds(5)).await.unwrap());
assert!(pod_b.claim(&app, t(0) + chrono::Duration::from_std(CLAIM_WINDOW).unwrap()).await.unwrap());
// A newer fetch is never replaced by an older one.
let history = |etag: &str| CraftAppHistory { etag: Some(etag.into()), complete: true, releases: Vec::new(), fetched_at: None };
assert!(pod_a.write_fetched(&app, &CraftAppReleases::default(), &history("\"e2\""), Some("\"e2\""), t(2)).await.unwrap());
assert!(pod_a.claim(&app, t(2)).await.unwrap(), "a shared result releases the claim");
assert!(!pod_b.write_fetched(&app, &CraftAppReleases::default(), &history("\"e1\""), Some("\"e1\""), t(1)).await.unwrap());
assert_eq!(pod_b.read_history(&app).await.unwrap().unwrap().etag.as_deref(), Some("\"e2\""), "the losing write's history isn't shared");
let fetched = read_app(pod_a.clone(), keys.clone()).await.unwrap().fetched.unwrap();
assert_eq!((fetched.etag.as_deref(), fetched.fetched_at), (Some("\"e2\""), t(2)));
// A 304 moves the time only, and only for the release it revalidated.
assert!(!pod_b.write_unchanged(&app, "\"e1\"", t(3)).await.unwrap(), "stale ETag");
assert!(!pod_b.write_unchanged(&app, "\"e2\"", t(1)).await.unwrap(), "older than the shared fetch");
assert!(pod_b.write_unchanged(&app, "\"e2\"", t(3)).await.unwrap());
let fetched = read_app(pod_a.clone(), keys.clone()).await.unwrap().fetched.unwrap();
assert_eq!((fetched.etag.as_deref(), fetched.fetched_at), (Some("\"e2\""), t(3)));
// Failures: newest wins.
let failure = SharedFailure { failed_at: t(5), consecutive_failures: 2 };
assert!(pod_a.write_failure(&app, failure).await.unwrap());
assert!(!pod_b.write_failure(&app, SharedFailure { failed_at: t(4), consecutive_failures: 1 }).await.unwrap());
assert_eq!(read_app(pod_a.clone(), keys.clone()).await.unwrap().failure, Some(failure));
// Garbage in an entry is overwritten, not trusted.
let key = CraftAppReleaseRedisKey::new_for_app(&other).to_string();
let garbage_key = key.clone();
pod_a.run(move |conn| redis::cmd("HSET").arg(&garbage_key).arg("v").arg("1").arg("fetched_ms").arg("soon").arg("releases").arg("{").query::<()>(conn)).await.unwrap();
assert!(pod_a.read(&keys).await.unwrap().0[1].as_ref().unwrap().fetched.is_none());
assert!(pod_a.write_fetched(&other, &CraftAppReleases::default(), &CraftAppHistory::default(), None, t(1)).await.unwrap());
assert!(pod_a.read(&keys).await.unwrap().0[1].as_ref().unwrap().fetched.is_some());
// Entries expire if nobody refreshes them.
let ttl_key = key.clone();
let ttl: i64 = pod_a.run(move |conn| redis::cmd("PTTL").arg(&ttl_key).query(conn)).await.unwrap();
assert!(ttl > 6 * 24 * 3600 * 1000, "{}", ttl);
// The fleet backoff round-trips (only touched when absent, to leave a real one alone).
let (_, existing) = pod_a.read(&keys).await.unwrap();
if existing == Backoff::default() {
let backoff = Backoff { until: Some(t(30)), trouble: 2 };
pod_a.write_backoff(backoff).await.unwrap();
assert_eq!(pod_b.read(&keys).await.unwrap().1, backoff);
pod_b.write_backoff(Backoff::default()).await.unwrap();
assert_eq!(pod_a.read(&keys).await.unwrap().1, Backoff::default());
}
let mut cleanup: Vec<String> = keys.iter().map(|k| CraftAppReleaseRedisKey::new_for_app(k).to_string()).collect();
cleanup.extend(keys.iter().map(|k| CraftAppReleaseHistoryRedisKey::new_for_app(k).to_string()));
pod_a.run(move |conn| redis::cmd("DEL").arg(&cleanup).query::<()>(conn)).await.unwrap();
}
fn guarded_write_at(time: DateTime<Utc>, min_gap: Duration, required_etag: Option<&str>) -> GuardedWrite {
GuardedWrite {
key: "craftApps:releases:app:test".to_string(),
time_field: shared_entry::FIELD_FETCHED_MS,
time,
min_gap,
required_etag: required_etag.map(str::to_string),
fields: Vec::new(),
companion: None,
}
}
/// Answers `+OK` to connection setup (`CLIENT SETINFO`, `SELECT`, `HELLO`), then keeps the
/// connection open without another word once a real command (`PING`, `HGETALL`, ...) arrives.
fn answer_handshake_then_go_silent(mut stream: TcpStream) {
let mut buf = [0u8; 4096];
loop {
let n = match stream.read(&mut buf) {
Ok(0) | Err(_) => return,
Ok(n) => n,
};
let chunk = String::from_utf8_lossy(&buf[..n]).to_ascii_uppercase();
if !(chunk.contains("CLIENT") || chunk.contains("SELECT") || chunk.contains("HELLO")) {
std::thread::sleep(Duration::from_secs(60));
return;
}
let commands = chunk.lines().filter(|line| line.starts_with('*')).count();
if stream.write_all("+OK\r\n".repeat(commands).as_bytes()).is_err() {
return;
}
}
}
fn test_redis_url() -> String {
std::env::var("CRAFT_APPS_TEST_REDIS_URL").unwrap_or_else(|_| DEFAULT_TEST_REDIS_URL.to_string())
}
fn test_pool(url: &str) -> PollerRedisPool {
build_poller_redis_pool(url).unwrap()
}
fn t(minute: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 10, 10, 12, minute, 0).unwrap()
}
fn ms(time: DateTime<Utc>) -> String {
time.timestamp_millis().to_string()
}
}
@@ -35,6 +35,13 @@ const nextConfig: NextConfig = {
{ key: "Cache-Control", value: "public, max-age=31536000, immutable" },
],
},
{
source: "/launcher-screenshots/:path*",
headers: [
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Cache-Control", value: "public, max-age=31536000, immutable" },
],
},
];
},
async redirects() {
@@ -16,7 +16,7 @@
"test:studio": "playwright test --config playwright.studio.config.ts",
"test:repos": "playwright test tests/linux-repos.spec.ts tests/flatpak-oci.spec.ts",
"test:downloads": "playwright test tests/app-downloads.spec.ts tests/linux-downloads.spec.ts tests/linux-repos.spec.ts tests/flatpak-oci.spec.ts",
"test:launcher-catalog": "node --test scripts/sign-launcher-catalog.test.mjs"
"test:launcher-catalog": "node --test scripts/sign-launcher-catalog.test.mjs scripts/generate-launcher-catalog.test.mjs"
},
"dependencies": {
"@radix-ui/react-navigation-menu": "^1.2.22",
@@ -22,3 +22,7 @@
/launcher-app-icons/*
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=31536000, immutable
/launcher-screenshots/*
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=31536000, immutable
@@ -52,19 +52,19 @@ title = "Serious color"
[[apps.details.shots]]
caption = "Curves and type layers"
key = "demo"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/photocraft/demo.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/photocraft/demo.jpg"
[[apps.details.shots]]
caption = "Levels with a live histogram"
key = "adjustments"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/photocraft/adjustments.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/photocraft/adjustments.jpg"
[[apps.details.shots]]
caption = "Layer styles on live type"
key = "layer-styles"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/photocraft/layer-styles.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/photocraft/layer-styles.jpg"
[[apps.details.shots]]
caption = "Selections and masked adjustments"
key = "masks"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/photocraft/masks.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/photocraft/masks.jpg"
[[apps]]
color = [232, 87, 63]
@@ -117,19 +117,19 @@ title = "Open formats"
[[apps.details.shots]]
caption = "The Neon Drive poster"
key = "neon"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/vectorcraft/neon.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/vectorcraft/neon.jpg"
[[apps.details.shots]]
caption = "Live blends"
key = "ribbons"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/vectorcraft/ribbons.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/vectorcraft/ribbons.jpg"
[[apps.details.shots]]
caption = "A feature sheet and the Layers panel"
key = "sheet"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/vectorcraft/sheet.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/vectorcraft/sheet.jpg"
[[apps.details.shots]]
caption = "Pathfinder and exact booleans"
key = "bezier"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/vectorcraft/bezier.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/vectorcraft/bezier.jpg"
[[apps]]
color = [139, 92, 246]
@@ -182,15 +182,15 @@ title = "Broadcast-ready audio"
[[apps.details.shots]]
caption = "The Color workspace, with scopes"
key = "color"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/filmcraft/color.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/filmcraft/color.jpg"
[[apps.details.shots]]
caption = "The Assembly workspace"
key = "assembly"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/filmcraft/assembly.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/filmcraft/assembly.jpg"
[[apps.details.shots]]
caption = "Keyframes in Effect Controls"
key = "keyframes"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/filmcraft/keyframes.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/filmcraft/keyframes.jpg"
[[apps]]
color = [242, 165, 22]
@@ -243,19 +243,19 @@ title = "Instant feedback"
[[apps.details.shots]]
caption = "The Edit view"
key = "hero"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/lightcraft/hero.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/lightcraft/hero.jpg"
[[apps.details.shots]]
caption = "The tone curve"
key = "curve"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/lightcraft/curve.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/lightcraft/curve.jpg"
[[apps.details.shots]]
caption = "Color grading wheels"
key = "grading"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/lightcraft/grading.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/lightcraft/grading.jpg"
[[apps.details.shots]]
caption = "A radial mask over a sky mask"
key = "masking"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/lightcraft/masking.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/lightcraft/masking.jpg"
[[apps]]
color = [232, 32, 79]
@@ -357,19 +357,19 @@ title = "Export anywhere"
[[apps.details.shots]]
caption = "An animated composition"
key = "hero"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/effectcraft/hero.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/effectcraft/hero.jpg"
[[apps.details.shots]]
caption = "The Graph Editor"
key = "graph"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/effectcraft/graph.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/effectcraft/graph.jpg"
[[apps.details.shots]]
caption = "Particles and Effect Controls"
key = "effects"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/effectcraft/effects.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/effectcraft/effects.jpg"
[[apps.details.shots]]
caption = "3D layers with cameras and lights"
key = "3d"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/effectcraft/3d.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/effectcraft/3d.jpg"
[[apps]]
color = [218, 198, 4]
@@ -472,7 +472,7 @@ title = "Built for automation"
[[apps.details.shots]]
caption = "A magazine spread with a threaded story"
key = "spread"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/designcraft/spread.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/designcraft/spread.jpg"
[[apps]]
color = [2, 218, 150]
@@ -574,19 +574,19 @@ title = "Built for agents"
[[apps.details.shots]]
caption = "The Home tab and the Navigation pane"
key = "hero"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/wordcraft/hero.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/wordcraft/hero.jpg"
[[apps.details.shots]]
caption = "Track Changes and comments"
key = "review"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/wordcraft/review.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/wordcraft/review.jpg"
[[apps.details.shots]]
caption = "The Design tab"
key = "design"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/wordcraft/design.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/wordcraft/design.jpg"
[[apps.details.shots]]
caption = "The Layout tab"
key = "layout"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/wordcraft/layout.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/wordcraft/layout.jpg"
[[apps]]
color = [31, 165, 201]
@@ -633,19 +633,19 @@ title = "Plugins"
[[apps.details.shots]]
caption = "The Edit window with a nine-track session"
key = "edit"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/soundcraft/edit.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/soundcraft/edit.jpg"
[[apps.details.shots]]
caption = "The Mix window"
key = "mix"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/soundcraft/mix.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/soundcraft/mix.jpg"
[[apps.details.shots]]
caption = "Automation and memory locations"
key = "automation"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/soundcraft/automation.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/soundcraft/automation.jpg"
[[apps.details.shots]]
caption = "The Score Editor"
key = "score"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/soundcraft/score.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/soundcraft/score.jpg"
[[apps]]
color = [240, 122, 30]
@@ -698,19 +698,19 @@ title = "Exchange files"
[[apps.details.shots]]
caption = "Editing a slide, with sections and notes"
key = "editor"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/deckcraft/editor.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/deckcraft/editor.jpg"
[[apps.details.shots]]
caption = "The Shape Format tab"
key = "shape"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/deckcraft/shape.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/deckcraft/shape.jpg"
[[apps.details.shots]]
caption = "The slide sorter"
key = "sorter"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/deckcraft/sorter.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/deckcraft/sorter.jpg"
[[apps.details.shots]]
caption = "The Format Shape pane"
key = "format"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/deckcraft/format.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/deckcraft/format.jpg"
[[apps]]
color = [62, 166, 232]
@@ -760,15 +760,15 @@ title = "Built for agents"
[[apps.details.shots]]
caption = "An apartment floor plan"
key = "apartment"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/cadcraft/apartment.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/cadcraft/apartment.jpg"
[[apps.details.shots]]
caption = "A mechanical bracket drawing"
key = "bracket"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/cadcraft/bracket.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/cadcraft/bracket.jpg"
[[apps.details.shots]]
caption = "A layout sheet"
key = "layout"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/cadcraft/layout.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/cadcraft/layout.jpg"
[[apps]]
color = [31, 157, 85]
@@ -821,19 +821,19 @@ title = "Everywhere"
[[apps.details.shots]]
caption = "A quarterly sales dashboard"
key = "hero"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/gridcraft/hero.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/gridcraft/hero.jpg"
[[apps.details.shots]]
caption = "A household budget"
key = "budget"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/gridcraft/budget.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/gridcraft/budget.jpg"
[[apps.details.shots]]
caption = "A pivot table"
key = "pivot"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/gridcraft/pivot.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/gridcraft/pivot.jpg"
[[apps.details.shots]]
caption = "Formatting a chart"
key = "chart"
url = "https://raw.githubusercontent.com/storytold/craft-launcher-assets/v1/gridcraft/chart.jpg"
url = "https://getartcraft.com/launcher-screenshots/v1/gridcraft/chart.jpg"
[[apps]]
color = [194, 103, 43]
@@ -897,7 +897,6 @@ mac_team = "DJ6XS33FX8"
name = "MaterialCraft"
publisher = "ArtCraft"
repo = "storytold/materialcraft"
site = "https://github.com/storytold/materialcraft"
tagline = "Procedural material design"
[apps.details]
headline = "Build materials with node graphs."
@@ -1024,7 +1023,8 @@ kind = "community"
msi_publisher = "MailCraft contributors"
name = "MailCraft"
publisher = "UCS Labs"
repo = "UCS-Care-Group/mailcraft"
repo = "UCSLabs/mailcraft"
former_repo = "UCS-Care-Group/mailcraft"
site = "https://mailcraft.work"
tagline = "Mail, calendar and contacts"
[apps.details]
Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

@@ -25,9 +25,28 @@ Review changes to repositories and signing teams before publishing. The command
copies icons without modification and leaves older hashed icons available for
clients still using an earlier catalog.
## Cloudflare build signing
## Cloudflare build generation and signing
The existing `npm run build:cloudflare` static-export pipeline now signs the final
The existing `npm run build:cloudflare` static-export pipeline enriches
`public/launcher-catalog.toml` into `out/launcher-catalog.toml` via
`scripts/generate-launcher-catalog.mjs` before signing. Similar to the static
Linux repositories (`scripts/generate-static-repos.mjs`), it reads the latest
stable, prerelease, and nightly versions from `src/lib/crafting-app-releases.ts`
(kept fresh hourly by `.github/workflows/update-craft-release-versions.yml` and
on release-change dispatch; configure `CLOUDFLARE_DEPLOY_HOOK` to rebuild even
when the recorded version strings have not changed),
fetches each release's `SHA256SUMS.txt` from GitHub, and writes:
- top-level `generated_at` (RFC 3339 UTC timestamp),
- top-level `[launcher]` with `[launcher.releases.<channel>]` and
`[[launcher.releases.<channel>.assets]]` for `artcraft-launcher`, and
- per-app `[apps.releases.<channel>]` and `[[apps.releases.<channel>.assets]]`
(`stable`, `prerelease`, `nightly`) inside each `[[apps]]` entry.
`public/launcher-catalog.toml` itself stays unchanged so
`sync-launcher-catalog.py --check` continues to verify the base catalog cleanly.
`scripts/sign-launcher-catalog.mjs` then signs the final
`out/launcher-catalog.toml` bytes. It writes `out/launcher-catalog.toml.sig` as a
base64-encoded, 64-byte Ed25519 detached signature followed by a newline. This
format must be matched by the launcher verifier; it is not a minisign envelope.
@@ -77,5 +77,12 @@ execFileSync(process.execPath, ["--no-warnings", jitiBin, join(ROOT, "scripts",
env: process.env,
});
// Enrich out/launcher-catalog.toml with static release metadata (stable, prerelease, nightly)
// before signing the final exported bytes.
execFileSync(process.execPath, ["--no-warnings", jitiBin, join(ROOT, "scripts", "generate-launcher-catalog.mjs")], {
stdio: "inherit",
env: process.env,
});
// Sign the final exported bytes; missing/invalid secrets fail the deployment build.
signLauncherCatalog(join(ROOT, "out"));
@@ -0,0 +1,425 @@
import { createHash } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
// Matches craft-launcher's MAX_CATALOG_BYTES (1 MiB) so deployed catalogs never exceed the
// launcher's verification limit.
export const MAX_CATALOG_BYTES = 1 << 20;
const GITHUB_BASE = "https://github.com";
const SHA256SUMS_NAME = "SHA256SUMS.txt";
const MAX_FETCH_ATTEMPTS = 3;
const FETCH_TIMEOUT_MS = 10_000;
const FETCH_CONCURRENCY = 6;
const INVALID_FILENAME_CHARS = /[\x00-\x1f\x7f/\\:<>"|?*]/;
const HEX64 = /^[0-9a-f]{64}$/i;
/**
* Validates a release asset filename using the same rules as ArtCraft Launcher.
*/
export function isValidFileName(name) {
return (
typeof name === "string" &&
name.length > 0 &&
name.length <= 200 &&
!name.startsWith(".") &&
!INVALID_FILENAME_CHARS.test(name)
);
}
/**
* Validates a Git tag before interpolating it into a GitHub release URL.
*/
export function isValidTag(tag) {
return (
typeof tag === "string" &&
tag.length > 0 &&
tag.length <= 64 &&
!/[\s/\\?#\x00-\x1f\x7f]/.test(tag)
);
}
/**
* Parses a `SHA256SUMS.txt` file into sorted `{ name, sha256 }` entries.
* Invalid lines, malformed hashes, and unsafe filenames are skipped.
*/
export function parseSha256Sums(text) {
const byName = new Map();
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
const match = line.match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
if (!match) continue;
const sha256 = match[1].toLowerCase();
const name = match[2].trim();
if (!HEX64.test(sha256) || !isValidFileName(name)) continue;
byName.set(name, sha256);
}
return [...byName.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, sha256]) => ({ name, sha256 }));
}
/**
* Escapes a string as a TOML basic string literal.
*/
export function formatTomlString(value) {
let out = '"';
for (const ch of String(value)) {
const code = ch.codePointAt(0);
if (ch === "\\") out += "\\\\";
else if (ch === '"') out += '\\"';
else if (ch === "\b") out += "\\b";
else if (ch === "\t") out += "\\t";
else if (ch === "\n") out += "\\n";
else if (ch === "\f") out += "\\f";
else if (ch === "\r") out += "\\r";
else if (code < 0x20 || code === 0x7f) {
out += `\\u${code.toString(16).padStart(4, "0")}`;
} else {
out += ch;
}
}
return `${out}"`;
}
/**
* Fetches `SHA256SUMS.txt` for a GitHub release tag with retries and returns the checksummed
* assets it lists plus a record for `SHA256SUMS.txt` itself.
* Returns null if `SHA256SUMS.txt` is not published (HTTP 404).
*/
export async function fetchReleaseAssets(repo, tag, fetchImpl = fetch) {
if (!isValidTag(tag)) {
throw new Error(`Invalid release tag "${tag}" for ${repo}`);
}
const sumsUrl = `${GITHUB_BASE}/${repo}/releases/download/${encodeURIComponent(tag)}/${SHA256SUMS_NAME}`;
let lastError = new Error(`Unable to fetch ${sumsUrl}`);
for (let attempt = 1; attempt <= MAX_FETCH_ATTEMPTS; attempt += 1) {
try {
const res = await fetchImpl(sumsUrl, {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (res.status === 404) {
return null;
}
if (res.ok) {
const bytes = Buffer.from(await res.arrayBuffer());
const entries = parseSha256Sums(bytes.toString("utf8"));
const assets = entries.map(({ name, sha256 }) => ({
name,
download_url: `${GITHUB_BASE}/${repo}/releases/download/${tag}/${name}`,
sha256,
}));
// The checksum document is itself a release asset, as in GitHub's own asset list.
assets.push({
name: SHA256SUMS_NAME,
download_url: `${GITHUB_BASE}/${repo}/releases/download/${tag}/${SHA256SUMS_NAME}`,
sha256: createHash("sha256").update(bytes).digest("hex"),
});
return assets;
}
lastError = new Error(`HTTP ${res.status} fetching ${sumsUrl}`);
} catch (error) {
lastError = error instanceof Error ? error : lastError;
}
if (attempt < MAX_FETCH_ATTEMPTS) {
await new Promise((r) => setTimeout(r, 500 * attempt));
}
}
throw lastError;
}
/**
* Formats a single release channel (`stable`, `prerelease`, or `nightly`) under `tablePrefix`.
*/
export function formatReleaseSection(tablePrefix, release) {
const lines = [
`[${tablePrefix}]`,
`tag = ${formatTomlString(release.tag)}`,
`version = ${formatTomlString(release.version)}`,
`html_url = ${formatTomlString(release.html_url)}`,
`prerelease = ${release.prerelease ? "true" : "false"}`,
];
for (const asset of release.assets ?? []) {
lines.push(`[[${tablePrefix}.assets]]`);
lines.push(`name = ${formatTomlString(asset.name)}`);
lines.push(`download_url = ${formatTomlString(asset.download_url)}`);
if (asset.sha256) {
lines.push(`sha256 = ${formatTomlString(asset.sha256)}`);
}
}
return lines.join("\n");
}
function formatChannelsBlock(prefix, channels) {
if (!channels) return "";
const sections = [];
for (const channel of ["stable", "prerelease", "nightly"]) {
if (channels[channel]) {
sections.push(formatReleaseSection(`${prefix}.${channel}`, channels[channel]));
}
}
return sections.join("\n");
}
/**
* Enriches the committed `public/launcher-catalog.toml` text with statically generated
* `generated_at`, `[launcher]` release channels, and per-app `[apps.releases.*]` tables.
* Preserves all existing `[[apps]]` entries and display order.
*/
export function enrichLauncherCatalog(baseToml, { generatedAt, launcherReleases, appReleasesById }) {
const firstAppMatch = baseToml.match(/(^|\n)\[\[apps\]\]\r?\n/);
if (!firstAppMatch) {
throw new Error("Base launcher-catalog.toml contains no [[apps]] entries");
}
const splitIndex = firstAppMatch.index + (firstAppMatch[1] ? firstAppMatch[1].length : 0);
const headerPart = baseToml.slice(0, splitIndex).trimEnd();
const appsPart = baseToml.slice(splitIndex);
const preambleLines = [headerPart, "", `generated_at = ${formatTomlString(generatedAt)}`];
const launcherSections = formatChannelsBlock("launcher.releases", launcherReleases);
if (launcherSections) {
preambleLines.push(
"",
"[launcher]",
`id = ${formatTomlString("artcraft-launcher")}`,
`name = ${formatTomlString("ArtCraft Launcher")}`,
`repo = ${formatTomlString("storytold/craft-launcher")}`,
launcherSections,
);
}
// Split into individual `[[apps]]` blocks so each block's `[apps.releases.*]` attaches to it.
const appBlocks = appsPart.split(/(?=^\[\[apps\]\]\r?\n)/m).filter((block) => block.trim().length > 0);
const enrichedBlocks = appBlocks.map((block) => {
const trimmed = block.trimEnd();
const idMatch = trimmed.match(/^id\s*=\s*"([^"]+)"/m);
if (!idMatch) {
return trimmed;
}
const appId = idMatch[1];
const channelsText = formatChannelsBlock("apps.releases", appReleasesById?.[appId]);
return channelsText ? `${trimmed}\n${channelsText}` : trimmed;
});
const output = `${preambleLines.join("\n")}\n\n${enrichedBlocks.join("\n\n")}\n`;
const byteLength = Buffer.byteLength(output, "utf8");
if (byteLength > MAX_CATALOG_BYTES) {
throw new Error(
`Generated launcher-catalog.toml is ${byteLength} bytes, exceeding MAX_CATALOG_BYTES (${MAX_CATALOG_BYTES})`,
);
}
return output;
}
/**
* Runs async tasks with bounded concurrency.
*/
async function mapWithConcurrency(items, limit, fn) {
const results = new Array(items.length);
let nextIndex = 0;
async function worker() {
while (nextIndex < items.length) {
const index = nextIndex;
nextIndex += 1;
results[index] = await fn(items[index], index);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
await Promise.all(workers);
return results;
}
/**
* Collects all configured release targets from `crafting-app-releases.ts`.
*/
export async function collectConfiguredReleases() {
const {
CRAFT_APP_RELEASES,
CRAFT_COMMUNITY_RELEASES,
CRAFT_LAUNCHER_RELEASE,
CRAFT_NIGHTLY_RELEASES,
CRAFT_PRERELEASE_RELEASES,
} = await import("../src/lib/crafting-app-releases.ts");
const targets = [];
if (CRAFT_LAUNCHER_RELEASE) {
const tag = CRAFT_LAUNCHER_RELEASE.tag ?? `v${CRAFT_LAUNCHER_RELEASE.version}`;
targets.push({
id: "artcraft-launcher",
repo: "storytold/craft-launcher",
channel: "stable",
tag,
version: CRAFT_LAUNCHER_RELEASE.version,
prerelease: false,
required: true,
});
}
if (CRAFT_PRERELEASE_RELEASES["artcraft-launcher"]) {
const pre = CRAFT_PRERELEASE_RELEASES["artcraft-launcher"];
targets.push({
id: "artcraft-launcher",
repo: "storytold/craft-launcher",
channel: "prerelease",
tag: pre.tag,
version: pre.version,
prerelease: true,
required: false,
});
}
if (CRAFT_NIGHTLY_RELEASES["artcraft-launcher"]) {
const nightly = CRAFT_NIGHTLY_RELEASES["artcraft-launcher"];
targets.push({
id: "artcraft-launcher",
repo: "storytold/craft-launcher",
channel: "nightly",
tag: nightly.tag,
version: nightly.version,
prerelease: true,
required: false,
});
}
for (const [slug, release] of Object.entries(CRAFT_APP_RELEASES)) {
const repo = `storytold/${slug}`;
if (release) {
const tag = release.tag ?? `v${release.version}`;
targets.push({
id: slug,
repo,
channel: "stable",
tag,
version: release.version,
prerelease: false,
required: true,
});
}
const pre = CRAFT_PRERELEASE_RELEASES[slug];
if (pre) {
targets.push({
id: slug,
repo,
channel: "prerelease",
tag: pre.tag,
version: pre.version,
prerelease: true,
required: false,
});
}
const nightly = CRAFT_NIGHTLY_RELEASES[slug];
if (nightly) {
targets.push({
id: slug,
repo,
channel: "nightly",
tag: nightly.tag,
version: nightly.version,
prerelease: true,
required: false,
});
}
}
for (const [appId, entry] of Object.entries(CRAFT_COMMUNITY_RELEASES)) {
for (const channel of ["stable", "prerelease", "nightly"]) {
const ch = entry[channel];
if (!ch) continue;
targets.push({
id: appId,
repo: entry.repo,
channel,
tag: ch.tag,
version: ch.version,
prerelease: channel !== "stable",
required: false,
});
}
}
return targets;
}
/**
* Generates the static `out/launcher-catalog.toml` from `public/launcher-catalog.toml`
* and the configured release versions + GitHub `SHA256SUMS.txt` checksums.
*/
export async function generateLauncherCatalog({
baseCatalogPath,
outCatalogPath,
generatedAt = new Date().toISOString(),
targets,
fetchImpl = fetch,
}) {
const resolvedTargets = targets ?? (await collectConfiguredReleases());
const baseToml = readFileSync(baseCatalogPath, "utf8");
const launcherReleases = {};
const appReleasesById = {};
await mapWithConcurrency(resolvedTargets, FETCH_CONCURRENCY, async (target) => {
let assets = [];
try {
const fetched = await fetchReleaseAssets(target.repo, target.tag, fetchImpl);
if (fetched) {
assets = fetched;
} else if (target.required) {
throw new Error(`SHA256SUMS.txt not found for ${target.repo}@${target.tag}`);
}
} catch (error) {
if (target.required) {
throw error;
}
console.warn(
`Warning: could not fetch SHA256SUMS.txt for ${target.repo}@${target.tag} (${target.channel}): ${error instanceof Error ? error.message : error}`,
);
}
const record = {
tag: target.tag,
version: target.version,
html_url: `${GITHUB_BASE}/${target.repo}/releases/tag/${target.tag}`,
prerelease: target.prerelease,
assets,
};
if (target.id === "artcraft-launcher") {
launcherReleases[target.channel] = record;
} else {
if (!appReleasesById[target.id]) {
appReleasesById[target.id] = {};
}
appReleasesById[target.id][target.channel] = record;
}
});
const output = enrichLauncherCatalog(baseToml, {
generatedAt,
launcherReleases,
appReleasesById,
});
writeFileSync(outCatalogPath, output, "utf8");
return {
bytes: Buffer.byteLength(output, "utf8"),
releaseCount: resolvedTargets.length,
};
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const ROOT = process.cwd();
const baseCatalogPath = join(ROOT, "public", "launcher-catalog.toml");
const outCatalogPath = join(ROOT, "out", "launcher-catalog.toml");
console.info("Generating static launcher-catalog.toml release metadata...");
const { bytes, releaseCount } = await generateLauncherCatalog({
baseCatalogPath,
outCatalogPath,
});
console.info(`Generated out/launcher-catalog.toml (${releaseCount} release channels, ${bytes} bytes).`);
}
@@ -0,0 +1,245 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { createHash, generateKeyPairSync, verify } from "node:crypto";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import {
MAX_CATALOG_BYTES,
enrichLauncherCatalog,
generateLauncherCatalog,
parseSha256Sums,
} from "./generate-launcher-catalog.mjs";
import { signLauncherCatalog } from "./sign-launcher-catalog.mjs";
const HASH_A = "a".repeat(64);
const HASH_B = "b".repeat(64);
const HASH_C = "c".repeat(64);
const BASE_TOML = `# Header comment
# Source: test
[[apps]]
id = "photocraft"
name = "PhotoCraft"
repo = "storytold/photocraft"
[apps.details]
headline = "Image editor"
[[apps.details.features]]
title = "Fast"
text = "Native GPU"
[[apps]]
id = "solidcraft"
name = "SolidCraft"
repo = "tangency-labs/solidcraft"
[apps.details]
headline = "CAD"
`;
test("parseSha256Sums parses standard and binary-mode entries and rejects unsafe filenames", () => {
const sums = parseSha256Sums([
`${HASH_B.toUpperCase()} photocraft-0.23.1-windows-x64.msi`,
`${HASH_A} *photocraft-0.23.1-macos-universal.dmg`,
`${HASH_C} ../evil.msi`,
`${HASH_C} .hidden`,
"not-a-hash file.zip",
`${HASH_C} sub/dir.zip`,
].join("\n"));
assert.deepEqual(sums, [
{ name: "photocraft-0.23.1-macos-universal.dmg", sha256: HASH_A },
{ name: "photocraft-0.23.1-windows-x64.msi", sha256: HASH_B },
]);
});
test("generateLauncherCatalog enriches stable, prerelease, and nightly channels and produces valid signed TOML", async (t) => {
const dir = mkdtempSync(join(tmpdir(), "launcher-catalog-gen-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const baseCatalogPath = join(dir, "base.toml");
const outCatalogPath = join(dir, "launcher-catalog.toml");
writeFileSync(baseCatalogPath, BASE_TOML, "utf8");
writeFileSync(join(dir, "launcher-announcements.toml"), '[[announcements]]\nid = "a1"\ntitle = "Hi"\n', "utf8");
const responses = new Map([
[
"https://github.com/storytold/craft-launcher/releases/download/v0.20.3/SHA256SUMS.txt",
`${HASH_A} artcraft-launcher-0.20.3-macos-universal.dmg\n`,
],
[
"https://github.com/storytold/craft-launcher/releases/download/v0.21.0-nightly.20261126.1.1/SHA256SUMS.txt",
`${HASH_B} artcraft-launcher-0.21.0-nightly.20261126.1.1-linux-x86_64.AppImage\n`,
],
[
"https://github.com/storytold/photocraft/releases/download/v0.23.1/SHA256SUMS.txt",
`${HASH_A} photocraft-0.23.1-macos-universal.dmg\n${HASH_B} photocraft-0.23.1-windows-x64.msi\n`,
],
[
"https://github.com/storytold/photocraft/releases/download/v0.24.0-rc.1/SHA256SUMS.txt",
`${HASH_C} photocraft-0.24.0-rc.1-macos-universal.dmg\n`,
],
[
"https://github.com/storytold/photocraft/releases/download/v0.24.0-nightly.20261126.5.1/SHA256SUMS.txt",
`${HASH_C} photocraft-0.24.0-nightly.20261126.5.1-linux-x86_64.AppImage\n`,
],
]);
const fakeFetch = async (url) => {
const body = responses.get(String(url));
if (body === undefined) {
return { ok: false, status: 404, text: async () => "" };
}
return { ok: true, status: 200, arrayBuffer: async () => Buffer.from(body, "utf8") };
};
const result = await generateLauncherCatalog({
baseCatalogPath,
outCatalogPath,
generatedAt: "2026-11-26T21:30:00.000Z",
targets: [
{
id: "artcraft-launcher",
repo: "storytold/craft-launcher",
channel: "stable",
tag: "v0.20.3",
version: "0.20.3",
prerelease: false,
required: true,
},
{
id: "artcraft-launcher",
repo: "storytold/craft-launcher",
channel: "nightly",
tag: "v0.21.0-nightly.20261126.1.1",
version: "0.21.0-nightly.20261126.1.1",
prerelease: true,
required: false,
},
{
id: "photocraft",
repo: "storytold/photocraft",
channel: "stable",
tag: "v0.23.1",
version: "0.23.1",
prerelease: false,
required: true,
},
{
id: "photocraft",
repo: "storytold/photocraft",
channel: "prerelease",
tag: "v0.24.0-rc.1",
version: "0.24.0-rc.1",
prerelease: true,
required: false,
},
{
id: "photocraft",
repo: "storytold/photocraft",
channel: "nightly",
tag: "v0.24.0-nightly.20261126.5.1",
version: "0.24.0-nightly.20261126.5.1",
prerelease: true,
required: false,
},
{
id: "solidcraft",
repo: "tangency-labs/solidcraft",
channel: "stable",
tag: "v0.3.0",
version: "0.3.0",
prerelease: false,
required: false,
},
],
fetchImpl: fakeFetch,
});
assert.equal(result.releaseCount, 6);
assert.ok(result.bytes > 0 && result.bytes <= MAX_CATALOG_BYTES);
// Parse the generated TOML with Python's stdlib tomllib to verify strict TOML 1.0 compliance.
const py = spawnSync(
"python3",
[
"-c",
'import json, sys, tomllib; print(json.dumps(tomllib.loads(open(sys.argv[1], "rb").read().decode())))',
outCatalogPath,
],
{ encoding: "utf8" },
);
assert.equal(py.status, 0, py.stderr);
const parsed = JSON.parse(py.stdout);
assert.equal(parsed.generated_at, "2026-11-26T21:30:00.000Z");
assert.equal(parsed.launcher.id, "artcraft-launcher");
assert.equal(parsed.launcher.releases.stable.tag, "v0.20.3");
assert.equal(parsed.launcher.releases.stable.assets.length, 2);
assert.equal(parsed.launcher.releases.nightly.tag, "v0.21.0-nightly.20261126.1.1");
assert.equal(parsed.launcher.releases.nightly.prerelease, true);
assert.equal(parsed.apps.length, 2);
const photo = parsed.apps[0];
assert.equal(photo.id, "photocraft");
assert.equal(photo.releases.stable.tag, "v0.23.1");
assert.equal(photo.releases.stable.assets.length, 3);
assert.equal(photo.releases.stable.assets[0].sha256, HASH_A);
// The checksum document is listed too, hashed over the exact bytes that were fetched.
const sums = photo.releases.stable.assets.find((a) => a.name === "SHA256SUMS.txt");
assert.equal(
sums.download_url,
"https://github.com/storytold/photocraft/releases/download/v0.23.1/SHA256SUMS.txt",
);
assert.equal(
sums.sha256,
createHash("sha256").update(`${HASH_A} photocraft-0.23.1-macos-universal.dmg\n${HASH_B} photocraft-0.23.1-windows-x64.msi\n`).digest("hex"),
);
assert.equal(photo.releases.prerelease.tag, "v0.24.0-rc.1");
assert.equal(photo.releases.nightly.tag, "v0.24.0-nightly.20261126.5.1");
// Community app with missing SHA256SUMS.txt still emits channel metadata without failing the build.
const solid = parsed.apps[1];
assert.equal(solid.id, "solidcraft");
assert.equal(solid.releases.stable.tag, "v0.3.0");
assert.equal(solid.releases.stable.assets, undefined);
// Signing the generated catalog produces a valid Ed25519 detached signature over the final bytes.
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const env = {
LAUNCHER_CATALOG_SIGNING_KEY: Buffer.from(privateKey.export({ type: "pkcs8", format: "pem" })).toString("base64"),
};
signLauncherCatalog(dir, env);
const finalBytes = readFileSync(outCatalogPath);
const sig = Buffer.from(readFileSync(join(dir, "launcher-catalog.toml.sig"), "utf8").trim(), "base64");
assert.equal(sig.length, 64);
assert.equal(verify(null, finalBytes, publicKey, sig), true);
});
test("enrichLauncherCatalog rejects outputs larger than MAX_CATALOG_BYTES", () => {
const hugeAssets = Array.from({ length: 6000 }, (_, i) => ({
name: `photocraft-0.23.1-asset-${i}.tar.gz`,
download_url: `https://github.com/storytold/photocraft/releases/download/v0.23.1/photocraft-0.23.1-asset-${i}.tar.gz`,
sha256: HASH_A,
}));
assert.throws(
() =>
enrichLauncherCatalog(BASE_TOML, {
generatedAt: "2026-11-26T21:30:00.000Z",
launcherReleases: {},
appReleasesById: {
photocraft: {
stable: {
tag: "v0.23.1",
version: "0.23.1",
html_url: "https://github.com/storytold/photocraft/releases/tag/v0.23.1",
prerelease: false,
assets: hugeAssets,
},
},
},
}),
/MAX_CATALOG_BYTES/,
);
});
@@ -274,3 +274,28 @@ export type CraftNightlyRelease = {
export const CRAFT_NIGHTLY_RELEASES: Partial<
Record<CraftAppSlug | "artcraft-launcher" | "artcraft", CraftNightlyRelease>
> = {};
export type CraftChannelRelease = {
/** Exact GitHub release tag (e.g. "v0.24.0-rc.1" or "v0.23.1"). */
tag: string;
/** Version without the leading "v" (e.g. "0.24.0-rc.1" or "0.23.1"). */
version: string;
};
// Highest-version non-nightly beta/RC prerelease per repository, updated automatically by
// `.github/workflows/update-craft-release-versions.yml`.
export const CRAFT_PRERELEASE_RELEASES: Partial<
Record<CraftAppSlug | "artcraft-launcher", CraftChannelRelease>
> = {};
export type CraftCommunityAppReleases = {
/** GitHub repository (`owner/repo`), matching `public/launcher-catalog.toml`. */
repo: string;
stable?: CraftChannelRelease;
prerelease?: CraftChannelRelease;
nightly?: CraftChannelRelease;
};
// Community apps listed in `public/launcher-catalog.toml`, updated automatically by
// `.github/workflows/update-craft-release-versions.yml`.
export const CRAFT_COMMUNITY_RELEASES: Record<string, CraftCommunityAppReleases> = {};