Split Android build from release publishing (#57714)

Summary:
This should reduce the publishing time needed for `publish_react_native` by parallelizing Android & iOS build

## Changelog:

[INTERNAL] -

Pull Request resolved: https://github.com/react/react-native/pull/57714

Test Plan: N/A

Reviewed By: cipolleschi

Differential Revision: D113889729

Pulled By: cortinico

fbshipit-source-id: aaa66a3cb9ce5c22bf15780503cf9a063c4b2725
This commit is contained in:
Nicola Corti authored and meta-codesync[bot] committed 2026-07-28 14:03:25 -07:00
1 parent e92816c5a5
commit a44d68ec6d
8 files changed
+535 -14

No files matched your search

+6
View File
@@ -14,6 +14,12 @@ Prepares files within the `react-native` package and template for the target rel
Prepares release artifacts and publishes the `react-native` package to npm.
### `cleanup-maven-staging-repositories`
Drops Sonatype staging repositories that exactly match the description in
`ORG_GRADLE_PROJECT_SONATYPE_REPOSITORY_DESCRIPTION`, along with any associated
unpublished Central Portal deployments.
### `publish-updated-packages`
Publishes all updated packages (excluding `react-native`) to npm. Triggered when a commit on a release branch contains `#publish-packages-to-npm`.
@@ -0,0 +1,228 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const {
cleanupMavenStagingRepositories,
createAuthorizationHeader,
} = require('../cleanup-maven-staging-repositories');
const fetchMock = jest.fn();
// $FlowFixMe[cannot-write]
global.fetch = fetchMock;
const API_URL = 'https://sonatype.example/';
const PORTAL_API_URL = 'https://portal.example/';
const CREDENTIALS = {username: 'token-user', password: 'token-password'};
const DESCRIPTION = 'react-native:v0.86.2:github-run-1234';
describe('cleanupMavenStagingRepositories', () => {
beforeEach(() => {
jest.spyOn(console, 'log').mockImplementation(() => {});
jest.resetAllMocks();
});
test('drops matching repositories in every state', async () => {
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
repositories: [
{key: 'matching-1', state: 'open', description: DESCRIPTION},
{key: 'other-run', state: 'open', description: 'another run'},
{key: 'matching-2', state: 'open', description: DESCRIPTION},
{key: 'already-closed', state: 'closed', description: DESCRIPTION},
{
key: 'already-released',
state: 'released',
description: DESCRIPTION,
},
],
}),
});
fetchMock.mockResolvedValue({ok: true});
await expect(
cleanupMavenStagingRepositories(DESCRIPTION, CREDENTIALS, API_URL),
).resolves.toBe(4);
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(
fetchMock.mock.calls.map(([url, options]) => [
url.toString(),
options.method,
]),
).toEqual([
['https://sonatype.example/manual/search/repositories?ip=any', 'GET'],
['https://sonatype.example/manual/drop/repository/matching-1', 'DELETE'],
['https://sonatype.example/manual/drop/repository/matching-2', 'DELETE'],
[
'https://sonatype.example/manual/drop/repository/already-closed',
'DELETE',
],
[
'https://sonatype.example/manual/drop/repository/already-released',
'DELETE',
],
]);
expect(fetchMock.mock.calls[0][1].headers).toEqual({
Authorization: createAuthorizationHeader(CREDENTIALS),
});
});
test('does nothing when no repository matches', async () => {
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({repositories: []}),
});
await expect(
cleanupMavenStagingRepositories(DESCRIPTION, CREDENTIALS, API_URL),
).resolves.toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
test('waits for validation and drops the associated Portal deployment', async () => {
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
repositories: [
{
key: 'closed-repository',
state: 'closed',
description: DESCRIPTION,
portal_deployment_id: 'deployment-1',
},
],
}),
});
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({deploymentState: 'VALIDATING'}),
});
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({deploymentState: 'VALIDATED'}),
});
fetchMock.mockResolvedValue({ok: true});
await expect(
cleanupMavenStagingRepositories(
DESCRIPTION,
CREDENTIALS,
API_URL,
PORTAL_API_URL,
0,
2,
),
).resolves.toBe(1);
expect(
fetchMock.mock.calls.map(([url, options]) => [
url.toString(),
options.method,
]),
).toEqual([
['https://sonatype.example/manual/search/repositories?ip=any', 'GET'],
[
'https://portal.example/api/v1/publisher/status?id=deployment-1',
'POST',
],
[
'https://portal.example/api/v1/publisher/status?id=deployment-1',
'POST',
],
[
'https://portal.example/api/v1/publisher/deployment/deployment-1',
'DELETE',
],
[
'https://sonatype.example/manual/drop/repository/closed-repository',
'DELETE',
],
]);
});
test('keeps an already published Portal deployment', async () => {
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
repositories: [
{
key: 'released-repository',
state: 'released',
description: DESCRIPTION,
portal_deployment_id: 'deployment-2',
},
],
}),
});
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({deploymentState: 'PUBLISHED'}),
});
fetchMock.mockResolvedValueOnce({ok: true});
await expect(
cleanupMavenStagingRepositories(
DESCRIPTION,
CREDENTIALS,
API_URL,
PORTAL_API_URL,
),
).resolves.toBe(1);
expect(
fetchMock.mock.calls.map(([url, options]) => [
url.toString(),
options.method,
]),
).toEqual([
['https://sonatype.example/manual/search/repositories?ip=any', 'GET'],
[
'https://portal.example/api/v1/publisher/status?id=deployment-2',
'POST',
],
[
'https://sonatype.example/manual/drop/repository/released-repository',
'DELETE',
],
]);
});
test('fails when Sonatype returns an error', async () => {
fetchMock.mockResolvedValueOnce({
ok: false,
status: 503,
text: async () => 'temporarily unavailable',
});
await expect(
cleanupMavenStagingRepositories(DESCRIPTION, CREDENTIALS, API_URL),
).rejects.toThrow(
'Sonatype request to /manual/search/repositories failed with HTTP 503: temporarily unavailable',
);
});
test('rejects an invalid search response', async () => {
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
await expect(
cleanupMavenStagingRepositories(DESCRIPTION, CREDENTIALS, API_URL),
).rejects.toThrow(
'Sonatype returned an invalid repository search response.',
);
});
});
@@ -0,0 +1,204 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const DEFAULT_API_URL = 'https://ossrh-staging-api.central.sonatype.com/';
const DEFAULT_PORTAL_API_URL = 'https://central.sonatype.com/';
const DEFAULT_PORTAL_POLL_INTERVAL_MS = 10_000;
const DEFAULT_PORTAL_STATUS_ATTEMPTS = 60;
/*::
type Credentials = {
password: string,
username: string,
};
type StagingRepository = {
description?: ?string,
key: string,
portal_deployment_id?: ?string,
};
*/
function createAuthorizationHeader(
credentials /*: Credentials */,
) /*: string */ {
const token = Buffer.from(
`${credentials.username}:${credentials.password}`,
).toString('base64');
return `Bearer ${token}`;
}
async function request(
url /*: URL */,
credentials /*: Credentials */,
method /*: string */ = 'GET',
) /*: Promise<Response> */ {
const response = await fetch(url, {
method,
headers: {
Authorization: createAuthorizationHeader(credentials),
},
});
if (!response.ok) {
const responseBody = await response.text();
throw new Error(
`Sonatype request to ${url.pathname} failed with HTTP ${response.status}: ${responseBody}`,
);
}
return response;
}
function sleep(milliseconds /*: number */) /*: Promise<void> */ {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
async function cleanupPortalDeployment(
deploymentId /*: string */,
credentials /*: Credentials */,
portalApiUrl /*: string */,
pollIntervalMs /*: number */,
maxStatusAttempts /*: number */,
) /*: Promise<void> */ {
const statusUrl = new URL('api/v1/publisher/status', portalApiUrl);
statusUrl.searchParams.set('id', deploymentId);
let deploymentState /*: string */ = '';
for (let attempt = 1; attempt <= maxStatusAttempts; attempt++) {
const statusResponse = await request(statusUrl, credentials, 'POST');
const statusResult = await statusResponse.json();
deploymentState = statusResult.deploymentState;
if (typeof deploymentState !== 'string') {
throw new Error(
`Sonatype returned an invalid status for Portal deployment ${deploymentId}.`,
);
}
if (deploymentState !== 'PENDING' && deploymentState !== 'VALIDATING') {
break;
}
if (attempt === maxStatusAttempts) {
throw new Error(
`Portal deployment ${deploymentId} remained ${deploymentState} after ${maxStatusAttempts} status checks.`,
);
}
if (pollIntervalMs > 0) {
await sleep(pollIntervalMs);
}
}
if (deploymentState === 'VALIDATED' || deploymentState === 'FAILED') {
const dropUrl = new URL(
`api/v1/publisher/deployment/${encodeURIComponent(deploymentId)}`,
portalApiUrl,
);
await request(dropUrl, credentials, 'DELETE');
console.log(`Dropped Central Portal deployment ${deploymentId}.`);
} else if (
deploymentState === 'PUBLISHING' ||
deploymentState === 'PUBLISHED'
) {
console.log(
`Central Portal deployment ${deploymentId} is already ${deploymentState}; it cannot be dropped.`,
);
} else {
throw new Error(
`Central Portal deployment ${deploymentId} has unsupported state ${deploymentState}.`,
);
}
}
async function cleanupMavenStagingRepositories(
repositoryDescription /*: string */,
credentials /*: Credentials */,
stagingApiUrl /*: string */ = DEFAULT_API_URL,
portalApiUrl /*: string */ = DEFAULT_PORTAL_API_URL,
portalPollIntervalMs /*: number */ = DEFAULT_PORTAL_POLL_INTERVAL_MS,
maxPortalStatusAttempts /*: number */ = DEFAULT_PORTAL_STATUS_ATTEMPTS,
) /*: Promise<number> */ {
if (repositoryDescription === '') {
throw new Error('A Maven staging repository description is required.');
}
const searchUrl = new URL('manual/search/repositories', stagingApiUrl);
searchUrl.searchParams.set('ip', 'any');
const searchResponse = await request(searchUrl, credentials);
const searchResult = await searchResponse.json();
if (!Array.isArray(searchResult.repositories)) {
throw new Error('Sonatype returned an invalid repository search response.');
}
const matchingRepositories /*: Array<StagingRepository> */ =
searchResult.repositories.filter(
repository => repository.description === repositoryDescription,
);
for (const repository of matchingRepositories) {
if (repository.portal_deployment_id != null) {
await cleanupPortalDeployment(
repository.portal_deployment_id,
credentials,
portalApiUrl,
portalPollIntervalMs,
maxPortalStatusAttempts,
);
}
const dropUrl = new URL(
`manual/drop/repository/${encodeURIComponent(repository.key)}`,
stagingApiUrl,
);
await request(dropUrl, credentials, 'DELETE');
console.log(`Dropped Maven staging repository ${repository.key}.`);
}
if (matchingRepositories.length === 0) {
console.log(
`No Maven staging repository matched "${repositoryDescription}".`,
);
}
return matchingRepositories.length;
}
async function main() {
const repositoryDescription =
process.env.ORG_GRADLE_PROJECT_SONATYPE_REPOSITORY_DESCRIPTION;
const username = process.env.ORG_GRADLE_PROJECT_SONATYPE_USERNAME;
const password = process.env.ORG_GRADLE_PROJECT_SONATYPE_PASSWORD;
if (repositoryDescription == null) {
throw new Error(
'ORG_GRADLE_PROJECT_SONATYPE_REPOSITORY_DESCRIPTION is required.',
);
}
if (username == null || password == null) {
throw new Error('Sonatype username and password are required.');
}
await cleanupMavenStagingRepositories(repositoryDescription, {
username,
password,
});
}
if (require.main === module) {
void main();
}
module.exports = {
cleanupPortalDeployment,
cleanupMavenStagingRepositories,
createAuthorizationHeader,
};
@@ -0,0 +1,49 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
const echoMock = jest.fn();
const execMock = jest.fn();
const exitMock = jest.fn();
const testMock = jest.fn();
jest.mock('shelljs', () => ({
echo: echoMock,
exec: execMock,
exit: exitMock,
test: testMock,
}));
const {publishAndroidArtifactsToMaven} = require('../release-utils');
describe('publishAndroidArtifactsToMaven', () => {
beforeEach(() => {
jest.resetAllMocks();
});
test('finds and releases the repository closed by build_android', () => {
execMock.mockReturnValueOnce({code: 0});
publishAndroidArtifactsToMaven('0.86.2', 'release');
expect(execMock).toHaveBeenCalledWith(
'./gradlew findSonatypeStagingRepository releaseSonatypeStagingRepository',
);
expect(exitMock).not.toHaveBeenCalled();
});
test('does not manage a staging repository for a nightly', () => {
publishAndroidArtifactsToMaven('0.87.0-nightly-20260728', 'nightly');
expect(execMock).not.toHaveBeenCalled();
expect(exitMock).not.toHaveBeenCalled();
});
});
+3 -3
View File
@@ -61,14 +61,14 @@ function publishAndroidArtifactsToMaven(
// We want to gate ourselves against accidentally publishing a 1.x or a 1000.x on
// maven central which will break the semver for our artifacts.
if (buildType === 'release' && releaseVersion.startsWith('0.')) {
// -------- For stable releases, we also need to close and release the staging repository.
// -------- The Android job already uploaded and closed this staging repository.
if (
exec(
'./gradlew publishAndroidToSonatype closeAndReleaseSonatypeStagingRepository',
'./gradlew findSonatypeStagingRepository releaseSonatypeStagingRepository',
).code
) {
echo(
'Failed to close and release the staging repository on Sonatype (Maven Central) for Android artifacts',
'Failed to release the staging repository on Sonatype (Maven Central) for Android artifacts',
);
exit(1);
}