feature/ota-updates #138

Merged
EgorEast merged 25 commits from feature/ota-updates into main 2026-10-25 11:32:05 +00:00
Owner

Self-hosted OTA-обновления (expo-updates + xprem) и умный релизный конвейер

Что это

Приложение получает тихие фоновые JS-обновления с собственного сервера (xprem, протокол Expo Updates v1): проверка при старте, скачивание в фоне, применение при следующем запуске — без диалогов и установки APK. Существующий путь самообновления через APK (Forgejo releases + PackageInstaller) сохранён для нативных изменений.

Режимы релизов (release.yml, job changes)

Изменения Что происходит
Нативные (android/, ios/, plugins/, modules/, yarn.lock, app.config.ts, ota.config.ts) APK + Forgejo-релиз с ассетами + web
Только JS/TS Web + публикация OTA. Релиз не создаётся
Любые Web деплоится всегда

Детекция — content-aware (version-строки build.gradle/pbxproj от bump-скрипта не считаются нативным churn), вынесена в общий скрипт scripts/ci/detect-native-changes.sh. Два guard'а: натив изменён без бампа RUNTIME_VERSION → падение; RUNTIME_VERSION изменён без натива → падение (OTA «в пустоту»).

В приложении

  • ota.config.ts — конфиг OTA полностью из env (EXPO_PUBLIC_OTA_URL, EXPO_PUBLIC_XPREM_APP_ID, EXPO_PUBLIC_XPREM_CHANNEL_NAME, EXPO_PUBLIC_XPREM_BRANCH_NAME); все четыре заданы → OTA включён, хоть одна нет → updates.enabled: false (сборки без env — в т.ч. будущие F-Droid — не самообновляются by design)
  • RUNTIME_VERSION управляется автоматически: bump-version определяет режим (натив/JS по контенту диффа, включая незатреканные файлы) и на нативных релизах поднимает литерал до новой версии приложения; CI-guard'ы страхуют ручное тегирование
  • expo-updates возвращён (~58.0.18), autolinking-exclude снят, манифест-плагин больше не вычищает expo.modules.updates.*, android/ перегенерирован
  • Гейт диалога: если для текущего runtime есть OTA — APK-диалог и push не показываются вовсе
  • Code signing включается автоматически при наличии certs/xprem-certificate.pem (сертификат добавлен, ключ остаётся на сервере)

Новые ручные воркфлоу

  • ota-publish.yml — хотфикс без тега/релиза: web-деплой + публикация OTA; js-only верификация (натив/дрейф runtime → падение с требованием полноценного релиза); полный step-summary
  • xprem-cleanup.yml — очистка устаревших OTA-бандлов после нативного релиза: удаляет ветку в xprem и переиздаёт текущий бандл; deep-режим дополнительно чистит CAS-пул через SSH

Требования (уже настроены)

  • Сервер xprem развёрнут плейбуком (ota.slovo-propovedi.ru, роль slovo-xprem)
  • Forgejo org vars: EXPO_PUBLIC_* (4 шт.); secrets: XPREM_EOO_TOKEN, XPREM_ADMIN_EMAIL, XPREM_ADMIN_PASSWORD

Верификация

  • yarn lint / check:types / check:fsd / check:unused / check:circular — чисто
  • 2322 теста проходят; expo prebuild --clean + gradle-сборка успешны
  • Детекция режимов проверена на реальной истории тегов; bash -n / симуляции всех shell-шагов воркфлоу
  • Логика гейта и парсинга манифеста покрыта тестами (updateOtaGate — 20, updateOtaStatus — 5)

После мержа

  1. Обычный bump-релиз (первый после слияния будет нативным — соберётся APK с включённым OTA)
  2. Затем JS-only релиз и ручной ota-publish — обкатать и закрыть debt-запись про необкатанную механику

Debt (осознанный)

  • F-Droid: при появлении канала — kill-switch OTA для их сборок (запись в docs/debt.md)
  • Новая CI-механика (changes, ota, ota-publish, xprem-cleanup) ещё не прогонялась на живом Forgejo
## Self-hosted OTA-обновления (expo-updates + xprem) и умный релизный конвейер ### Что это Приложение получает **тихие фоновые JS-обновления** с собственного сервера (xprem, протокол Expo Updates v1): проверка при старте, скачивание в фоне, применение при следующем запуске — без диалогов и установки APK. Существующий путь самообновления через APK (Forgejo releases + PackageInstaller) сохранён для нативных изменений. ### Режимы релизов (release.yml, job `changes`) | Изменения | Что происходит | |---|---| | Нативные (android/, ios/, plugins/, modules/, yarn.lock, app.config.ts, ota.config.ts) | APK + Forgejo-релиз с ассетами + web | | Только JS/TS | Web + публикация OTA. **Релиз не создаётся** | | Любые | Web деплоится всегда | Детекция — content-aware (version-строки `build.gradle`/`pbxproj` от bump-скрипта не считаются нативным churn), вынесена в общий скрипт `scripts/ci/detect-native-changes.sh`. Два guard'а: натив изменён без бампа `RUNTIME_VERSION` → падение; `RUNTIME_VERSION` изменён без натива → падение (OTA «в пустоту»). ### В приложении - `ota.config.ts` — конфиг OTA **полностью из env** (`EXPO_PUBLIC_OTA_URL`, `EXPO_PUBLIC_XPREM_APP_ID`, `EXPO_PUBLIC_XPREM_CHANNEL_NAME`, `EXPO_PUBLIC_XPREM_BRANCH_NAME`); все четыре заданы → OTA включён, хоть одна нет → `updates.enabled: false` (сборки без env — в т.ч. будущие F-Droid — не самообновляются by design) - `RUNTIME_VERSION` управляется автоматически: `bump-version` определяет режим (натив/JS по контенту диффа, включая незатреканные файлы) и на нативных релизах поднимает литерал до новой версии приложения; CI-guard'ы страхуют ручное тегирование - `expo-updates` возвращён (`~58.0.18`), autolinking-exclude снят, манифест-плагин больше не вычищает `expo.modules.updates.*`, `android/` перегенерирован - Гейт диалога: если для текущего runtime есть OTA — APK-диалог и push не показываются вовсе - Code signing включается автоматически при наличии `certs/xprem-certificate.pem` (сертификат добавлен, ключ остаётся на сервере) ### Новые ручные воркфлоу - **`ota-publish.yml`** — хотфикс без тега/релиза: web-деплой + публикация OTA; js-only верификация (натив/дрейф runtime → падение с требованием полноценного релиза); полный step-summary - **`xprem-cleanup.yml`** — очистка устаревших OTA-бандлов после нативного релиза: удаляет ветку в xprem и переиздаёт текущий бандл; `deep`-режим дополнительно чистит CAS-пул через SSH ### Требования (уже настроены) - Сервер xprem развёрнут плейбуком (`ota.slovo-propovedi.ru`, роль `slovo-xprem`) - Forgejo org vars: `EXPO_PUBLIC_*` (4 шт.); secrets: `XPREM_EOO_TOKEN`, `XPREM_ADMIN_EMAIL`, `XPREM_ADMIN_PASSWORD` ### Верификация - `yarn lint` / `check:types` / `check:fsd` / `check:unused` / `check:circular` — чисто - 2322 теста проходят; `expo prebuild --clean` + gradle-сборка успешны - Детекция режимов проверена на реальной истории тегов; `bash -n` / симуляции всех shell-шагов воркфлоу - Логика гейта и парсинга манифеста покрыта тестами (updateOtaGate — 20, updateOtaStatus — 5) ### После мержа 1. Обычный bump-релиз (первый после слияния будет нативным — соберётся APK с включённым OTA) 2. Затем JS-only релиз и ручной `ota-publish` — обкатать и закрыть debt-запись про необкатанную механику ### Debt (осознанный) - F-Droid: при появлении канала — kill-switch OTA для их сборок (запись в `docs/debt.md`) - Новая CI-механика (`changes`, `ota`, `ota-publish`, `xprem-cleanup`) ещё не прогонялась на живом Forgejo
Two update channels: expo-updates silently delivers JS/assets bundles from our
own xprem server (Expo Updates protocol v1), applied on the next cold start; the
APK release (Forgejo + in-app PackageInstaller) stays the only channel for
native changes.

- re-enable expo-updates (dependency + autolinking); its manifest meta-data is
  no longer stripped by withAndroidManifestCleanup
- ota.config.ts: fixed-literal runtimeVersion, updates block (ON_LOAD,
  fallbackToCacheTimeout 0), xprem request headers, conditional code signing
- updateOtaGate.ts: effective running version (embedded launch -> APP_VERSION,
  OTA launch -> manifest extra.expoClient.version), so the APK dialog and the
  push notification skip releases already shipped as an OTA bundle
- expo-updates is imported dynamically inside the native-only branch, web never
  evaluates it
- release.yml: non-fatal eoas publish step, skipped without XPREM_EOO_TOKEN
- docs: updates/decisions/debt (xprem bootstrap placeholders, F-Droid)

Bootstrap placeholders: XPREM_APP_ID and certs/xprem-certificate.pem are filled
after the xprem dashboard bootstrap; android/ needs a prebuild.

Signed-off-by: egoreast <egor.east@yandex.ru>
Deployment values (manifest URL, xprem app id, channel, branch) now come
only from EXPO_PUBLIC_OTA_URL / EXPO_PUBLIC_XPREM_APP_ID /
EXPO_PUBLIC_XPREM_CHANNEL_NAME / EXPO_PUBLIC_XPREM_BRANCH_NAME instead of
hardcoded literals in ota.config.ts.

The contract is all-or-nothing: with all four set, app.config gets the full
updates block; if any is missing or empty, the build gets
`updates: { enabled: false }` and never self-updates. That keeps builds
without deployment env (future F-Droid buildbot, arbitrary local builds)
away from the production OTA channel.

release.yml passes the four values from Forgejo org vars into the APK
prebuild/build and the eoas publish step (which runs expo export and would
otherwise emit a bundle with updates disabled), and skips publishing with a
warning naming any missing value. runtimeVersion stays a deliberate literal:
it is versioning, not deployment config.

Signed-off-by: egoreast <egor.east@yandex.ru>
Signed-off-by: egoreast <egor.east@yandex.ru>
The expo-router plugin reuses expo's config patterns, so it still loaded
app.config.ts and failed on EXPO_PUBLIC_* validation (knip never loads .env).
Override its config list the same way the expo plugin already does.

Signed-off-by: egoreast <egor.east@yandex.ru>
Signed-off-by: egoreast <egor.east@yandex.ru>
- .env.example: EXPO_PUBLIC_OTA_URL is the xprem server base URL, not the
  manifest endpoint — expo-updates appends /manifest itself.
- docs/features/updates.md: env contract table states the base-URL shape;
  EAS_NO_VCS=1 described as always set (the job dirties tracked files);
  explicit release-checklist bullet for RUNTIME_VERSION bumps.
- ota.config.ts: comment warns that a /manifest or /api suffix breaks the
  device protocol.
- .forgejo/workflows/release.yml: set EAS_NO_VCS=1 in the OTA publish step,
  because the release job sed-patches android/gradle.properties and re-runs
  prebuild before publishing (eoas aborts on a dirty tree otherwise).
- docs/debt.md: open entries for the missing RUNTIME_VERSION reminder and for
  keeping eoas pinned in sync with slovo_xprem_version in the playbook repo.
- updateOtaGate.test.ts: cover extra.expoClient === null and array `extra`,
  asserting the gate falls back to the baked app version.

Signed-off-by: egoreast <egor.east@yandex.ru>
Enables the codeSigningCertificate branch in ota.config.ts; private key stays server-side in xprem.

Signed-off-by: egoreast <egor.east@yandex.ru>
The release workflow now decides its mode from the diff against the previous
tag: native paths (android/, ios/, plugins/, modules/, package.json,
yarn.lock, app.config.ts, ota.config.ts) build and publish the APK, JS-only
changes publish the OTA bundle to xprem and cut a notes-only Forgejo release,
and web is released on every tag regardless of mode.

The new changes job also fails the pipeline when native paths changed but
RUNTIME_VERSION in ota.config.ts was not bumped, replacing the manual
checklist discipline. create-release depends on changes, so a failed guard
blocks the whole release. The OTA publish step moves out of the android job
into its own ota job that installs dependencies itself.

Signed-off-by: egoreast <egor.east@yandex.ru>
When a newer release is detected, checkForUpdateAction now asks expo-updates
(checkForUpdateAsync) whether a bundle exists for the current runtimeVersion.
If it does, both the APK dialog and the push notification are skipped: the OTA
applies silently on the next cold start, after which the running version
matches the release and the gate stays quiet. A failed check counts as "no
OTA" and keeps the dialog as the safe fallback.

The decision lives in a pure decideUpdatePrompt helper in updateOtaGate; the
expo-updates readers move to the internal updateOtaStatus module so the
checkForUpdateAction file stays under the line limit.

Signed-off-by: egoreast <egor.east@yandex.ru>
updates.md now describes the native / js-only / web release modes, the CI
guard that enforces a RUNTIME_VERSION bump for native diffs (forgetting is a
red pipeline, not silent breakage), and the rule that the APK dialog appears
only when no OTA path exists for the running runtimeVersion.

debt.md drops the RUNTIME_VERSION reminder entry, now enforced by the
release workflow guard.

Signed-off-by: egoreast <egor.east@yandex.ru>
bump-version.mjs rewrites package.json, gradle versionName/versionCode and
the pbxproj MARKETING_VERSION/CURRENT_PROJECT_VERSION on every release, so
the name-only native filter always matched and the ota job was dead code.

- drop package.json from the name-only filter (yarn.lock covers deps)
- judge android/app/build.gradle and ios/**/*.pbxproj by diff content: only
  +/- lines beyond version metadata count as native churn
- keep the name-only check for every other native path
- anchor the RUNTIME_VERSION sed to the declaration line

Signed-off-by: egoreast <egor.east@yandex.ru>
JS-only releases now always carry the web export zip, so the previous
'first .zip asset' heuristic would hand the PWA bundle to the APK update
flow. Match the APK archive by the landing repo's anchored pattern
(^slovo-propovedi-v[0-9][^/]*\.zip$) instead: the web zip has a '-web'
infix, so a digit right after 'v' excludes it.

Signed-off-by: egoreast <egor.east@yandex.ru>
- Create Forgejo Release: 409 / 'already exists' body is now a warning
  instead of a hard failure, so a full pipeline re-run survives; genuine
  HTTP errors stay fatal
- ota job: add the same yarn cache steps the web/android jobs use before
  the eoas publish installs dependencies

Signed-off-by: egoreast <egor.east@yandex.ru>
Extract the lazy expo-updates import into loadExpoUpdates so the fail-open
paths can be tested: Jest's CommonJS VM cannot intercept a native dynamic
import() (same limitation documented in notificationsHelpers.test.ts), so
the test mocks the loader seam instead.

Covers: import failure -> APP_VERSION fallback, embedded vs OTA launch
version resolution, checkForUpdateAsync throwing -> false, isAvailable ->
true.

Signed-off-by: egoreast <egor.east@yandex.ru>
release.yml is now five jobs (changes, create-release, web, android, ota),
not three. Flag that the new machinery — the changes job's git plumbing
(previous-tag resolution, content-aware native detection, RUNTIME_VERSION
reads) and the eoas publish path — has not run on a real release yet.

Signed-off-by: egoreast <egor.east@yandex.ru>
New workflow_dispatch workflow .forgejo/workflows/ota-publish.yml
("Publish OTA update (manual)") — the release.yml `ota` job behind a
manual trigger, so a hotfix can reach installed builds without cutting a
version or a tag. Normal js-only releases keep publishing OTA
automatically from release.yml.

Shape mirrors the ota job: ubuntu-24.04 + memory-heavy-jobs concurrency,
setup-node 24 + corepack + yarn cache, a guard step that warns and exits
0 when XPREM_EOO_TOKEN or any of the four EXPO_PUBLIC_XPREM_* vars is
missing (install and publish are gated on its `ready` output), then
`yarn install --frozen-lockfile` and `eoas publish --platform android`.
A failed publish stays non-fatal (`:⚠️:`), same semantics as the
release job; xprem dedupes identical content, so a re-run is harmless.

Docs: updates.md documents the manual path; debt.md records that the
eoas pin is now duplicated across two workflows and that the new
workflow has not run on Forgejo yet; decisions.md workflow list updated.

Signed-off-by: egoreast <egor.east@yandex.ru>
JS-only tags now deploy the web PWA and publish the OTA bundle only: no
Forgejo release object is created, so a release always means a new APK is
available on the landing. Native releases are unchanged. The manual
ota-publish workflow also deploys web (hotfix = new web version + new OTA
bundle, no release, no APK).

The eoas pin moves to a single .eoas-version file read by both workflows;
Renovate bumps it via a regex custom manager, so the pin-sync debt entry is
removed. Web assets are attached only in native mode, and the web job polls
for the release object since it no longer waits for create-release.

Signed-off-by: egoreast <egor.east@yandex.ru>
The manual OTA publish now renders one self-explanatory job summary for the
whole run instead of a couple of loose rows. The guard step writes the header
(branch, short commit SHA, UTC date, platform) plus the OTA config row; the
publish step appends its published/failed row and exports `result`; the web
path appends its vars/export/deploy rows; an always() footer reads the step
outputs and turns them into a verdict: 🎉 fully published, ⚠️ skipped or
non-fatal parts, ❌ the web path broke.

Fatal semantics are unchanged (OTA stays `:⚠️:` + exit 0, web failures
still fail the run) — the export and deploy steps now only add a `⚠️ failed`
row before exiting 1. Summary writes are wrapped in `|| true`, so an unset or
unwritable $GITHUB_STEP_SUMMARY never fails the workflow, and a step skipped
by `if:` appends nothing: the footer reports it as skipped, never as success.

Signed-off-by: egoreast <egor.east@yandex.ru>
Move the content-aware native-vs-JS detection out of release.yml into
scripts/ci/detect-native-changes.sh, so the release and manual OTA workflows
share one implementation. The script prints native/rv_prev/rv_now key=value
lines, treats an empty PREV_REF as the first-release case (native) and reads
RUNTIME_VERSION at both refs (empty pre-OTA history). release.yml calls it and
keeps the same job outputs; a new mirror guard blocks a RUNTIME_VERSION bump on
a JS-only diff.

Signed-off-by: egoreast <egor.east@yandex.ru>
The manual publish workflow now verifies the selected ref is JS-only before
installing or publishing: it diffs HEAD against the latest release tag with the
shared detect-native-changes.sh and fails when native paths changed or when
RUNTIME_VERSION drifted from that tag. Checkout fetches full history and tags
for the comparison; the run summary gains a Verification row and the footer
reports a blocked verification as a failed run.

Signed-off-by: egoreast <egor.east@yandex.ru>
docs: document js-only verification for manual OTA
Some checks failed
CI / dco (pull_request) Successful in 5s
CI / checks (pull_request) Has been cancelled
251ce14a12
Record that a manual OTA run verifies the selected ref is JS-only (native
paths or RUNTIME_VERSION drift fail the run and require a full release) and
that both workflows share scripts/ci/detect-native-changes.sh.

Signed-off-by: egoreast <egor.east@yandex.ru>
ci: add xprem storage purge workflow
All checks were successful
CI / dco (pull_request) Successful in 5s
CI / checks (pull_request) Successful in 12m55s
06e6a709c9
Signed-off-by: egoreast <egor.east@yandex.ru>
Detect native vs js-only changes from the worktree diff against the last
tag (same script CI uses) and update ota.config.ts accordingly: a native
release sets RUNTIME_VERSION to the new app version, a js-only release
keeps it untouched. detect-native-changes.sh gains a single-arg worktree
mode for this.

Signed-off-by: egoreast <egor.east@yandex.ru>
bump-version now decides the release mode itself and updates
RUNTIME_VERSION on native releases; the CI guards remain as a backstop
for tags created without the script.

Signed-off-by: egoreast <egor.east@yandex.ru>
fix: stage untracked files before release-mode detection
All checks were successful
CI / dco (pull_request) Successful in 5s
CI / checks (pull_request) Successful in 8m49s
c02ff3c3b1
bump-version.mjs detected native changes before its git add -A, so untracked
native files (for example a brand-new plugins/*.ts) were invisible to the
worktree diff against the last tag. Such a release was misclassified as
js-only, RUNTIME_VERSION stayed behind, and the CI guard only failed after the
tag had been pushed, forcing tag surgery.

Stage everything before detection so untracked files enter the diff, then
stage a second time after the RUNTIME_VERSION rewrite (and changelog update)
so the edits produced by detection land in the bump commit.

Signed-off-by: egoreast <egor.east@yandex.ru>
Sign in to join this conversation.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Slovo_Propovedi/slovo-propovedi-mobile!138
No description provided.