From 5a774a9bce0ca7eae2e6a49e5b4dadaefbe4b71d Mon Sep 17 00:00:00 2001 From: sunnylqm Date: Wed, 14 Oct 2026 14:16:47 +0800 Subject: [PATCH] fix(js): resolve gray rollouts in client.checkUpdate and switch to the downloaded version - client.checkUpdate now returns the result resolved for this device (gray rollout bucket, running version), as the provider already presented it. Before, only the provider resolved it: a direct client.checkUpdate() -> downloadUpdate() ignored the rollout percentage and installed the root release, and afterCheckUpdate saw the unresolved response. The provider no longer resolves a second time. - useUpdate().switchVersion() / switchVersionLater() without an argument target the downloaded version (the only one the client accepts), falling back to the last checked info only before any download. A check that found a newer release after the download used to turn "switch now" into a silent no-op. The provider reads it through client.getDownloadedHash() instead of the client module's sharedState. - The unknown-bundle warning names the brand's own CLI (cresc for Cresc). Co-Authored-By: Claude Opus 5.5 --- src/__tests__/client.test.ts | 47 ++++++++++++++++++++ src/__tests__/provider.contract.test.tsx | 56 +++++++++++++++++++++++- src/client.ts | 41 ++++++++++++++--- src/locales/en.ts | 2 +- src/locales/zh.ts | 2 +- src/provider.tsx | 52 +++++++++++++--------- 6 files changed, 171 insertions(+), 29 deletions(-) diff --git a/src/__tests__/client.test.ts b/src/__tests__/client.test.ts index 8e232e23..52760522 100644 --- a/src/__tests__/client.test.ts +++ b/src/__tests__/client.test.ts @@ -207,6 +207,53 @@ describe('Pushy server config', () => { }); }); + test('resolves the gray rollout for direct checkUpdate callers', async () => { + setupClientMocks(); + const afterCheckUpdate = mock(() => {}); + const { client } = await createClient({ afterCheckUpdate }); + const rootFor = (rollout: number) => ({ + update: true as const, + name: 'root', + hash: 'root-hash', + full: 'root.ppk', + paths: ['https://cdn.example.com'], + expVersion: { + name: 'gray', + hash: 'gray-hash', + full: 'gray.ppk', + config: { + rollout: { [client.getEffectivePackageVersion()]: rollout }, + }, + }, + }); + + // Every device is in a 100% rollout: the candidate replaces the root + // release (keeping the root's CDN paths), and expVersion is gone. + (globalThis as any).fetch = mock(async () => + createJsonResponse(rootFor(100)) + ); + const inRollout = await client.checkUpdate({ round: 1 }); + expect(inRollout).toMatchObject({ + update: true, + name: 'gray', + hash: 'gray-hash', + paths: ['https://cdn.example.com'], + }); + expect(inRollout).not.toHaveProperty('expVersion'); + expect(afterCheckUpdate).toHaveBeenLastCalledWith({ + status: 'completed', + result: inRollout, + }); + + // No device is in a 0% rollout: the root release applies. + (globalThis as any).fetch = mock(async () => + createJsonResponse(rootFor(0)) + ); + const outOfRollout = await client.checkUpdate({ round: 2 }); + expect(outOfRollout).toMatchObject({ update: true, hash: 'root-hash' }); + expect(outOfRollout).not.toHaveProperty('expVersion'); + }); + test('reports the native diff track version as diffV in the check body', async () => { setupClientMocks({ supportedDiffVersion: 2 }); const fetchMock = mock(async () => createJsonResponse({ update: false })); diff --git a/src/__tests__/provider.contract.test.tsx b/src/__tests__/provider.contract.test.tsx index 0556713a..88a271d8 100644 --- a/src/__tests__/provider.contract.test.tsx +++ b/src/__tests__/provider.contract.test.tsx @@ -32,13 +32,17 @@ let importSeq = 0; // dedup window. const setupRealClient = async ( options: Record = {}, - native: { markSuccess?: ReturnType; isFirstTime?: boolean } = {} + native: { + markSuccess?: ReturnType; + setNeedUpdate?: ReturnType; + isFirstTime?: boolean; + } = {} ) => { mockCore({ PushyModule: { markSuccess: native.markSuccess ?? mock(() => Promise.resolve()), reloadUpdate: mock(() => Promise.resolve()), - setNeedUpdate: mock(() => Promise.resolve()), + setNeedUpdate: native.setNeedUpdate ?? mock(() => Promise.resolve()), downloadPatchFromPpk: mock(() => Promise.resolve()), downloadPatchFromPackage: mock(() => Promise.resolve()), downloadFullUpdate: mock(() => Promise.resolve()), @@ -183,6 +187,54 @@ describe('UpdateProvider <-> Pushy contract', () => { expect(checkUpdate).toHaveBeenCalledTimes(1); }); + test('switching without an explicit version targets the downloaded one', async () => { + const setNeedUpdate = mock(() => Promise.resolve()); + const { client, UpdateProvider } = await setupRealClient( + { checkStrategy: null, updateStrategy: null }, + { setNeedUpdate } + ); + const captured: { current?: any } = {}; + const Probe = () => { + captured.current = useUpdate(); + return null; + }; + await renderProvider(UpdateProvider, client, ); + const release = (hash: string) => ({ + update: true, + name: hash, + hash, + full: `${hash}.ppk`, + paths: ['https://cdn.example.com'], + }); + + (globalThis as any).fetch = mock(async () => + createJsonResponse(release('hash-a')) + ); + await TestRenderer.act(async () => { + await captured.current.checkUpdate(); + await captured.current.downloadUpdate(); + await flush(); + }); + expect(client.getDownloadedHash()).toBe('hash-a'); + + // A later check finds a newer release before the user switches; the + // context's update info moves on to it, but only hash-a is on disk. + client.lastChecking = 0; + (globalThis as any).fetch = mock(async () => + createJsonResponse(release('hash-b')) + ); + await TestRenderer.act(async () => { + await captured.current.checkUpdate(); + await flush(); + }); + expect(captured.current.updateInfo.hash).toBe('hash-b'); + + await TestRenderer.act(async () => { + await captured.current.switchVersionLater(); + }); + expect(setNeedUpdate).toHaveBeenCalledWith({ hash: 'hash-a' }); + }); + test('changing dismissErrorAfter reschedules a running dismiss timer', async () => { (globalThis as any).fetch = mock(async () => { throw new Error('offline'); diff --git a/src/client.ts b/src/client.ts index f378af4b..53882c14 100644 --- a/src/client.ts +++ b/src/client.ts @@ -55,6 +55,7 @@ import { isValidCheckResult, jsonDeepEqual, nativeConfigsEquivalent, + resolveCheckResult, } from './updateFlowCore'; import { assertWeb, @@ -1067,6 +1068,9 @@ export class Pushy { * was requested, false when the call was ignored (not the downloaded hash, * a switch already in progress, beforeReload declined, dev without debug). */ + /** The downloaded version switchVersion(Later) accepts; undefined before a download. */ + getDownloadedHash = (): string | undefined => sharedState.downloadedHash; + switchVersion = async (hash: string): Promise => { if (!this.assertDebug('switchVersion()')) { return false; @@ -1139,6 +1143,27 @@ export class Pushy { } } }; + /** + * The server answers with the root release plus, during a gray rollout, the + * candidate `expVersion`. Which of the two applies is decided per device + * (rollout bucket of this uuid, the running version): every caller of + * checkUpdate gets that decision, not only the provider — a direct + * `client.checkUpdate()` → `downloadUpdate()` would otherwise ignore the + * rollout and install the root release. Idempotent. + */ + private resolveForThisDevice = (result: CheckResult): CheckResult => + result + ? resolveCheckResult( + result, + { + packageVersion: this.getEffectivePackageVersion(), + currentVersion, + uuid: cInfo.uuid, + }, + log + ) + : result; + checkUpdate = async (extra?: Record) => { if (!this.assertDebug('checkUpdate()')) { this.notifyAfterCheckUpdate({ status: 'skipped' }); @@ -1190,7 +1215,7 @@ export class Pushy { now - this.lastChecking < 1000 * 5 ) { try { - const result = await this.lastRespJson; + const result = this.resolveForThisDevice(await this.lastRespJson); this.notifyAfterCheckUpdate({ status: 'completed', result }); return result; } catch (e: any) { @@ -1238,20 +1263,26 @@ export class Pushy { return cached ?? (await this.fetchCheckResult(fetchPayload)); })(); this.lastRespJson = respJsonPromise; - const result: CheckResult = await respJsonPromise; + const rootResult: CheckResult = await respJsonPromise; - log('checking result:', result); + log('checking result:', rootResult); - if (result?.bundleStatus === 'unknownBundle') { + if (rootResult?.bundleStatus === 'unknownBundle') { // 服务端判定当前二进制内嵌 bundle 未注册,增量已被降级为全量。只面向 // 开发者(日志 + 遥测,控制台聚合是主渠道);终端用户无感知。 - warn(this.t('warn_unknown_bundle')); + warn( + this.t('warn_unknown_bundle', { + // Each brand ships its own CLI binary (react-native-update-cli). + cli: this.clientType === 'Cresc' ? 'cresc' : 'pushy', + }) + ); this.report({ type: 'bundleMismatch', data: bundleHash ? { bundleHash } : {}, }); } + const result = this.resolveForThisDevice(rootResult); this.notifyAfterCheckUpdate({ status: 'completed', result }); this.markJsCheckCompleted(); return result; diff --git a/src/locales/en.ts b/src/locales/en.ts index 78dc3663..5d9d7b86 100644 --- a/src/locales/en.ts +++ b/src/locales/en.ts @@ -25,7 +25,7 @@ export default { 'A second UpdateProvider was mounted: make sure the app renders exactly one UpdateProvider', error_parse_version_info: 'Failed to parse currentVersionInfo: {{info}}', warn_unknown_bundle: - 'The bundle embedded in this binary is not registered on the update platform; incremental updates are degraded to full downloads. Upload the package with pushy uploadIpa / uploadApk / uploadApp.', + 'The bundle embedded in this binary is not registered on the update platform; incremental updates are degraded to full downloads. Upload the package with {{cli}} uploadIpa / uploadApk / uploadApp.', error_update_check_failed: 'Update check failed', error_cannot_connect_server: 'Can not connect to update server. Please check your network.', diff --git a/src/locales/zh.ts b/src/locales/zh.ts index de24b441..871e646f 100644 --- a/src/locales/zh.ts +++ b/src/locales/zh.ts @@ -23,7 +23,7 @@ export default { '检测到同时挂载多个 UpdateProvider:请确保应用中只有一个 UpdateProvider', error_parse_version_info: '解析 currentVersionInfo 失败: {{info}}', warn_unknown_bundle: - '当前二进制内嵌 bundle 未在更新平台注册,增量更新已降级为全量。请使用 pushy uploadIpa / uploadApk / uploadApp 上传对应安装包。', + '当前二进制内嵌 bundle 未在更新平台注册,增量更新已降级为全量。请使用 {{cli}} uploadIpa / uploadApk / uploadApp 上传对应安装包。', error_update_check_failed: '更新检查失败', error_cannot_connect_server: '无法连接到更新服务器。请检查网络连接。', error_cannot_connect_backup: diff --git a/src/provider.tsx b/src/provider.tsx index 6c8b7d49..54f9a152 100644 --- a/src/provider.tsx +++ b/src/provider.tsx @@ -11,7 +11,6 @@ import { Alert, AppState, Linking, Platform } from 'react-native'; import { type Cresc, type Pushy, sharedState } from './client'; import { ProgressContext, UpdateContext } from './context'; import { - cInfo, currentVersion, currentVersionInfo, getCurrentVersionInfo, @@ -19,18 +18,28 @@ import { rolledBackVersion, } from './core'; import type { CheckResult, ProgressData, UpdateTestPayload } from './type'; -import { decideDownload, resolveCheckResult } from './updateFlowCore'; +import { decideDownload } from './updateFlowCore'; import { assertWeb, isWeb, log, noop, parseQueryParams } from './utils'; -// A context action applied to the hash of the given (default: the last -// checked) update info; a no-op without one. +// A switch action applied to the hash of the given update info; a no-op +// without one. Called without info it targets the downloaded version — the +// only one client.switchVersion(Later) accepts — and only falls back to the +// last checked info before anything was downloaded. Defaulting to the last +// checked info alone made a check that found a newer release after the +// download (updateInfo moved on) turn "switch now" into a silent no-op. const forUpdateHash = ( updateInfoRef: { current?: CheckResult }, + getDownloadedHash: () => string | undefined, apply: (hash: string) => Promise ) => - async (info: CheckResult | undefined = updateInfoRef.current) => - info?.hash ? apply(info.hash) : undefined; + async (info?: CheckResult) => { + const hash = + info !== undefined + ? info.hash + : getDownloadedHash() || updateInfoRef.current?.hash; + return hash ? apply(hash) : undefined; + }; export const UpdateProvider = ({ client, @@ -111,12 +120,22 @@ export const UpdateProvider = ({ ); const switchVersion = useMemo( - () => forUpdateHash(updateInfoRef, client.switchVersion), + () => + forUpdateHash( + updateInfoRef, + client.getDownloadedHash, + client.switchVersion + ), [client] ); const switchVersionLater = useMemo( - () => forUpdateHash(updateInfoRef, client.switchVersionLater), + () => + forUpdateHash( + updateInfoRef, + client.getDownloadedHash, + client.switchVersionLater + ), [client] ); @@ -225,27 +244,20 @@ export const UpdateProvider = ({ // No throttle here: the client already dedupes checks via its 5s // response cache, and a second throttle layer silently returned // undefined, indistinguishable from a failed check. - let rootInfo: CheckResult | undefined; + // Already resolved for this device (gray rollout, running version) by + // the client. + let info: CheckResult | undefined; try { - rootInfo = await client.checkUpdate(extra); + info = await client.checkUpdate(extra); } catch (e: any) { surfaceCaughtError(e, client.t('error_update_check_failed')); return; } - if (!rootInfo) { + if (!info) { // Check was skipped or failed with no cached result; keep the last // known updateInfo instead of overwriting it with an empty object. return; } - let info = resolveCheckResult( - rootInfo, - { - packageVersion: client.getEffectivePackageVersion(), - currentVersion, - uuid: cInfo.uuid, - }, - log - ); if ( info.update && (typeof info.hash !== 'string' || info.hash.length === 0)