Compare commits

..
Author SHA1 Message Date
AbbanMustafa fef31f74e5 fold into existing restore/save_build_cache 2026-03-18 01:16:41 -05:00
AbbanMustafa aa77ef6485 cleanup 2026-03-17 01:55:34 -05:00
AbbanMustafa c5a12d9c26 snapshots 2026-03-17 01:51:06 -05:00
AbbanMustafa 8a9bc57e28 cleanup 2026-03-17 01:39:01 -05:00
AbbanMustafa 94bf1ca46f cleanup 2026-03-17 01:31:28 -05:00
AbbanMustafa 8671d262f7 archive & simulator build support 2026-03-16 17:00:23 -05:00
AbbanMustafa 9aeaba46eb derived_data_path to the archive Gymfile template 2026-03-12 00:44:02 -05:00
AbbanMustafa d68a7fa34a proper path 2026-03-12 00:26:32 -05:00
AbbanMustafa b6450b28b6 proper path 2026-03-12 00:16:28 -05:00
AbbanMustafa 6090749291 run build phases 2026-03-11 19:19:49 -05:00
AbbanMustafa 10c148a359 derived data cache 2026-03-10 14:13:47 -05:00
Stanisław Chmiela f3fd05d2dc [eas-build-job] Rename UserFacingError to UserError (#3468)
## Summary
- rename `UserFacingError` to `UserError` across the stack
- keep payloads and behavior unchanged
- move unknown user-visible errors under the new name

## Changes
- rename the shared user error class in `eas-build-job`
- update `build-tools` and `worker` imports and `instanceof` checks
- update tests and direct `dist/errors` imports in build-tools

## Testing
- `packages/eas-build-job`: `npm exec -- corepack yarn build && npm exec -- corepack yarn test src/__tests__/errors.test.ts --runInBand`
- `packages/build-tools`: `npm exec -- corepack yarn jest-unit src/buildErrors/__tests__/detectError.test.ts src/steps/utils/ios/__tests__/AscApiUtils.test.ts --runInBand`
- `packages/worker`: `npm exec -- corepack yarn test:integration src/__integration__/stateSync.test.ts`
2026-03-10 10:17:55 +01:00
Ash Wu 1ca478cb5e [build-tools][steps] Report step metrics after each step (#3479)
* [build-tools][steps] Report step metrics after each step instead of batching at job completion

Signed-off-by: Ash Wu <[email protected]>

* address comments

Signed-off-by: Ash Wu <[email protected]>

* move reportStepMetric to customBuildContext

Signed-off-by: Ash Wu <[email protected]>

* address comments

Signed-off-by: Ash Wu <[email protected]>

---------

Signed-off-by: Ash Wu <[email protected]>
2026-03-10 14:57:53 +08:00
Expo CI efbb61b088 update CHANGELOG.md 2026-03-10 02:04:35 +00:00
42 changed files with 978 additions and 184 deletions

No files matched your search

+6 -2
View File
@@ -8,12 +8,16 @@ This is the log of notable changes to EAS CLI and related packages.
### 🎉 New features
- Show user email in `eas account:view` output. ([#3485](https://github.com/expo/eas-cli/pull/3485) by [@brentvatne](https://github.com/brentvatne))
### 🐛 Bug fixes
### 🧹 Chores
## [18.3.0](https://github.com/expo/eas-cli/releases/tag/v18.3.0) - 2026-03-10
### 🎉 New features
- Show user email in `eas account:view` output. ([#3485](https://github.com/expo/eas-cli/pull/3485) by [@brentvatne](https://github.com/brentvatne))
## [18.2.0](https://github.com/expo/eas-cli/releases/tag/v18.2.0) - 2026-03-09
### 🎉 New features
@@ -1,9 +1,14 @@
import { BuildTrigger, Ios, Metadata } from '@expo/eas-build-job';
import { StepMetric } from '@expo/steps';
import { createTestIosJob } from './utils/job';
import { createMockLogger } from './utils/logger';
import { BuildContext } from '../context';
import { CustomBuildContext } from '../customBuildContext';
import { uploadStepMetricsToWwwAsync } from '../utils/stepMetrics';
jest.mock('../utils/stepMetrics');
const mockUploadStepMetricsToWwwAsync = jest.mocked(uploadStepMetricsToWwwAsync);
describe(CustomBuildContext, () => {
it('should not lose workflowInterpolationContext', () => {
@@ -34,4 +39,122 @@ describe(CustomBuildContext, () => {
foo: 'bar',
});
});
describe('reportStepMetric', () => {
const expoApiV2BaseUrl = 'http://exp.test/--/api/v2/';
const workflowJobId = 'test-workflow-job-id';
const robotAccessToken = 'test-robot-token';
const sampleMetric: StepMetric = {
metricsId: 'eas/checkout',
result: 'success',
durationMs: 1000,
platform: 'linux',
};
function createCustomBuildContext(
overrides: {
expoApiV2BaseUrl?: string | undefined;
includeRobotAccessToken?: boolean;
includeWorkflowJobId?: boolean;
} = {}
): CustomBuildContext {
const job = createTestIosJob();
if (overrides.includeRobotAccessToken !== false) {
(job.secrets as any).robotAccessToken = robotAccessToken;
}
const env: Record<string, string> = {
__API_SERVER_URL: 'http://api.expo.test',
};
if (overrides.includeWorkflowJobId !== false) {
env.__WORKFLOW_JOB_ID = workflowJobId;
}
const ctx = new BuildContext(job, {
env,
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
logger: createMockLogger(),
uploadArtifact: jest.fn(),
workingdir: '/workingdir',
expoApiV2BaseUrl:
'expoApiV2BaseUrl' in overrides ? overrides.expoApiV2BaseUrl : expoApiV2BaseUrl,
});
return new CustomBuildContext(ctx);
}
beforeEach(() => {
jest.clearAllMocks();
mockUploadStepMetricsToWwwAsync.mockResolvedValue(undefined);
});
it('calls uploadStepMetricsToWwwAsync when all required fields are present', () => {
const customCtx = createCustomBuildContext();
customCtx.reportStepMetric(sampleMetric);
expect(mockUploadStepMetricsToWwwAsync).toHaveBeenCalledTimes(1);
expect(mockUploadStepMetricsToWwwAsync).toHaveBeenCalledWith(
expect.objectContaining({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl,
stepMetrics: [sampleMetric],
})
);
});
it('does not call upload when workflowJobId is missing', () => {
const customCtx = createCustomBuildContext({ includeWorkflowJobId: false });
customCtx.reportStepMetric(sampleMetric);
expect(mockUploadStepMetricsToWwwAsync).not.toHaveBeenCalled();
});
it('does not call upload when robotAccessToken is missing', () => {
const customCtx = createCustomBuildContext({ includeRobotAccessToken: false });
customCtx.reportStepMetric(sampleMetric);
expect(mockUploadStepMetricsToWwwAsync).not.toHaveBeenCalled();
});
it('does not call upload when expoApiV2BaseUrl is missing', () => {
const customCtx = createCustomBuildContext({ expoApiV2BaseUrl: undefined });
customCtx.reportStepMetric(sampleMetric);
expect(mockUploadStepMetricsToWwwAsync).not.toHaveBeenCalled();
});
it('drainPendingMetricUploads awaits all pending uploads', async () => {
let resolveUpload!: () => void;
const uploadPromise = new Promise<void>(resolve => {
resolveUpload = resolve;
});
mockUploadStepMetricsToWwwAsync.mockReturnValue(uploadPromise);
const customCtx = createCustomBuildContext();
customCtx.reportStepMetric(sampleMetric);
let drained = false;
const drainPromise = customCtx.drainPendingMetricUploads().then(() => {
drained = true;
});
await new Promise(r => setImmediate(r));
expect(drained).toBe(false);
resolveUpload();
await drainPromise;
expect(drained).toBe(true);
});
it('drainPendingMetricUploads settles even if an upload rejects', async () => {
mockUploadStepMetricsToWwwAsync.mockRejectedValue(new Error('upload failed'));
const customCtx = createCustomBuildContext();
customCtx.reportStepMetric(sampleMetric);
await expect(customCtx.drainPendingMetricUploads()).resolves.not.toThrow();
});
});
});
@@ -0,0 +1,128 @@
import { BuildPhase } from '@expo/eas-build-job';
import { BuildStepGlobalContext, StepsConfigParser } from '@expo/steps';
import { runGenericJobAsync } from '../generic';
import { CustomBuildContext } from '../customBuildContext';
import { uploadJobOutputsToWwwAsync } from '../utils/outputs';
jest.mock('../customBuildContext');
jest.mock('../utils/outputs');
jest.mock('../common/projectSources');
jest.mock('../steps/easFunctions', () => ({ getEasFunctions: jest.fn().mockReturnValue([]) }));
jest.mock('../steps/easFunctionGroups', () => ({
getEasFunctionGroups: jest.fn().mockReturnValue([]),
}));
jest.mock('@expo/steps');
jest.mock('fs/promises');
const mockUploadJobOutputsToWwwAsync = jest.mocked(uploadJobOutputsToWwwAsync);
describe(runGenericJobAsync, () => {
const expoApiV2BaseUrl = 'http://exp.test/--/api/v2/';
let mockDrainPendingMetricUploads: jest.Mock;
let mockCtx: any;
beforeEach(() => {
jest.clearAllMocks();
mockDrainPendingMetricUploads = jest.fn().mockResolvedValue(undefined);
(CustomBuildContext as unknown as jest.Mock).mockImplementation(() => ({
projectSourceDirectory: '/tmp/src',
env: { __WORKFLOW_JOB_ID: 'test-workflow-job-id' },
drainPendingMetricUploads: mockDrainPendingMetricUploads,
}));
(BuildStepGlobalContext as unknown as jest.Mock).mockImplementation(() => ({
env: { __WORKFLOW_JOB_ID: 'test-workflow-job-id' },
}));
mockCtx = {
expoApiV2BaseUrl,
job: {
secrets: { robotAccessToken: 'test-token' },
steps: [],
},
logger: {
info: jest.fn(),
debug: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
child: jest.fn().mockReturnThis(),
},
runBuildPhase: jest.fn(async (_phase: BuildPhase, fn: () => Promise<any>) => fn()),
};
mockUploadJobOutputsToWwwAsync.mockResolvedValue(undefined);
});
it('awaits drainPendingMetricUploads in COMPLETE_JOB phase', async () => {
const mockWorkflow = { executeAsync: jest.fn().mockResolvedValue(undefined) };
(StepsConfigParser as unknown as jest.Mock).mockImplementation(() => ({
parseAsync: jest.fn().mockResolvedValue(mockWorkflow),
}));
let resolveDrain!: () => void;
mockDrainPendingMetricUploads.mockReturnValue(
new Promise<void>(resolve => {
resolveDrain = resolve;
})
);
let resolved = false;
const resultPromise = runGenericJobAsync(mockCtx).then(() => {
resolved = true;
});
await new Promise(r => setImmediate(r));
expect(resolved).toBe(false);
resolveDrain();
await resultPromise;
expect(resolved).toBe(true);
});
it('awaits drainPendingMetricUploads even when outputs upload fails', async () => {
const mockWorkflow = { executeAsync: jest.fn().mockResolvedValue(undefined) };
(StepsConfigParser as unknown as jest.Mock).mockImplementation(() => ({
parseAsync: jest.fn().mockResolvedValue(mockWorkflow),
}));
mockUploadJobOutputsToWwwAsync.mockRejectedValue(new Error('outputs upload failed'));
let resolveDrain!: () => void;
mockDrainPendingMetricUploads.mockReturnValue(
new Promise<void>(resolve => {
resolveDrain = resolve;
})
);
let rejected = false;
const resultPromise = runGenericJobAsync(mockCtx).catch(err => {
rejected = true;
throw err;
});
await new Promise(r => setImmediate(r));
expect(rejected).toBe(false);
resolveDrain();
await expect(resultPromise).rejects.toThrow('outputs upload failed');
expect(rejected).toBe(true);
});
it('throws before workflow execution when expoApiV2BaseUrl is missing', async () => {
mockCtx.expoApiV2BaseUrl = undefined;
const mockWorkflow = { executeAsync: jest.fn() };
(StepsConfigParser as unknown as jest.Mock).mockImplementation(() => ({
parseAsync: jest.fn().mockResolvedValue(mockWorkflow),
}));
await expect(runGenericJobAsync(mockCtx)).rejects.toThrow(
'expoApiV2BaseUrl is required for generic jobs'
);
expect(CustomBuildContext).not.toHaveBeenCalled();
});
});
@@ -73,22 +73,20 @@ export async function resolveBuildPhaseErrorAsync(
return error;
}
const xcodeBuildLogs = await maybeReadXcodeBuildLogs(phase, buildLogsDirectory);
const userFacingError =
error instanceof errors.UserFacingError
const userError =
error instanceof errors.UserError
? error
: (resolveError(userErrorHandlers, logLines, errorContext, xcodeBuildLogs) ??
new errors.UnknownError(errorContext.phase));
const buildError = resolveError(buildErrorHandlers, logLines, errorContext, xcodeBuildLogs);
const trackingCode =
buildError && buildError.errorCode !== userFacingError.errorCode
? buildError.errorCode
: undefined;
buildError && buildError.errorCode !== userError.errorCode ? buildError.errorCode : undefined;
return new errors.BuildError(userFacingError.message, {
errorCode: userFacingError.errorCode,
return new errors.BuildError(userError.message, {
errorCode: userError.errorCode,
trackingCode,
docsUrl: userFacingError.docsUrl,
docsUrl: userError.docsUrl,
cause: error,
buildPhase: phase,
metadata: buildError?.metadata,
@@ -2,9 +2,9 @@ import { BuildMode, BuildPhase, Platform, Workflow, errors } from '@expo/eas-bui
import { ErrorHandler, XCODE_BUILD_PHASE } from './errors.types';
import UserFacingError = errors.UserFacingError;
import UserError = errors.UserError;
export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
export const userErrorHandlers: ErrorHandler<UserError>[] = [
{
platform: Platform.IOS,
phase: BuildPhase.INSTALL_PODS,
@@ -12,7 +12,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// example log:
// [!] `React` requires CocoaPods version `>= 1.10.1`, which is not satisfied by your current version, `1.10.0`.
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_UNSUPPORTED_COCOAPODS_VERSION_ERROR',
`Your project requires a newer version of CocoaPods. You can update it in the build profile in eas.json by either:
- changing the current version under key "cocoapods"
@@ -27,7 +27,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// example log:
// /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/dependency.rb:313:in `to_specs': Could not find 'bundler' (2.2.3) required by your /Users/expo/project/build/ios/Gemfile.lock. (Gem::MissingSpecVersionError)
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_UNSUPPORTED_BUNDLER_VERSION_ERROR',
`Your project requires a different version of the Ruby "bundler" program than the version installed in this EAS Build environment. You can specify which version of "bundler" to install by specifying the version under "build"→[buildProfileName]→"ios"→"bundler" in eas.json.`,
{ docsUrl: 'https://docs.expo.dev/build-reference/eas-json/' }
@@ -40,7 +40,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// > Failed to read key keyalias from store "/build/workingdir/build/generic/keystore-5787e6af-3002-4cb7-8a57-3e73d13313c2.jks": Invalid keystore format
regexp: /Invalid keystore format/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_INVALID_KEYSTORE_FORMAT_ERROR',
'The keystore used in this build is malformed or it has an unsupported type. Make sure you provided the correct file.'
),
@@ -52,7 +52,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// > Failed to read key keyalias from store "/build/workingdir/build/generic/keystore-286069a8-4bb9-48a6-add9-acf6b58ea06d.jks": null
regexp: /Failed to read key[^\n]+from store/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_INVALID_KEYSTORE_ALIAS_ERROR',
'The alias specified for this keystore does not exist. Make sure you specified the correct value.'
),
@@ -67,7 +67,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// [11:17:29] Error: [android.dangerous]: withAndroidDangerousBaseMod: Cannot copy google-services.json from /home/expo/workingdir/build/test/test-google-services.json to /home/expo/workingdir/build/android/app/google-services.json. Please make sure the source and destination paths exist.
regexp: /Cannot copy google-services\.json/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_MISSING_GOOGLE_SERVICES_JSON_ERROR',
'"google-services.json" is missing, make sure that the file exists. Remember that EAS Build only uploads the files tracked by git. Use EAS environment variables to provide EAS Build with the file.',
{ docsUrl: 'https://docs.expo.dev/eas/environment-variables/#file-environment-variables' }
@@ -82,7 +82,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
regexp:
/File google-services\.json is missing\. The Google Services Plugin cannot function without it/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_MISSING_GOOGLE_SERVICES_JSON_ERROR',
'"google-services.json" is missing, make sure that the file exists. Remember that EAS Build only uploads the files tracked by git. Use EAS environment variables to provide EAS Build with the file.',
{ docsUrl: 'https://docs.expo.dev/eas/environment-variables/#file-environment-variables' }
@@ -95,7 +95,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
// [08:44:18] ENOENT: no such file or directory, copyfile '/Users/expo/workingdir/build/managed/abc' -> '/Users/expo/workingdir/build/managed/ios/testapp/GoogleService-Info.plist'
regexp: /ENOENT: no such file or directory, copyfile .*GoogleService-Info.plist/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_MISSING_GOOGLE_SERVICES_PLIST_ERROR',
'"GoogleService-Info.plist" is missing, make sure that the file exists. Remember that EAS Build only uploads the files tracked by git. Use EAS environment variables to provide EAS Build with the file.',
{ docsUrl: 'https://docs.expo.dev/eas/environment-variables/#file-environment-variables' }
@@ -113,7 +113,7 @@ export const userErrorHandlers: ErrorHandler<UserFacingError>[] = [
regexp:
/Specs satisfying the `(.*)` dependency were found, but they required a higher minimum deployment target/,
createError: (_, { job }) => {
return new UserFacingError(
return new UserError(
'EAS_BUILD_HIGHER_MINIMUM_DEPLOYMENT_TARGET_ERROR',
`Some pods require a higher minimum deployment target.
${
@@ -141,7 +141,7 @@ ${
// You should run `pod update Firebase/Core` to apply changes you've made.
regexp: /CocoaPods could not find compatible versions for pod /,
createError: () => {
return new UserFacingError(
return new UserError(
'EAS_BUILD_INCOMPATIBLE_PODS_ERROR',
`Compatible versions of some pods could not be resolved.
You are seeing this error because either:
@@ -161,7 +161,7 @@ You are seeing this error because either:
/Fix the upstream dependency conflict, or retry.*\s.*this command with --force, or --legacy-peer-deps/,
createError: (matchResult: RegExpMatchArray) => {
if (matchResult.length >= 2) {
return new UserFacingError(
return new UserError(
'EAS_BUILD_NPM_CONFLICTING_PEER_DEPENDENCIES',
`Some of your peer dependencies are not compatible. The recommended approach is to fix your dependencies by resolving any conflicts listed by "npm install". As a temporary workaround you can:
- Add ".npmrc" file with "legacy-peer-deps=true" and commit that to your repo.
@@ -179,7 +179,7 @@ You are seeing this error because either:
regexp: /Integrity check failed for "(.*)" \(computed integrity doesn't match our records, got/,
createError: (matchResult: RegExpMatchArray) => {
if (matchResult.length >= 2) {
return new UserFacingError(
return new UserError(
'EAS_BUILD_YARN_LOCK_CHECKSUM_ERROR',
`Checksum for package "${matchResult[1]}" does not match value in registry. To fix that:
- run "yarn cache clean"
@@ -203,7 +203,7 @@ You are seeing this error because either:
/\[1\/4\] Resolving packages...\s*\[2\/4\] Fetching packages...\s*\[1\/4\] Resolving packages...\s*\[2\/4\] Fetching packages.../,
createError: (matchResult: RegExpMatchArray) => {
if (matchResult) {
return new UserFacingError(
return new UserError(
'EAS_BUILD_YARN_MULTIPLE_INSTANCES_ERROR',
`One of project dependencies is starting new install process while the main one is still in progress, which might result in corrupted packages. Most likely the reason for error is "prepare" script in git-referenced dependency of your project. Learn more: https://github.com/yarnpkg/yarn/issues/7212#issuecomment-493720324`
);
@@ -230,7 +230,7 @@ You are seeing this error because either:
regexp: /error: Signing for "[a-zA-Z-0-9_]+" requires a development team/,
createError: (_, { job }) =>
'type' in job && job.type === Workflow.MANAGED
? new UserFacingError(
? new UserError(
'XCODE_RESOURCE_BUNDLE_CODE_SIGNING_ERROR',
`Starting from Xcode 14, resource bundles are signed by default, which requires setting the development team for each resource bundle target.
To resolve this issue, downgrade to an older Xcode version using the "image" field in eas.json, or upgrade to SDK 46 or higher.`,
@@ -239,7 +239,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
'https://docs.expo.dev/build-reference/infrastructure/#ios-build-server-configurations',
}
)
: new UserFacingError(
: new UserError(
'XCODE_RESOURCE_BUNDLE_CODE_SIGNING_ERROR',
`Starting from Xcode 14, resource bundles are signed by default, which requires setting the development team for each resource bundle target.
To resolve this issue, downgrade to an older Xcode version using the "image" field in eas.json, or turn off signing resource bundles in your Podfile: https://expo.fyi/r/disable-bundle-resource-signing`,
@@ -254,7 +254,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
phase: BuildPhase.RUN_GRADLEW,
regexp: /.*/,
createError: () =>
new UserFacingError(
new UserError(
errors.ErrorCode.UNKNOWN_GRADLE_ERROR,
'Gradle build failed with unknown error. See logs for the "Run gradlew" phase for more information.'
),
@@ -265,7 +265,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
mode: BuildMode.RESIGN,
regexp: /No provisioning profile for application: '(.+)' with bundle identifier '(.+)'/,
createError: () =>
new UserFacingError(
new UserError(
'EAS_BUILD_RESIGN_PROVISIONING_PROFILE_MISMATCH_ERROR',
`The bundle identifier in provisioning profile used to resign the app does not match the bundle identifier of the app selected to be resigned. See logs above for more information.`
),
@@ -276,7 +276,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
mode: BuildMode.RESIGN,
regexp: /.*/,
createError: () =>
new UserFacingError(
new UserError(
errors.ErrorCode.UNKNOWN_FASTLANE_RESIGN_ERROR,
`The "Run fastlane" step failed with an unknown error.`
),
@@ -297,7 +297,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
// file modified: /Users/expo/workingdir/build/packages/video/ios/Vendor/dependency/ProgrammaticAccessLibrary.xcframework/ios-arm64/ProgrammaticAccessLibrary.framework/ProgrammaticAccessLibrary
regexp: /error: .+/g,
createError: matchResult =>
new UserFacingError(
new UserError(
'XCODE_BUILD_ERROR',
`The "Run fastlane" step failed because of an error in the Xcode build process. We automatically detected following errors in your Xcode build logs:\n${matchResult
.map(match => `- ${match.replace('error: ', '')}`)
@@ -309,7 +309,7 @@ To resolve this issue, downgrade to an older Xcode version using the "image" fie
phase: BuildPhase.RUN_FASTLANE,
regexp: /.*/,
createError: () =>
new UserFacingError(
new UserError(
errors.ErrorCode.UNKNOWN_FASTLANE_ERROR,
`The "Run fastlane" step failed with an unknown error. Refer to "Xcode Logs" below for additional, more detailed logs.`
),
@@ -1,10 +1,12 @@
import { BuildJob } from '@expo/eas-build-job';
import { BuildWorkflow } from '@expo/steps';
import { vol } from 'memfs';
import { createTestIosJob } from '../../__tests__/utils/job';
import { createMockLogger } from '../../__tests__/utils/logger';
import { prepareProjectSourcesAsync } from '../../common/projectSources';
import { BuildContext } from '../../context';
import { CustomBuildContext } from '../../customBuildContext';
import { findAndUploadXcodeBuildLogsAsync } from '../../ios/xcodeBuildLogs';
import { runCustomBuildAsync } from '../custom';
@@ -74,4 +76,60 @@ describe(runCustomBuildAsync, () => {
expect(prepareProjectSourcesAsync).toHaveBeenCalledTimes(2);
});
it('awaits drainPendingMetricUploads after workflow execution', async () => {
let resolveDrain!: () => void;
const drainSpy = jest
.spyOn(CustomBuildContext.prototype, 'drainPendingMetricUploads')
.mockReturnValue(
new Promise<void>(resolve => {
resolveDrain = resolve;
})
);
let resolved = false;
const resultPromise = runCustomBuildAsync(ctx).then(() => {
resolved = true;
});
await new Promise(r => setImmediate(r));
expect(resolved).toBe(false);
resolveDrain();
await resultPromise;
expect(resolved).toBe(true);
drainSpy.mockRestore();
});
it('awaits drainPendingMetricUploads even when workflow throws', async () => {
let resolveDrain!: () => void;
const drainSpy = jest
.spyOn(CustomBuildContext.prototype, 'drainPendingMetricUploads')
.mockReturnValue(
new Promise<void>(resolve => {
resolveDrain = resolve;
})
);
const executeSpy = jest
.spyOn(BuildWorkflow.prototype, 'executeAsync')
.mockRejectedValue(new Error('workflow failed'));
let rejected = false;
const resultPromise = runCustomBuildAsync(ctx).catch(err => {
rejected = true;
throw err;
});
await new Promise(r => setImmediate(r));
expect(rejected).toBe(false);
resolveDrain();
await expect(resultPromise).rejects.toThrow('workflow failed');
expect(rejected).toBe(true);
drainSpy.mockRestore();
executeSpy.mockRestore();
});
});
@@ -94,6 +94,7 @@ export async function runCustomBuildAsync(ctx: BuildContext<BuildJob>): Promise<
// do nothing, it's a non-breaking error.
}
}
await customBuildCtx.drainPendingMetricUploads();
}
} catch (err: any) {
err.artifacts = ctx.artifacts;
+28 -2
View File
@@ -16,8 +16,13 @@ import { runFastlaneGym, runFastlaneResign } from '../ios/fastlane';
import { installPods } from '../ios/pod';
import { downloadApplicationArchiveAsync } from '../ios/resign';
import { resolveArtifactPath, resolveBuildConfiguration, resolveScheme } from '../ios/resolve';
import { cacheStatsAsync, restoreCcacheAsync } from '../steps/functions/restoreBuildCache';
import { saveCcacheAsync } from '../steps/functions/saveBuildCache';
import {
cacheStatsAsync,
patchPodsXcodeprojAsync,
restoreCcacheAsync,
restoreXcodeCacheAsync,
} from '../steps/functions/restoreBuildCache';
import { saveCcacheAsync, saveXcodeCacheAsync } from '../steps/functions/saveBuildCache';
import { uploadApplicationArchive } from '../utils/artifacts';
import {
configureExpoUpdatesIfInstalledAsync,
@@ -51,6 +56,7 @@ async function buildAsync(ctx: BuildContext<Ios.Job>): Promise<void> {
const evictUsedBefore = new Date();
const credentialsManager = new CredentialsManager(ctx);
const workingDirectory = ctx.getReactNativeProjectDirectory();
let xcodeCacheHit = false;
try {
const credentials = await ctx.runBuildPhase(BuildPhase.PREPARE_CREDENTIALS, async () => {
return await credentialsManager.prepare();
@@ -87,10 +93,23 @@ async function buildAsync(ctx: BuildContext<Ios.Job>): Promise<void> {
env: ctx.env,
secrets: ctx.job.secrets,
});
xcodeCacheHit = await restoreXcodeCacheAsync({
logger: ctx.logger,
workingDirectory: ctx.buildDirectory,
env: ctx.env,
secrets: ctx.job.secrets,
simulator: ctx.job.simulator,
});
});
await ctx.runBuildPhase(BuildPhase.INSTALL_PODS, async () => {
await runInstallPodsAsync(ctx);
await patchPodsXcodeprojAsync({
logger: ctx.logger,
workingDirectory: ctx.buildDirectory,
env: ctx.env,
cacheHit: xcodeCacheHit,
});
});
await ctx.runBuildPhase(BuildPhase.POST_INSTALL_HOOK, async () => {
@@ -188,6 +207,13 @@ async function buildAsync(ctx: BuildContext<Ios.Job>): Promise<void> {
ctx.logger.info('Local builds do not support saving cache.');
return;
}
await saveXcodeCacheAsync({
logger: ctx.logger,
workingDirectory: ctx.buildDirectory,
env: ctx.env,
secrets: ctx.job.secrets,
simulator: ctx.job.simulator,
});
await ctx.cacheManager?.saveCache(ctx);
await saveCcacheAsync({
logger: ctx.logger,
+10 -4
View File
@@ -1,7 +1,13 @@
import { ExpoConfig } from '@expo/config';
import { BuildJob, BuildPhase, Ios, Job, Platform } from '@expo/eas-build-job';
import { BuildTrigger } from '@expo/eas-build-job/dist/common';
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import {
BuildJob,
BuildPhase,
BuildTrigger,
Ios,
Job,
Platform,
UserError,
} from '@expo/eas-build-job';
import spawn, { SpawnResult } from '@expo/turtle-spawn';
import fs from 'fs-extra';
import nullthrows from 'nullthrows';
@@ -281,7 +287,7 @@ async function validateAppConfigAsync(
extraMessage =
'If you are using environment variables to switch between projects in app.config.js/app.config.ts, make sure those variables are also set inside EAS Build. You can do that using "env" field in eas.json or EAS environment variables. ';
}
throw new UserFacingError(
throw new UserError(
'EAS_BUILD_PROJECT_ID_MISMATCH',
`The value of the "extra.eas.projectId" field (${appConfig.extra.eas.projectId}) in the app config does not match the current project id (${ctx.env.EAS_BUILD_PROJECT_ID}). ${extraMessage}Learn more: https://expo.fyi/eas-config-mismatch.`
);
+3
View File
@@ -67,6 +67,7 @@ export interface BuildContextOptions {
reportBuildPhaseStats?: (stats: BuildPhaseStats) => void;
skipNativeBuild?: boolean;
metadata?: Metadata;
expoApiV2BaseUrl?: string;
}
export class SkipNativeBuildError extends Error {}
@@ -82,6 +83,7 @@ export class BuildContext<TJob extends Job = Job> {
options?: { tags?: Record<string, string>; extras?: Record<string, string> }
) => void;
public readonly skipNativeBuild?: boolean;
public readonly expoApiV2BaseUrl?: string;
public artifacts: Artifacts = {};
private readonly _isLocal: boolean;
@@ -110,6 +112,7 @@ export class BuildContext<TJob extends Job = Job> {
this._job = job;
this._metadata = options.metadata;
this.skipNativeBuild = options.skipNativeBuild;
this.expoApiV2BaseUrl = options.expoApiV2BaseUrl;
this.reportBuildPhaseStats = options.reportBuildPhaseStats;
const environmentSecrets = this.getEnvironmentSecrets(job);
+27 -1
View File
@@ -9,12 +9,13 @@ import {
StaticJobInterpolationContext,
} from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { BuildRuntimePlatform, ExternalBuildContextProvider } from '@expo/steps';
import { BuildRuntimePlatform, ExternalBuildContextProvider, StepMetric } from '@expo/steps';
import { Client } from '@urql/core';
import assert from 'assert';
import path from 'path';
import { ArtifactToUpload, BuildContext } from './context';
import { uploadStepMetricsToWwwAsync } from './utils/stepMetrics';
const platformToBuildRuntimePlatform: Record<Platform, BuildRuntimePlatform> = {
[Platform.ANDROID]: BuildRuntimePlatform.LINUX,
@@ -60,6 +61,8 @@ export class CustomBuildContext<TJob extends Job = Job> implements ExternalBuild
public metadata?: Metadata;
private _env: Env;
private readonly expoApiV2BaseUrl?: string;
private readonly pendingMetricUploads: Promise<void>[] = [];
constructor(buildCtx: BuildContext<TJob>) {
this._env = buildCtx.env;
@@ -75,6 +78,7 @@ export class CustomBuildContext<TJob extends Job = Job> implements ExternalBuild
this.runtimeApi = {
uploadArtifact: (...args) => buildCtx['uploadArtifact'](...args),
};
this.expoApiV2BaseUrl = buildCtx.expoApiV2BaseUrl;
this.startTime = new Date();
}
@@ -142,4 +146,26 @@ export class CustomBuildContext<TJob extends Job = Job> implements ExternalBuild
};
this.metadata = metadata;
}
public reportStepMetric(metric: StepMetric): void {
const workflowJobId = this._env.__WORKFLOW_JOB_ID;
const robotAccessToken = this.job.secrets?.robotAccessToken;
if (!workflowJobId || !robotAccessToken || !this.expoApiV2BaseUrl) {
return;
}
const p = uploadStepMetricsToWwwAsync({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl: this.expoApiV2BaseUrl,
stepMetrics: [metric],
logger: this.logger,
});
this.pendingMetricUploads.push(p);
}
public async drainPendingMetricUploads(): Promise<void> {
await Promise.allSettled(this.pendingMetricUploads);
}
}
+17 -18
View File
@@ -2,6 +2,7 @@ import { BuildPhase, Generic } from '@expo/eas-build-job';
import { Result, asyncResult } from '@expo/results';
import { BuildStepGlobalContext, BuildWorkflow, StepsConfigParser, errors } from '@expo/steps';
import fs from 'fs/promises';
import nullthrows from 'nullthrows';
import { prepareProjectSourcesAsync } from './common/projectSources';
import { BuildContext } from './context';
@@ -10,12 +11,17 @@ import { getEasFunctionGroups } from './steps/easFunctionGroups';
import { getEasFunctions } from './steps/easFunctions';
import { uploadJobOutputsToWwwAsync } from './utils/outputs';
import { retryAsync } from './utils/retry';
import { uploadStepMetricsToWwwAsync } from './utils/stepMetrics';
export async function runGenericJobAsync(
ctx: BuildContext<Generic.Job>,
{ expoApiV2BaseUrl }: { expoApiV2BaseUrl: string }
ctx: BuildContext<Generic.Job>
): Promise<{ runResult: Result<void>; buildWorkflow: BuildWorkflow }> {
// expoApiV2BaseUrl is empty when running a local build, but generic jobs
// are never executed locally, so it is always present here.
const expoApiV2BaseUrl = nullthrows(
ctx.expoApiV2BaseUrl,
'expoApiV2BaseUrl is required for generic jobs'
);
const customBuildCtx = new CustomBuildContext(ctx);
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
@@ -60,22 +66,15 @@ export async function runGenericJobAsync(
const runResult = await asyncResult(workflow.executeAsync());
await ctx.runBuildPhase(BuildPhase.COMPLETE_JOB, async () => {
await uploadJobOutputsToWwwAsync(globalContext, {
logger: ctx.logger,
expoApiV2BaseUrl,
});
const workflowJobId = globalContext.env.__WORKFLOW_JOB_ID;
const robotAccessToken = ctx.job.secrets?.robotAccessToken;
if (workflowJobId && robotAccessToken) {
await uploadStepMetricsToWwwAsync({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl,
stepMetrics: globalContext.stepMetrics,
const results = await Promise.allSettled([
uploadJobOutputsToWwwAsync(globalContext, {
logger: ctx.logger,
});
expoApiV2BaseUrl,
}),
customBuildCtx.drainPendingMetricUploads(),
]);
if (results[0].status === 'rejected') {
throw results[0].reason;
}
});
@@ -19,6 +19,8 @@ export_options({
export_xcargs "OTHER_CODE_SIGN_FLAGS=\\"--keychain /Users/expo/Library/Keychains/login.keychain\\""
derived_data_path("./build")
disable_xcpretty(true)
buildlog_path("/tmp/logs")
@@ -42,6 +44,8 @@ export_options({
export_xcargs "OTHER_CODE_SIGN_FLAGS=\\"--keychain /tmp/keychain\\""
derived_data_path("./build")
disable_xcpretty(true)
buildlog_path("/tmp/logs")
@@ -67,6 +71,8 @@ export_options({
export_xcargs "OTHER_CODE_SIGN_FLAGS=\\"--keychain /tmp/keychain\\""
derived_data_path("./build")
disable_xcpretty(true)
buildlog_path("/tmp/logs")
@@ -94,6 +100,8 @@ export_options({
export_xcargs "OTHER_CODE_SIGN_FLAGS=\\"--keychain /tmp/keychain\\""
derived_data_path("./build")
disable_xcpretty(true)
buildlog_path("/tmp/logs")
@@ -57,6 +57,7 @@ describe('gymfile', () => {
credentials: mockCredentials,
scheme: 'MyApp',
buildConfiguration: 'Release',
derivedDataPath: './build',
outputDirectory: '/tmp/output',
clean: true,
logsDirectory: '/tmp/logs',
@@ -93,6 +94,7 @@ describe('gymfile', () => {
outputFile,
credentials: mockCredentials,
scheme: 'TestScheme',
derivedDataPath: './build',
outputDirectory: '/tmp/output',
clean: false,
logsDirectory: '/tmp/logs',
@@ -130,6 +132,7 @@ describe('gymfile', () => {
credentials: mockCredentials,
scheme: 'MyApp',
buildConfiguration: 'Release',
derivedDataPath: './build',
outputDirectory: '/tmp/output',
clean: true,
logsDirectory: '/tmp/logs',
@@ -191,6 +194,7 @@ describe('gymfile', () => {
outputFile,
credentials: mockCredentials,
scheme: 'MyApp',
derivedDataPath: './build',
outputDirectory: '/tmp/output',
clean: true,
logsDirectory: '/tmp/logs',
+1
View File
@@ -141,6 +141,7 @@ async function ensureGymfileExists<TJob extends Ios.Job>(
credentials: nullthrows(credentials, 'credentials must exist for non-simulator builds'),
scheme,
buildConfiguration,
derivedDataPath: './build',
outputDirectory: './build',
clean: false,
logsDirectory,
+3
View File
@@ -10,6 +10,7 @@ interface ArchiveBuildOptions {
credentials: Credentials;
scheme: string;
buildConfiguration?: string;
derivedDataPath: string;
outputDirectory: string;
clean: boolean;
logsDirectory: string;
@@ -32,6 +33,7 @@ export async function createGymfileForArchiveBuild({
credentials,
scheme,
buildConfiguration,
derivedDataPath,
entitlements,
outputDirectory,
logsDirectory,
@@ -58,6 +60,7 @@ export async function createGymfileForArchiveBuild({
KEYCHAIN_PATH: credentials.keychainPath,
SCHEME: scheme,
SCHEME_BUILD_CONFIGURATION: buildConfiguration,
DERIVED_DATA_PATH: derivedDataPath,
OUTPUT_DIRECTORY: outputDirectory,
EXPORT_METHOD: credentials.distributionType,
CLEAN: String(clean),
@@ -74,6 +74,8 @@ function createStepsForIosSimulatorBuild({
globalCtx,
buildToolsContext,
}: HelperFunctionsInput): BuildStep[] {
const evictUsedBefore = new Date();
const calculateEASUpdateRuntimeVersion =
calculateEASUpdateRuntimeVersionFunction().createBuildStepFromFunctionCall(globalCtx, {
id: 'calculate_eas_update_runtime_version',
@@ -106,6 +108,11 @@ function createStepsForIosSimulatorBuild({
createPrebuildBuildFunction().createBuildStepFromFunctionCall(globalCtx),
calculateEASUpdateRuntimeVersion,
installPods,
createRestoreBuildCacheFunction().createBuildStepFromFunctionCall(globalCtx, {
callInputs: {
platform: Platform.IOS,
},
}),
configureEASUpdate,
...(shouldUseEagerBundle(globalCtx.staticContext.metadata)
? [
@@ -122,6 +129,11 @@ function createStepsForIosSimulatorBuild({
createFindAndUploadBuildArtifactsBuildFunction(
buildToolsContext
).createBuildStepFromFunctionCall(globalCtx),
createSaveBuildCacheFunction(evictUsedBefore).createBuildStepFromFunctionCall(globalCtx, {
callInputs: {
platform: Platform.IOS,
},
}),
];
}
@@ -195,9 +207,9 @@ function createStepsForIosBuildWithCredentials({
),
resolveAppleTeamIdFromCredentials,
prebuildStep,
restoreCache,
calculateEASUpdateRuntimeVersion,
installPods,
restoreCache,
configureEASUpdate,
configureIosCredentialsFunction().createBuildStepFromFunctionCall(globalCtx),
configureIosVersionFunction().createBuildStepFromFunctionCall(globalCtx),
@@ -1,4 +1,4 @@
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import { UserError } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -56,7 +56,7 @@ export function createDownloadArtifactFunction(): BuildFunction {
const interpolationContext = stepsCtx.global.getInterpolationContext();
if (!('workflow' in interpolationContext)) {
throw new UserFacingError(
throw new UserError(
'EAS_DOWNLOAD_ARTIFACT_NO_WORKFLOW',
'No workflow found in the interpolation context.'
);
@@ -64,7 +64,7 @@ export function createDownloadArtifactFunction(): BuildFunction {
const robotAccessToken = stepsCtx.global.staticContext.job.secrets?.robotAccessToken;
if (!robotAccessToken) {
throw new UserFacingError(
throw new UserError(
'EAS_DOWNLOAD_ARTIFACT_NO_ROBOT_ACCESS_TOKEN',
'No robot access token found in the job secrets.'
);
@@ -1,4 +1,4 @@
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import { UserError } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -134,7 +134,7 @@ export async function downloadBuildAsync({
});
if (matchingFiles.length === 0) {
throw new UserFacingError(
throw new UserError(
'EAS_DOWNLOAD_BUILD_NO_MATCHING_FILES',
`No ${extensions.map(ext => `.${ext}`).join(', ')} entries found in the archive.`
);
@@ -1,4 +1,4 @@
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import { UserError } from '@expo/eas-build-job';
import {
BuildFunction,
BuildStepInput,
@@ -51,10 +51,7 @@ export function createReadIpaInfoBuildFunction(): BuildFunction {
const ipaPathInput = z.string().parse(inputs.ipa_path.value);
const ipaPath = path.resolve(stepCtx.workingDirectory, ipaPathInput);
if (!(await fs.pathExists(ipaPath))) {
throw new UserFacingError(
'EAS_READ_IPA_INFO_FILE_NOT_FOUND',
`IPA file not found: ${ipaPath}`
);
throw new UserError('EAS_READ_IPA_INFO_FILE_NOT_FOUND', `IPA file not found: ${ipaPath}`);
}
const ipaInfo = await readIpaInfoAsync(ipaPath);
@@ -72,7 +69,7 @@ export async function readIpaInfoAsync(ipaPath: string): Promise<IpaInfo> {
const bundleIdentifier = infoPlist.CFBundleIdentifier;
if (typeof bundleIdentifier !== 'string') {
throw new UserFacingError(
throw new UserError(
'EAS_READ_IPA_INFO_INVALID_INFO_PLIST',
'Failed to read IPA info: Missing or invalid CFBundleIdentifier in Info.plist'
);
@@ -80,7 +77,7 @@ export async function readIpaInfoAsync(ipaPath: string): Promise<IpaInfo> {
const bundleShortVersion = infoPlist.CFBundleShortVersionString;
if (typeof bundleShortVersion !== 'string') {
throw new UserFacingError(
throw new UserError(
'EAS_READ_IPA_INFO_INVALID_INFO_PLIST',
'Failed to read IPA info: Missing or invalid CFBundleShortVersionString in Info.plist'
);
@@ -88,7 +85,7 @@ export async function readIpaInfoAsync(ipaPath: string): Promise<IpaInfo> {
const bundleVersion = infoPlist.CFBundleVersion;
if (typeof bundleVersion !== 'string') {
throw new UserFacingError(
throw new UserError(
'EAS_READ_IPA_INFO_INVALID_INFO_PLIST',
'Failed to read IPA info: Missing or invalid CFBundleVersion in Info.plist'
);
@@ -100,11 +97,11 @@ export async function readIpaInfoAsync(ipaPath: string): Promise<IpaInfo> {
bundleVersion,
};
} catch (error) {
if (error instanceof UserFacingError) {
if (error instanceof UserError) {
throw error;
}
throw new UserFacingError(
throw new UserError(
'EAS_READ_IPA_INFO_FAILED',
`Failed to read IPA info: ${(error as Error).message}`,
{ cause: error }
@@ -118,10 +115,7 @@ function parseInfoPlistBuffer(data: Buffer): Record<string, unknown> {
const parsedBinaryPlists = bplistParser.parseBuffer(data);
const parsedBinaryPlist = parsedBinaryPlists[0];
if (!parsedBinaryPlist || typeof parsedBinaryPlist !== 'object') {
throw new UserFacingError(
'EAS_READ_IPA_INFO_INVALID_BINARY_PLIST',
'Invalid binary plist in IPA'
);
throw new UserError('EAS_READ_IPA_INFO_INVALID_BINARY_PLIST', 'Invalid binary plist in IPA');
}
return parsedBinaryPlist as Record<string, unknown>;
}
@@ -135,7 +129,7 @@ async function readInfoPlistBufferFromIpaAsync(ipaPath: string): Promise<Buffer>
const entries = Object.values(await zip.entries());
const infoPlistEntry = entries.find(entry => INFO_PLIST_PATH_REGEXP.test(entry.name));
if (!infoPlistEntry) {
throw new UserFacingError(
throw new UserError(
'EAS_READ_IPA_INFO_INFO_PLIST_NOT_FOUND',
`Failed to read IPA info: Could not find Info.plist in ${ipaPath}`
);
@@ -1,4 +1,4 @@
import { Platform } from '@expo/eas-build-job';
import { Ios, Platform } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -7,7 +7,10 @@ import {
BuildStepInputValueTypeName,
spawnAsync,
} from '@expo/steps';
import spawn from '@expo/turtle-spawn';
import fs from 'fs';
import nullthrows from 'nullthrows';
import path from 'path';
import { sendCcacheStatsAsync } from './ccacheStats';
import { decompressCacheAsync, downloadCacheAsync, downloadPublicCacheAsync } from './restoreCache';
@@ -17,6 +20,11 @@ import {
getCcachePath,
} from '../../utils/cacheKey';
import { TurtleFetchError } from '../../utils/turtleFetch';
import { XCODE_CACHE_KEY_PREFIX, generateXcodeCacheKeyAsync } from '../../utils/xcodeCacheKey';
// Stable path outside DerivedData where cached pod products are restored.
// xcodebuild archive wipes ArchiveIntermediates, so products must live elsewhere.
export const PODS_CACHE_DIR = '/tmp/pods-cache';
export function createRestoreBuildCacheFunction(): BuildFunction {
return new BuildFunction({
@@ -50,6 +58,23 @@ export function createRestoreBuildCacheFunction(): BuildFunction {
env,
secrets: stepCtx.global.staticContext.job.secrets,
});
if (platform === Platform.IOS) {
const simulator = (stepCtx.global.staticContext.job as Ios.Job).simulator;
const cacheHit = await restoreXcodeCacheAsync({
logger,
workingDirectory,
env,
secrets: stepCtx.global.staticContext.job.secrets,
simulator,
});
await patchPodsXcodeprojAsync({
logger,
workingDirectory,
env,
cacheHit,
});
}
},
});
}
@@ -176,6 +201,191 @@ export async function restoreCcacheAsync({
}
}
export async function restoreXcodeCacheAsync({
logger,
workingDirectory,
env,
secrets,
simulator,
}: {
logger: bunyan;
workingDirectory: string;
env: Record<string, string | undefined>;
secrets?: { robotAccessToken?: string };
simulator?: boolean;
}): Promise<boolean> {
if (env.EAS_XCODE_CACHE !== '1') {
return false;
}
const robotAccessToken = nullthrows(
secrets?.robotAccessToken,
'Robot access token is required for cache operations'
);
const expoApiServerURL = nullthrows(env.__API_SERVER_URL, '__API_SERVER_URL is not set');
try {
const cacheKey = await generateXcodeCacheKeyAsync(workingDirectory, simulator);
logger.info(`Restoring Xcode cache key: ${cacheKey}`);
const jobId = nullthrows(env.EAS_BUILD_ID, 'EAS_BUILD_ID is not set');
const { archivePath, matchedKey } = await downloadCacheAsync({
logger,
jobId,
expoApiServerURL,
robotAccessToken,
paths: ['pods-products-v2'],
key: cacheKey,
keyPrefixes: [`${XCODE_CACHE_KEY_PREFIX}${simulator ? 'sim' : 'device'}-`],
platform: Platform.IOS,
});
await fs.promises.mkdir(PODS_CACHE_DIR, { recursive: true });
await spawn('tar', ['xzf', archivePath, '-C', PODS_CACHE_DIR]);
// Modulemap files contain hardcoded absolute paths from the original build.
// Rewrite them to point to the cache directory instead.
await rewriteModulemapPathsAsync(PODS_CACHE_DIR, logger);
logger.info(
`Xcode cache restored to ${PODS_CACHE_DIR} ${matchedKey === cacheKey ? '(direct hit)' : '(prefix match)'}`
);
return true;
} catch (err: unknown) {
if (err instanceof TurtleFetchError && err.response?.status === 404) {
logger.info('No Xcode cache found for this key');
} else {
logger.warn('Failed to restore Xcode cache: ', err);
}
return false;
}
}
async function rewriteModulemapPathsAsync(cacheDir: string, logger: bunyan): Promise<void> {
let modulemapFiles: string;
try {
const result = await spawn('find', [cacheDir, '-name', '*.modulemap'], { stdio: 'pipe' });
modulemapFiles = result.stdout.trim();
} catch {
return;
}
if (!modulemapFiles) {
return;
}
let patchCount = 0;
for (const filePath of modulemapFiles.split('\n')) {
if (!filePath) continue;
const content = await fs.promises.readFile(filePath, 'utf-8');
// Match absolute paths ending with /Release-<platform>/ (iphoneos, iphonesimulator, etc.)
const replaced = content.replace(/"[^"]*\/Release-[a-z]+\//g, `"${cacheDir}/`);
if (replaced !== content) {
await fs.promises.writeFile(filePath, replaced);
patchCount++;
}
}
logger.info(`Rewrote paths in ${patchCount} modulemap files`);
}
const PATCH_RUBY_SCRIPT = `
require 'xcodeproj'
project = Xcodeproj::Project.open('ios/Pods/Pods.xcodeproj')
umbrella_targets = project.native_targets.select { |t| t.name.start_with?('Pods-') }
abort "ERROR: No Pods-* umbrella targets found!" if umbrella_targets.empty?
umbrella_names = umbrella_targets.map(&:name)
puts "Keeping umbrella targets: #{umbrella_names.join(', ')}"
pod_targets = project.native_targets.reject { |t| t.name.start_with?('Pods-') }
puts "Found #{pod_targets.size} pod targets to remove"
umbrella_targets.each do |umbrella|
deps = umbrella.dependencies.to_a
deps.each { |dep| dep.remove_from_project }
puts "Cleared #{deps.size} dependencies from #{umbrella.name}"
end
pod_targets.each do |target|
target.remove_from_project
end
project.save
puts "Saved — #{project.native_targets.size} target(s) remaining"
`;
export async function patchPodsXcodeprojAsync({
logger,
workingDirectory,
env,
cacheHit,
}: {
logger: bunyan;
workingDirectory: string;
env: Record<string, string | undefined>;
cacheHit: boolean;
}): Promise<void> {
if (env.EAS_XCODE_CACHE !== '1' || !cacheHit) {
return;
}
logger.info('Patching Pods.xcodeproj to remove pod targets...');
await spawnAsync('ruby', ['-e', PATCH_RUBY_SCRIPT], {
cwd: workingDirectory,
logger,
env,
stdio: 'pipe',
});
logger.info('Pods.xcodeproj patched successfully');
// Point PODS_CONFIGURATION_BUILD_DIR to the stable cache directory
// so Xcode finds pre-built products there instead of in DerivedData
await patchPodXcconfigAsync(workingDirectory, logger);
logger.info('Pods xcconfig patched successfully');
}
async function patchPodXcconfigAsync(workingDirectory: string, logger: bunyan): Promise<void> {
const targetSupportDir = path.join(workingDirectory, 'ios', 'Pods', 'Target Support Files');
let patchCount = 0;
const entries = await fs.promises.readdir(targetSupportDir);
for (const entry of entries) {
if (!entry.startsWith('Pods-')) {
continue;
}
const dir = path.join(targetSupportDir, entry);
const stat = await fs.promises.stat(dir);
if (!stat.isDirectory()) {
continue;
}
const files = await fs.promises.readdir(dir);
for (const file of files) {
if (!file.endsWith('.xcconfig')) {
continue;
}
const filePath = path.join(dir, file);
let content = await fs.promises.readFile(filePath, 'utf-8');
if (content.includes('PODS_CONFIGURATION_BUILD_DIR')) {
content = content.replace(
/PODS_CONFIGURATION_BUILD_DIR\s*=\s*.*/g,
`PODS_CONFIGURATION_BUILD_DIR = ${PODS_CACHE_DIR}`
);
await fs.promises.writeFile(filePath, content);
patchCount++;
logger.info(`Patched ${filePath}`);
}
}
}
logger.info(`Patched ${patchCount} xcconfig files`);
}
export async function cacheStatsAsync({
logger,
env,
@@ -1,4 +1,4 @@
import { Platform } from '@expo/eas-build-job';
import { Ios, Platform } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { asyncResult } from '@expo/results';
import {
@@ -9,9 +9,11 @@ import {
} from '@expo/steps';
import fs from 'fs';
import nullthrows from 'nullthrows';
import path from 'path';
import { compressCacheAsync, uploadCacheAsync } from './saveCache';
import { generateDefaultBuildCacheKeyAsync, getCcachePath } from '../../utils/cacheKey';
import { generateXcodeCacheKeyAsync } from '../../utils/xcodeCacheKey';
export function createSaveBuildCacheFunction(evictUsedBefore: Date): BuildFunction {
return new BuildFunction({
@@ -38,6 +40,17 @@ export function createSaveBuildCacheFunction(evictUsedBefore: Date): BuildFuncti
);
}
if (platform === Platform.IOS) {
const simulator = (stepCtx.global.staticContext.job as Ios.Job).simulator;
await saveXcodeCacheAsync({
logger,
workingDirectory,
env,
secrets: stepCtx.global.staticContext.job.secrets,
simulator,
});
}
await saveCcacheAsync({
logger,
workingDirectory,
@@ -135,3 +148,121 @@ export async function saveCcacheAsync({
logger.error({ err }, 'Failed to save cache');
}
}
export async function saveXcodeCacheAsync({
logger,
workingDirectory,
env,
secrets,
simulator,
}: {
logger: bunyan;
workingDirectory: string;
env: Record<string, string | undefined>;
secrets?: { robotAccessToken?: string };
simulator?: boolean;
}): Promise<void> {
if (env.EAS_XCODE_CACHE !== '1') {
return;
}
const productsPath = await findBuildProductsPathAsync(workingDirectory, logger);
if (!productsPath) {
logger.warn('No build products found, skipping Xcode cache save');
return;
}
logger.info(`Found build products at: ${productsPath}`);
const cachePaths = ['pods-products-v2'];
try {
const cacheKey = await generateXcodeCacheKeyAsync(workingDirectory, simulator);
logger.info(`Saving Xcode cache key: ${cacheKey}`);
const jobId = nullthrows(env.EAS_BUILD_ID, 'EAS_BUILD_ID is not set');
const robotAccessToken = nullthrows(
secrets?.robotAccessToken,
'Robot access token is required for cache operations'
);
const expoApiServerURL = nullthrows(env.__API_SERVER_URL, '__API_SERVER_URL is not set');
logger.info('Compressing Xcode build products...');
const { archivePath } = await compressCacheAsync({
paths: ['.'],
workingDirectory: productsPath,
verbose: env.EXPO_DEBUG === '1',
logger,
});
const { size } = await fs.promises.stat(archivePath);
await uploadCacheAsync({
logger,
jobId,
expoApiServerURL,
robotAccessToken,
archivePath,
key: cacheKey,
paths: cachePaths,
size,
platform: Platform.IOS,
});
logger.info('Xcode cache saved successfully');
} catch (err) {
logger.error({ err }, 'Failed to save Xcode cache');
}
}
async function findBuildProductsPathAsync(
workingDirectory: string,
logger: bunyan
): Promise<string | null> {
const iosBuildDir = path.join(workingDirectory, 'ios', 'build');
// Archive build: Build/Intermediates.noindex/ArchiveIntermediates/<AppName>/BuildProductsPath/Release-iphoneos/
const archiveIntermediatesDir = path.join(
iosBuildDir,
'Build',
'Intermediates.noindex',
'ArchiveIntermediates'
);
try {
const entries = await fs.promises.readdir(archiveIntermediatesDir);
for (const entry of entries) {
const buildProductsPath = path.join(archiveIntermediatesDir, entry, 'BuildProductsPath');
try {
const configs = await fs.promises.readdir(buildProductsPath);
const releaseDir = configs.find(c => c.startsWith('Release-'));
if (releaseDir) {
const fullPath = path.join(buildProductsPath, releaseDir);
logger.info(`Found archive build products: ${fullPath}`);
return fullPath;
}
} catch {
// No BuildProductsPath in this entry
}
}
} catch {
// No ArchiveIntermediates directory
}
// Simulator build: Build/Products/Release-iphonesimulator/
const productsDir = path.join(iosBuildDir, 'Build', 'Products');
try {
const configs = await fs.promises.readdir(productsDir);
const releaseDir = configs.find(c => c.startsWith('Release-'));
if (releaseDir) {
const fullPath = path.join(productsDir, releaseDir);
logger.info(`Found simulator build products: ${fullPath}`);
return fullPath;
}
} catch {
// No Products directory
}
logger.info('No build products found');
return null;
}
@@ -1,4 +1,4 @@
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import { UserError } from '@expo/eas-build-job';
import { asyncResult } from '@expo/results';
import {
BuildFunction,
@@ -272,7 +272,7 @@ export function createUploadToAscBuildFunction(): BuildFunction {
? ipaInfoResult.value.bundleIdentifier
: null;
throw new UserFacingError(
throw new UserError(
'EAS_UPLOAD_TO_ASC_INVALID_BUNDLE_ID',
`Build upload was rejected by App Store Connect because the app bundle identifier in the IPA does not match the selected App Store Connect app.\n\n` +
`IPA bundle identifier: ${ipaBundleIdentifier ?? '(unavailable)'}\n` +
@@ -284,7 +284,7 @@ export function createUploadToAscBuildFunction(): BuildFunction {
}
if (isMissingPurposeStringError(errors)) {
const missingUsageDescriptionKeys = parseMissingUsageDescriptionKeys(errors);
throw new UserFacingError(
throw new UserError(
'EAS_UPLOAD_TO_ASC_MISSING_PURPOSE_STRING',
`Build upload was rejected by App Store Connect because Info.plist is missing one or more privacy purpose strings.\n\n` +
`${
@@ -303,7 +303,7 @@ export function createUploadToAscBuildFunction(): BuildFunction {
);
}
if (isClosedVersionTrainError(errors)) {
throw new UserFacingError(
throw new UserError(
'EAS_UPLOAD_TO_ASC_CLOSED_VERSION_TRAIN',
`Build upload was rejected by App Store Connect because the ${bundleShortVersion} app version is not accepted for new build submissions. ` +
'This usually means the version train is closed or lower than a previously approved version. ' +
@@ -1,4 +1,4 @@
import { UserFacingError } from '@expo/eas-build-job/dist/errors';
import { UserError } from '@expo/eas-build-job';
import {
AscApiClient,
@@ -39,7 +39,7 @@ export namespace AscApiUtils {
// Don't hide the original NOT_FOUND error with a secondary lookup failure.
throw error;
}
throw new UserFacingError(
throw new UserError(
'EAS_UPLOAD_TO_ASC_APP_NOT_FOUND',
`App Store Connect app for application identifier ${appleAppIdentifier} was not found. ` +
'Verify the configured application identifier and that the App Store Connect API key has access to the application in the correct App Store Connect account.' +
@@ -94,7 +94,7 @@ export namespace AscApiUtils {
errors.every(item => item.code === 'ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE');
if (isDuplicateVersionError) {
throw new UserFacingError(
throw new UserError(
'EAS_UPLOAD_TO_ASC_VERSION_DUPLICATE',
`Increment Build Number: Build number ${bundleVersion} for app version ${bundleShortVersion} has already been used. ` +
'App Store Connect requires unique build numbers within each app version (version train). ' +
@@ -24,7 +24,7 @@ describe('AscApiUtils', () => {
).resolves.toEqual(response);
});
it('throws UserFacingError with visible apps when app id is not found', async () => {
it('throws UserError with visible apps when app id is not found', async () => {
const notFoundPayload = {
errors: [
{
@@ -97,7 +97,7 @@ describe('AscApiUtils', () => {
});
describe('createBuildUploadAsync', () => {
it('throws UserFacingError when ASC duplicate version error is returned', async () => {
it('throws UserError when ASC duplicate version error is returned', async () => {
const payload = {
errors: [
{
@@ -17,6 +17,8 @@ export_options({
export_xcargs "OTHER_CODE_SIGN_FLAGS=\\"--keychain <%- KEYCHAIN_PATH %>\\""
derived_data_path("<%- DERIVED_DATA_PATH %>")
disable_xcpretty(true)
buildlog_path("<%- LOGS_DIRECTORY %>")
@@ -1,10 +1,13 @@
import { StepMetricsCollection } from '@expo/steps';
import { StepMetric } from '@expo/steps';
import { randomUUID } from 'crypto';
import { uploadStepMetricsToWwwAsync } from '../stepMetrics';
import { turtleFetch } from '../turtleFetch';
jest.mock('../turtleFetch');
jest.mock('../turtleFetch', () => ({
...jest.requireActual('../turtleFetch'),
turtleFetch: jest.fn(),
}));
const mockTurtleFetch = turtleFetch as jest.MockedFunction<typeof turtleFetch>;
describe(uploadStepMetricsToWwwAsync, () => {
@@ -23,44 +26,52 @@ describe(uploadStepMetricsToWwwAsync, () => {
jest.clearAllMocks();
});
it('uploads step metrics to www', async () => {
const stepMetrics: StepMetricsCollection = [
{ metricsId: 'eas/checkout', result: 'success', durationMs: 1000, platform: 'linux' },
{
metricsId: 'eas/install_node_modules',
result: 'failed',
durationMs: 5000,
platform: 'linux',
},
];
it('uploads step metrics', async () => {
const stepMetric: StepMetric = {
metricsId: 'eas/checkout',
result: 'success',
durationMs: 1000,
platform: 'linux',
};
await uploadStepMetricsToWwwAsync({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl,
stepMetrics,
stepMetrics: [stepMetric],
logger: mockLogger,
});
expect(mockTurtleFetch).toHaveBeenCalledTimes(1);
expect(mockTurtleFetch).toHaveBeenCalledWith(
`${expoApiV2BaseUrl}workflows/${workflowJobId}/metrics`,
'POST',
expect.objectContaining({
json: { stepMetrics },
json: { stepMetrics: [stepMetric] },
headers: { Authorization: `Bearer ${robotAccessToken}` },
retries: 2,
})
);
});
it('does nothing when stepMetrics is empty', async () => {
await uploadStepMetricsToWwwAsync({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl,
stepMetrics: [],
logger: mockLogger,
});
it('silently gives up on failure', async () => {
mockTurtleFetch.mockRejectedValue(new Error('persistent failure'));
expect(mockTurtleFetch).not.toHaveBeenCalled();
const stepMetric: StepMetric = {
metricsId: 'eas/checkout',
result: 'failed',
durationMs: 500,
platform: 'darwin',
};
await expect(
uploadStepMetricsToWwwAsync({
workflowJobId,
robotAccessToken,
expoApiV2BaseUrl,
stepMetrics: [stepMetric],
logger: mockLogger,
})
).resolves.not.toThrow();
});
});
+6 -13
View File
@@ -1,5 +1,5 @@
import { bunyan } from '@expo/logger';
import { StepMetricsCollection } from '@expo/steps';
import { StepMetric } from '@expo/steps';
import { turtleFetch } from './turtleFetch';
@@ -13,29 +13,22 @@ export async function uploadStepMetricsToWwwAsync({
workflowJobId: string;
robotAccessToken: string;
expoApiV2BaseUrl: string;
stepMetrics: StepMetricsCollection;
stepMetrics: StepMetric[];
logger: bunyan;
}): Promise<void> {
if (stepMetrics.length === 0) {
logger.debug('No step metrics to upload');
return;
}
try {
await turtleFetch(
new URL(`workflows/${workflowJobId}/metrics`, expoApiV2BaseUrl).toString(),
'POST',
{
json: { stepMetrics },
headers: {
Authorization: `Bearer ${robotAccessToken}`,
},
timeout: 20000,
headers: { Authorization: `Bearer ${robotAccessToken}` },
timeout: 5000,
retries: 2,
logger,
}
);
logger.info(`Uploaded ${stepMetrics.length} step metrics`);
} catch {
// Don't display unactionable error to the user, let's send it to Sentry in the future
// Don't fail the build for metrics — silently give up
}
}
@@ -0,0 +1,23 @@
import * as PackageManagerUtils from '@expo/package-manager';
import { hashFiles } from '@expo/steps';
import path from 'path';
import { findPackagerRootDir } from './packageManager';
export const XCODE_CACHE_KEY_PREFIX = 'ios-xcode-cache-';
export async function generateXcodeCacheKeyAsync(
workingDirectory: string,
simulator?: boolean
): Promise<string> {
const packagerRunDir = findPackagerRootDir(workingDirectory);
const manager = PackageManagerUtils.createForProject(packagerRunDir);
const lockPath = path.join(packagerRunDir, manager.lockFile);
const variant = simulator ? 'sim' : 'device';
try {
return `${XCODE_CACHE_KEY_PREFIX}${variant}-${hashFiles([lockPath])}`;
} catch (err: any) {
throw new Error(`Failed to read lockfile for Xcode cache key generation: ${err.message}`);
}
}
@@ -1,4 +1,4 @@
import { BuildError, ExpoError, UserFacingError } from '../errors';
import { BuildError, ExpoError, UserError } from '../errors';
import { BuildPhase } from '../logs';
class TestExpoError extends ExpoError {
@@ -56,9 +56,9 @@ describe(BuildError, () => {
});
});
describe(UserFacingError, () => {
describe(UserError, () => {
it('supports docsUrl in options', () => {
const error = new UserFacingError('ERR_CODE', 'message', {
const error = new UserError('ERR_CODE', 'message', {
docsUrl: 'https://docs.example.dev',
});
@@ -69,14 +69,14 @@ describe(UserFacingError, () => {
it('supports cause in options', () => {
const cause = new Error('root cause');
const error = new UserFacingError('ERR_CODE', 'message', { cause });
const error = new UserError('ERR_CODE', 'message', { cause });
expect(error.cause).toBe(cause);
});
it('supports docsUrl, metadata, and cause in options', () => {
const cause = new Error('root cause');
const error = new UserFacingError('ERR_CODE', 'message', {
const error = new UserError('ERR_CODE', 'message', {
docsUrl: 'https://docs.example.dev',
metadata: { packageName: 'expo' },
cause,
+3 -3
View File
@@ -72,7 +72,7 @@ export class BuildError<
}
}
export class UserFacingError<
export class UserError<
TMetadata extends ErrorMetadata = ErrorMetadata,
> extends ExpoError<TMetadata> {
constructor(
@@ -93,7 +93,7 @@ export class UserFacingError<
}
}
export class UnknownError extends UserFacingError {
export class UnknownError extends UserError {
constructor(buildPhase?: BuildPhase) {
super(
ErrorCode.UNKNOWN_ERROR,
@@ -124,7 +124,7 @@ export class UnknownCustomBuildError extends BuildError {
}
}
export class CredentialsDistCertMismatchError extends UserFacingError {
export class CredentialsDistCertMismatchError extends UserError {
constructor(message: string) {
super('EAS_BUILD_CREDENTIALS_DIST_CERT_MISMATCH', message);
}
+1
View File
@@ -20,6 +20,7 @@ export {
export { Metadata, sanitizeMetadata } from './metadata';
export * from './job';
export * from './logs';
export * from './errors';
export * as errors from './errors';
export * from './artifacts';
export * from './context';
+4 -8
View File
@@ -8,7 +8,7 @@ import { v4 as uuidv4 } from 'uuid';
import { BuildRuntimePlatform } from './BuildRuntimePlatform';
import { BuildStep, BuildStepOutputAccessor, SerializedBuildStepOutputAccessor } from './BuildStep';
import { BuildStepEnv } from './BuildStepEnv';
import { StepMetricInput, StepMetricsCollection } from './StepMetrics';
import { StepMetric, StepMetricInput } from './StepMetrics';
import { BuildStepRuntimeError } from './errors';
import { hashFiles } from './utils/hashFiles';
import {
@@ -40,6 +40,7 @@ export interface ExternalBuildContextProvider {
readonly env: BuildStepEnv;
updateEnv(env: BuildStepEnv): void;
reportStepMetric?(metric: StepMetric): void;
}
export interface SerializedBuildStepGlobalContext {
@@ -56,8 +57,6 @@ export class BuildStepGlobalContext {
private didCheckOut = false;
private _hasAnyPreviousStepFailed = false;
private stepById: Record<string, BuildStepOutputAccessor> = {};
private readonly _stepMetrics: StepMetricsCollection = [];
constructor(
private readonly provider: ExternalBuildContextProvider,
public readonly skipCleanup: boolean
@@ -183,12 +182,9 @@ export class BuildStepGlobalContext {
this._hasAnyPreviousStepFailed = true;
}
public get stepMetrics(): StepMetricsCollection {
return this._stepMetrics;
}
public addStepMetric(metric: StepMetricInput): void {
this._stepMetrics.push({ ...metric, platform: this.runtimePlatform });
const stepMetric: StepMetric = { ...metric, platform: this.runtimePlatform };
this.provider.reportStepMetric?.(stepMetric);
}
public wasCheckedOut(): boolean {
-2
View File
@@ -9,5 +9,3 @@ export type StepMetricInput = {
export type StepMetric = StepMetricInput & {
platform: 'darwin' | 'linux';
};
export type StepMetricsCollection = StepMetric[];
@@ -4,6 +4,7 @@ import { createGlobalContextMock } from './utils/context';
import { BuildRuntimePlatform } from '../BuildRuntimePlatform';
import { BuildStep } from '../BuildStep';
import { BuildWorkflow } from '../BuildWorkflow';
import { StepMetric } from '../StepMetrics';
describe(BuildWorkflow, () => {
describe(BuildWorkflow.prototype.executeAsync, () => {
@@ -159,6 +160,19 @@ describe(BuildWorkflow, () => {
});
describe('step metrics collection', () => {
function createContextWithMetricCollector(
params: { runtimePlatform?: BuildRuntimePlatform } = {}
): { ctx: ReturnType<typeof createGlobalContextMock>; collected: StepMetric[] } {
const collected: StepMetric[] = [];
const ctx = createGlobalContextMock({
...params,
reportStepMetric: metric => {
collected.push(metric);
},
});
return { ctx, collected };
}
it('collects metrics for steps with __metricsId', async () => {
const mockBuildStep = mock<BuildStep>();
when(mockBuildStep.shouldExecuteStep()).thenReturn(true);
@@ -167,17 +181,19 @@ describe(BuildWorkflow, () => {
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock({ runtimePlatform: BuildRuntimePlatform.LINUX });
const { ctx, collected } = createContextWithMetricCollector({
runtimePlatform: BuildRuntimePlatform.LINUX,
});
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await workflow.executeAsync();
expect(ctx.stepMetrics).toHaveLength(1);
expect(ctx.stepMetrics[0]).toMatchObject({
expect(collected).toHaveLength(1);
expect(collected[0]).toMatchObject({
metricsId: 'test-step-metrics',
result: 'success',
platform: 'linux',
});
expect(ctx.stepMetrics[0].durationMs).toBeGreaterThanOrEqual(0);
expect(collected[0].durationMs).toBeGreaterThanOrEqual(0);
});
it('does not collect metrics for steps without __metricsId', async () => {
@@ -188,11 +204,11 @@ describe(BuildWorkflow, () => {
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock();
const { ctx, collected } = createContextWithMetricCollector();
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await workflow.executeAsync();
expect(ctx.stepMetrics).toHaveLength(0);
expect(collected).toHaveLength(0);
});
it('collects failed result when step throws', async () => {
@@ -203,17 +219,19 @@ describe(BuildWorkflow, () => {
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock({ runtimePlatform: BuildRuntimePlatform.DARWIN });
const { ctx, collected } = createContextWithMetricCollector({
runtimePlatform: BuildRuntimePlatform.DARWIN,
});
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await expect(workflow.executeAsync()).rejects.toThrowError('Step failed');
expect(ctx.stepMetrics).toHaveLength(1);
expect(ctx.stepMetrics[0]).toMatchObject({
expect(collected).toHaveLength(1);
expect(collected[0]).toMatchObject({
metricsId: 'failing-step-metrics',
result: 'failed',
platform: 'darwin',
});
expect(ctx.stepMetrics[0].durationMs).toBeGreaterThanOrEqual(0);
expect(collected[0].durationMs).toBeGreaterThanOrEqual(0);
});
it('does not collect metrics when step is skipped', async () => {
@@ -223,13 +241,13 @@ describe(BuildWorkflow, () => {
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock();
const { ctx, collected } = createContextWithMetricCollector();
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await workflow.executeAsync();
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
verify(mockBuildStep.skip()).once();
expect(ctx.stepMetrics).toHaveLength(0);
expect(collected).toHaveLength(0);
});
it('collects metrics with darwin platform when runtimePlatform is darwin', async () => {
@@ -240,12 +258,14 @@ describe(BuildWorkflow, () => {
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock({ runtimePlatform: BuildRuntimePlatform.DARWIN });
const { ctx, collected } = createContextWithMetricCollector({
runtimePlatform: BuildRuntimePlatform.DARWIN,
});
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await workflow.executeAsync();
expect(ctx.stepMetrics).toHaveLength(1);
expect(ctx.stepMetrics[0].platform).toBe('darwin');
expect(collected).toHaveLength(1);
expect(collected[0].platform).toBe('darwin');
});
it('collects metrics for multiple steps', async () => {
@@ -271,13 +291,27 @@ describe(BuildWorkflow, () => {
instance(mockBuildStep3),
];
const ctx = createGlobalContextMock({ runtimePlatform: BuildRuntimePlatform.LINUX });
const { ctx, collected } = createContextWithMetricCollector({
runtimePlatform: BuildRuntimePlatform.LINUX,
});
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await workflow.executeAsync();
expect(ctx.stepMetrics).toHaveLength(2);
expect(ctx.stepMetrics[0].metricsId).toBe('step-1');
expect(ctx.stepMetrics[1].metricsId).toBe('step-3');
expect(collected).toHaveLength(2);
expect(collected[0].metricsId).toBe('step-1');
expect(collected[1].metricsId).toBe('step-3');
});
it('does not throw when reportStepMetric is not provided on the provider', async () => {
const mockBuildStep = mock<BuildStep>();
when(mockBuildStep.shouldExecuteStep()).thenReturn(true);
when(mockBuildStep.__metricsId).thenReturn('no-callback-test');
const buildSteps: BuildStep[] = [instance(mockBuildStep)];
const ctx = createGlobalContextMock();
const workflow = new BuildWorkflow(ctx, { buildSteps, buildFunctions: {} });
await expect(workflow.executeAsync()).resolves.not.toThrow();
});
});
});
+18 -13
View File
@@ -12,9 +12,11 @@ import {
ExternalBuildContextProvider,
} from '../../BuildStepContext';
import { BuildStepEnv } from '../../BuildStepEnv';
import { StepMetric } from '../../StepMetrics';
export class MockContextProvider implements ExternalBuildContextProvider {
private _env: BuildStepEnv = {};
public reportStepMetric?: (metric: StepMetric) => void;
constructor(
public readonly logger: bunyan,
@@ -45,6 +47,7 @@ interface BuildContextParams {
projectTargetDirectory?: string;
relativeWorkingDirectory?: string;
staticContextContent?: JobInterpolationContext;
reportStepMetric?: (metric: StepMetric) => void;
}
export function createStepContextMock({
@@ -81,21 +84,23 @@ export function createGlobalContextMock({
projectTargetDirectory,
relativeWorkingDirectory,
staticContextContent,
reportStepMetric,
}: BuildContextParams = {}): BuildStepGlobalContext {
const resolvedProjectTargetDirectory =
projectTargetDirectory ?? path.join(os.tmpdir(), 'eas-build', uuidv4());
return new BuildStepGlobalContext(
new MockContextProvider(
logger ?? createMockLogger(),
runtimePlatform ?? BuildRuntimePlatform.LINUX,
projectSourceDirectory ?? '/non/existent/dir',
resolvedProjectTargetDirectory,
relativeWorkingDirectory
? path.resolve(resolvedProjectTargetDirectory, relativeWorkingDirectory)
: resolvedProjectTargetDirectory,
'/non/existent/dir',
staticContextContent ?? ({} as JobInterpolationContext)
),
skipCleanup ?? false
const provider = new MockContextProvider(
logger ?? createMockLogger(),
runtimePlatform ?? BuildRuntimePlatform.LINUX,
projectSourceDirectory ?? '/non/existent/dir',
resolvedProjectTargetDirectory,
relativeWorkingDirectory
? path.resolve(resolvedProjectTargetDirectory, relativeWorkingDirectory)
: resolvedProjectTargetDirectory,
'/non/existent/dir',
staticContextContent ?? ({} as JobInterpolationContext)
);
if (reportStepMetric) {
provider.reportStepMetric = reportStepMetric;
}
return new BuildStepGlobalContext(provider, skipCleanup ?? false);
}
+1 -1
View File
@@ -16,4 +16,4 @@ export * from './interpolation';
export * from './utils/shell/spawn';
export * from './utils/jsepEval';
export * from './utils/hashFiles';
export { StepMetric, StepMetricResult, StepMetricsCollection } from './StepMetrics';
export { StepMetric, StepMetricResult } from './StepMetrics';
@@ -350,10 +350,7 @@ describe('State sync mechanism', () => {
it('should expose user-facing error from generic job', async () => {
jest.mocked(runGenericJobAsync).mockResolvedValueOnce({
runResult: result(
new errors.UserFacingError(
genericJobRunErrorCode,
'ASC app was not found for this account.'
)
new errors.UserError(genericJobRunErrorCode, 'ASC app was not found for this account.')
),
buildWorkflow: {} as any,
});
+1 -3
View File
@@ -64,9 +64,7 @@ export async function build({
case undefined: {
artifacts = {};
const buildCtx = ctx as BuildContext<Generic.Job>;
const { runResult } = await runGenericJobAsync(buildCtx, {
expoApiV2BaseUrl: config.wwwApiV2BaseUrl,
});
const { runResult } = await runGenericJobAsync(buildCtx);
if (!runResult.ok) {
throw runResult.reason;
+1
View File
@@ -89,6 +89,7 @@ export function createBuildContext<TJob extends Job>({
cacheManager: new GCSCacheManager(),
metadata,
reportBuildPhaseStats: reportBuildPhaseStatsFn,
expoApiV2BaseUrl: config.wwwApiV2BaseUrl,
});
return ctx;
}
+1 -1
View File
@@ -9,7 +9,7 @@ import { v4 as uuidv4 } from 'uuid';
import config from './config';
class SystemDepsInstallError extends errors.UserFacingError {
class SystemDepsInstallError extends errors.UserError {
constructor(dependency: string) {
super(
'EAS_BUILD_SYSTEM_DEPS_INSTALL_ERROR',
+1 -1
View File
@@ -374,7 +374,7 @@ function toBuildError(error: unknown, job: Job): errors.BuildError {
return error;
}
if (error instanceof errors.UserFacingError) {
if (error instanceof errors.UserError) {
return new errors.BuildError(error.message, {
errorCode: error.errorCode,
docsUrl: error.docsUrl,