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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/__tests__/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
Expand Down
56 changes: 54 additions & 2 deletions src/__tests__/provider.contract.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ let importSeq = 0;
// dedup window.
const setupRealClient = async (
options: Record<string, any> = {},
native: { markSuccess?: ReturnType<typeof mock>; isFirstTime?: boolean } = {}
native: {
markSuccess?: ReturnType<typeof mock>;
setNeedUpdate?: ReturnType<typeof mock>;
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()),
Expand Down Expand Up @@ -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, <Probe />);
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');
Expand Down
41 changes: 36 additions & 5 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
isValidCheckResult,
jsonDeepEqual,
nativeConfigsEquivalent,
resolveCheckResult,
} from './updateFlowCore';
import {
assertWeb,
Expand Down Expand Up @@ -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<boolean> => {
if (!this.assertDebug('switchVersion()')) {
return false;
Expand Down Expand Up @@ -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<string, any>) => {
if (!this.assertDebug('checkUpdate()')) {
this.notifyAfterCheckUpdate({ status: 'skipped' });
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
52 changes: 32 additions & 20 deletions src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,35 @@ 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,
packageVersion,
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 =
<T,>(
updateInfoRef: { current?: CheckResult },
getDownloadedHash: () => string | undefined,
apply: (hash: string) => Promise<T>
) =>
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,
Expand Down Expand Up @@ -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]
);

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