mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-22 21:31:15 -10:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86bb93bf27 | ||
|
|
70a1704507 | ||
|
|
666933ca60 | ||
|
|
053c6ebf65 | ||
|
|
f9d961b978 | ||
|
|
be073d8e10 | ||
|
|
3b3046ada5 | ||
|
|
87ad87177e | ||
|
|
6923c416d6 | ||
|
|
f27e7988a1 | ||
|
|
b4e4229464 | ||
|
|
a04489e678 | ||
|
|
4b6fd3c942 | ||
|
|
e34c0cb3f6 | ||
|
|
c7f766568c | ||
|
|
a328e59ee4 | ||
|
|
f843a97165 | ||
|
|
1e112fee24 | ||
|
|
6d3e79c255 | ||
|
|
04e909c4d9 | ||
|
|
1a6e94123a | ||
|
|
544cd18bac | ||
|
|
8dc514e9f2 | ||
|
|
f4b4f035b0 | ||
|
|
92397fd3d4 | ||
|
|
154d90d3ce | ||
|
|
5a0908533b | ||
|
|
14e9f1af44 | ||
|
|
291ec6f2c8 | ||
|
|
a4edee8178 | ||
|
|
6fa3f47f91 | ||
|
|
71338cbaa2 | ||
|
|
36f83dee90 | ||
|
|
352c3b68f0 | ||
|
|
5dafefd484 | ||
|
|
b7ff9b10d8 | ||
|
|
55d1e2942d | ||
|
|
a7f9742a03 | ||
|
|
f615fc5ba3 | ||
|
|
00ef775b2b | ||
|
|
e914819052 | ||
|
|
ab32f0c241 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Count Android web preview input as session activity, so `max_idle_time_minutes` works on Android sessions. `eas/start_serve_sim_remote_session` no longer rejects it on Android; the API does not accept an idle timeout for Android web-preview-only sessions yet.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Accept `issue_comment` as a `github.event_name` value in the workflow interpolation context.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the native job schema for Android, with the `builder` field.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add `builder` to the build metadata.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the `NativeBuilder` enum.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Add the step function that signs and builds a native iOS project with fastlane gym.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/eas-build-job': minor
|
||||
---
|
||||
|
||||
Add the native job schema for iOS: `builder`, `projectFile`, and `secrets.credentialsByBundleIdentifier`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Add the step function that verifies the artifact of a native iOS build.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Add the step functions that install pods and detect the Xcode project for a native iOS build.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': none
|
||||
---
|
||||
|
||||
Extract the custom build project preparation into `prepareProjectForStepsAsync`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Add start and collect steps that attach serve-sim simulator crash reports to device run sessions as IPS files.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Add start and collect steps that attach serve-sim network captures to device run sessions as HAR files.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Mark the default device for each platform in `eas simulator:devices` and include `isDefault` in JSON output.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
A successful remote device run session no longer fails when its agent-device, Appium, or Argent tunnel does not stop within its time-out.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Build a native iOS project with Xcode when the build job carries `builder: xcode`.
|
||||
@@ -22,9 +22,3 @@ rules:
|
||||
mentions: ['kitten', 'kadikraman']
|
||||
- patterns: ['packages/eas-cli/src/commands/deploy/**']
|
||||
mentions: ['kitten', 'kadikraman']
|
||||
- patterns: ['packages/eas-cli/src/commands/build/**']
|
||||
mentions: ['sjchmiela']
|
||||
- patterns: ['packages/eas-cli/src/build/**']
|
||||
mentions: ['sjchmiela']
|
||||
- patterns: ['packages/eas-cli/src/commands/workflow/**']
|
||||
mentions: ['sjchmiela']
|
||||
@@ -83,8 +83,8 @@ jobs:
|
||||
git push --force-with-lease origin "$branch"
|
||||
|
||||
if gh pr view "$branch" --json state --jq '.state' 2>/dev/null | grep -q OPEN; then
|
||||
gh pr edit "$branch" --title "$title" --body "$body" --add-reviewer sjchmiela
|
||||
gh pr edit "$branch" --title "$title" --body "$body"
|
||||
else
|
||||
gh pr create --base main --head "$branch" --title "$title" --body "$body" \
|
||||
--label 'no changelog' --reviewer sjchmiela
|
||||
--label 'no changelog'
|
||||
fi
|
||||
@@ -2,6 +2,55 @@
|
||||
|
||||
This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
## [27.10.0](https://github.com/expo/eas-cli/releases/tag/v27.10.0) - 2026-11-13
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [build-tools] Add the experimental `experimental_emulator_capture_version` input to `eas/start_android_emulator`. The Android Emulator then preloads that version of the `expo-emulator-capture` agent and uses the lavapipe renderer, and later steps start expo-device-hub with the emulator capture on. When the agent cannot install, the emulator starts as before. Only web preview sessions support the capture for now, so other session types fail with an error when the input is set. ([#4827](https://github.com/expo/eas-cli/pull/4827) by [@krystofwoldrich-agent](https://github.com/krystofwoldrich-agent))
|
||||
- [eas-cli] Add `eas simulator:devices` to list the devices Expo suggests for a simulator session. ([#4879](https://github.com/expo/eas-cli/pull/4879) by [@brentvatne](https://github.com/brentvatne))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [build-tools] Retry the first ngrok tunnel open of a device run session up to two times when ngrok rejects it with ERR_NGROK_802. The first open now waits 19 seconds instead of 15, so a tunnel that opens late is kept instead of closed. Startup can be cancelled during the retries, and a preview tunnel stops retrying when its session host finishes. ([#4874](https://github.com/expo/eas-cli/pull/4874) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- [eas-cli] Include the parent CLI command in telemetry to distinguish nested commands from direct usage. ([#4876](https://github.com/expo/eas-cli/pull/4876) by [@davidmokos](https://github.com/davidmokos))
|
||||
- [build-tools] Run worker SSH sessions as detached upterm sessions that reconnect on their own under the same session ID, and stop them with `upterm session stop`. ([#4857](https://github.com/expo/eas-cli/pull/4857) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
- [build-tools] Run the command a client passes with `eas workflow:ssh <id> <command>` in worker SSH sessions, in the build directory. ([#4863](https://github.com/expo/eas-cli/pull/4863) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
- [build-tools] Always download upterm for worker SSH sessions instead of using an `upterm` found on `PATH`. ([#4859](https://github.com/expo/eas-cli/pull/4859) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
- [eas-cli][build-tools] Bump Node.js to 22.23.5 to fix the CVEs in the [November 2026 Node.js security releases](https://nodejs.org/en/blog/vulnerability/november-2026-security-releases). ([#4889](https://github.com/expo/eas-cli/pull/4889) by [@ramonclaudio](https://github.com/ramonclaudio))
|
||||
|
||||
## [27.9.0](https://github.com/expo/eas-cli/releases/tag/v27.9.0) - 2026-11-12
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [eas-cli] Warn about Expo Simulators and EAS Workflows outages from status.expo.dev before `eas simulator:start` creates a session, and describe degraded performance and maintenance correctly in all outage warnings. ([#4873](https://github.com/expo/eas-cli/pull/4873) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
|
||||
## [27.8.0](https://github.com/expo/eas-cli/releases/tag/v27.8.0) - 2026-11-12
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [eas-cli] Tell accounts without EAS Simulator access that it is available on the Starter, Production, and Enterprise plans and link to the billing page, instead of pointing at the waitlist. `simulator:availability --json` now returns `billingUrl` instead of `waitlistUrl`. ([#4866](https://github.com/expo/eas-cli/pull/4866) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [build-tools] Point expo-device-hub at the scrcpy server copy in the `turtle-v2` bucket in Android device sessions, so a failed GitHub release download no longer fails the session. expo-device-hub falls back to GitHub when the copy is missing. ([#4848](https://github.com/expo/eas-cli/pull/4848) by [@sjkim-expo](https://github.com/sjkim-expo))
|
||||
- [build-tools] Fix black iOS session preview artifacts on multi-display Simulators by capturing the active display through serve-sim. ([#4777](https://github.com/expo/eas-cli/pull/4777) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
Skip automatic previews on older serve-sim versions that cannot exclude them from idle activity.
|
||||
|
||||
- [build-tools] Report flow tags with the Maestro test results of jobs that run `maestro-runner`. The tags are read from the runner's `report.json`. ([#4853](https://github.com/expo/eas-cli/pull/4853) by [@hSATAC](https://github.com/hSATAC))
|
||||
- [build-tools] Send the session preview size to `preview-upload-session` and refresh it when the size changes. ([#4864](https://github.com/expo/eas-cli/pull/4864) by [@hirbod](https://github.com/hirbod))
|
||||
- [eas-cli] Remove the "Android emulator support is still in development" warning from `eas simulator`. ([#4870](https://github.com/expo/eas-cli/pull/4870) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- [build-tools] Send the width, height and source of simulator session screenshots (manual, agent-device and Argent, including Argent screenshot diffs) as artifact metadata, read from the image header. ([#4858](https://github.com/expo/eas-cli/pull/4858) by [@hirbod](https://github.com/hirbod))
|
||||
- [eas-cli][build-tools][eas-build-job] Fix sizes of 102.4 GB and larger being printed with a value about a million times too large, and share one `formatBytes` helper between `eas-cli` and `build-tools`. ([#4854](https://github.com/expo/eas-cli/pull/4854) by [@vonovak](https://github.com/vonovak))
|
||||
- [eas-cli] Package local Simulator app bundles for upload when the host supports gzip tar archives, and reject unsupported IPA and ZIP installs before uploading. ([#4684](https://github.com/expo/eas-cli/pull/4684) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
Fix packaging stalls for app bundles containing hard links and clean temporary archives when interrupted. Local app directories and `.tar.gz`/`.tgz` files require a host advertising archive support.
|
||||
|
||||
- [eas-cli] Remove the `[EXPERIMENTAL]` label from `eas simulator` commands, except `eas simulator:egress` and the `--egress` flag. ([#4869](https://github.com/expo/eas-cli/pull/4869) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
|
||||
## [27.7.2](https://github.com/expo/eas-cli/releases/tag/v27.7.2) - 2026-11-10
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"STAGING": "27.7.1",
|
||||
"PRODUCTION": "27.7.1"
|
||||
"STAGING": "27.10.0",
|
||||
"PRODUCTION": "27.10.0"
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"npmClient": "yarn",
|
||||
"version": "27.7.2",
|
||||
"version": "27.10.0",
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
|
||||
}
|
||||
@@ -6,4 +6,4 @@ MISE_NODE_COREPACK = "true"
|
||||
actionlint = "1.7.12"
|
||||
gcloud = "570.0.0"
|
||||
jq = "1.8.1"
|
||||
node = "22.23.4"
|
||||
node = "22.23.5"
|
||||
@@ -1,5 +1,36 @@
|
||||
# @expo/build-tools
|
||||
|
||||
## 27.10.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add the experimental `experimental_emulator_capture_version` input to `eas/start_android_emulator`. The Android Emulator then preloads that version of the `expo-emulator-capture` agent and uses the lavapipe renderer, and later steps start expo-device-hub with the emulator capture on. When the agent cannot install, the emulator starts as before. Only web preview sessions support the capture for now, so other session types fail with an error when the input is set. ([#4827](https://github.com/expo/eas-cli/pull/4827) by [@krystofwoldrich-agent](https://github.com/krystofwoldrich-agent))
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Retry the first ngrok tunnel open of a device run session up to two times when ngrok rejects it with ERR_NGROK_802. The first open now waits 19 seconds instead of 15, so a tunnel that opens late is kept instead of closed. Startup can be cancelled during the retries, and a preview tunnel stops retrying when its session host finishes. ([#4874](https://github.com/expo/eas-cli/pull/4874) by [@szdziedzic](https://github.com/szdziedzic))
|
||||
- Run worker SSH sessions as detached upterm sessions that reconnect on their own under the same session ID, and stop them with `upterm session stop`. ([#4857](https://github.com/expo/eas-cli/pull/4857) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
- Run the command a client passes with `eas workflow:ssh <id> <command>` in worker SSH sessions, in the build directory. ([#4863](https://github.com/expo/eas-cli/pull/4863) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
- Always download upterm for worker SSH sessions instead of using an `upterm` found on `PATH`. ([#4859](https://github.com/expo/eas-cli/pull/4859) by [@AHGIJMKLKKZNPJKQR](https://github.com/AHGIJMKLKKZNPJKQR))
|
||||
|
||||
## 27.9.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.8.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Point expo-device-hub at the scrcpy server copy in the `turtle-v2` bucket in Android device sessions, so a failed GitHub release download no longer fails the session. expo-device-hub falls back to GitHub when the copy is missing. ([#4848](https://github.com/expo/eas-cli/pull/4848) by [@sjkim-expo](https://github.com/sjkim-expo))
|
||||
- Fix black iOS session preview artifacts on multi-display Simulators by capturing the active display through serve-sim. ([#4777](https://github.com/expo/eas-cli/pull/4777) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
Skip automatic previews on older serve-sim versions that cannot exclude them from idle activity.
|
||||
|
||||
- Report flow tags with the Maestro test results of jobs that run `maestro-runner`. The tags are read from the runner's `report.json`. ([#4853](https://github.com/expo/eas-cli/pull/4853) by [@hSATAC](https://github.com/hSATAC))
|
||||
- Send the session preview size to `preview-upload-session` and refresh it when the size changes. ([#4864](https://github.com/expo/eas-cli/pull/4864) by [@hirbod](https://github.com/hirbod))
|
||||
- Send the width, height and source of simulator session screenshots (manual, agent-device and Argent, including Argent screenshot diffs) as artifact metadata, read from the image header. ([#4858](https://github.com/expo/eas-cli/pull/4858) by [@hirbod](https://github.com/hirbod))
|
||||
- Fix sizes of 102.4 GB and larger being printed with a value about a million times too large, and share one `formatBytes` helper between `eas-cli` and `build-tools`. ([#4854](https://github.com/expo/eas-cli/pull/4854) by [@vonovak](https://github.com/vonovak))
|
||||
|
||||
## 27.7.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/build-tools",
|
||||
"version": "27.7.2",
|
||||
"version": "27.10.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -26,7 +26,7 @@
|
||||
"build:egress-guard": "resources/egress-guard/build.sh",
|
||||
"test:egress-guard": "resources/egress-guard/tests/run-policy-tests.sh && resources/egress-guard/tests/run-guard-tests.sh",
|
||||
"typecheck": "tsc",
|
||||
"generate-appium-commands": "mise exec [email protected].4 -- node scripts/generate-appium-commands.js",
|
||||
"generate-appium-commands": "mise exec [email protected].5 -- node scripts/generate-appium-commands.js",
|
||||
"prepack": "rimraf dist \"*.tsbuildinfo\" && yarn gql && tsc -p tsconfig.build.json",
|
||||
"jest-unit": "jest --config jest/unit-config.ts",
|
||||
"jest-integration": "jest --config jest/integration-config.ts",
|
||||
@@ -42,17 +42,17 @@
|
||||
"dependencies": {
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/downloader": "27.7.2",
|
||||
"@expo/eas-build-job": "27.7.2",
|
||||
"@expo/downloader": "27.10.0",
|
||||
"@expo/eas-build-job": "27.10.0",
|
||||
"@expo/env": "^0.4.0",
|
||||
"@expo/logger": "27.7.2",
|
||||
"@expo/logger": "27.10.0",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
"@expo/plist": "^0.3.5",
|
||||
"@expo/results": "^1.0.0",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "27.7.2",
|
||||
"@expo/template-file": "27.7.2",
|
||||
"@expo/turtle-spawn": "27.7.2",
|
||||
"@expo/steps": "27.10.0",
|
||||
"@expo/template-file": "27.10.0",
|
||||
"@expo/turtle-spawn": "27.10.0",
|
||||
"@expo/xcpretty": "^4.4.7",
|
||||
"@ngrok/ngrok": "1.7.0",
|
||||
"@sentry/node": "7.77.0",
|
||||
@@ -80,6 +80,7 @@
|
||||
"tar": "7.5.22",
|
||||
"uuid": "9.0.1",
|
||||
"ws": "8.21.1",
|
||||
"xcode": "^3.0.1",
|
||||
"yaml": "^2.9.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Job, Metadata } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import {
|
||||
BuildRuntimePlatform,
|
||||
@@ -75,6 +76,20 @@ export function createStepContextMock({
|
||||
});
|
||||
}
|
||||
|
||||
export function createTestBuildContext<TJob extends Job>(
|
||||
job: TJob,
|
||||
metadata?: Metadata
|
||||
): BuildContext<TJob> {
|
||||
return new BuildContext(job, {
|
||||
env: { __API_SERVER_URL: 'http://api.expo.test' },
|
||||
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
|
||||
logger: createMockLogger(),
|
||||
uploadArtifact: jest.fn(),
|
||||
workingdir: '/workingdir',
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
export function createCustomBuildContextMock(): CustomBuildContext {
|
||||
const ctx = new BuildContext(createTestIosJob({}), {
|
||||
env: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
BuildMode,
|
||||
BuildTrigger,
|
||||
Ios,
|
||||
NativeBuilder,
|
||||
Platform,
|
||||
Workflow,
|
||||
} from '@expo/eas-build-job';
|
||||
@@ -92,3 +93,31 @@ export function createTestIosJob({
|
||||
workflowInterpolationContext,
|
||||
};
|
||||
}
|
||||
|
||||
export function createTestXcodeJob(overrides: Record<string, unknown> = {}): Ios.Job {
|
||||
return {
|
||||
mode: BuildMode.BUILD,
|
||||
builder: NativeBuilder.XCODE,
|
||||
platform: Platform.IOS,
|
||||
triggeredBy: BuildTrigger.GIT_BASED_INTEGRATION,
|
||||
type: Workflow.GENERIC,
|
||||
projectArchive: {
|
||||
type: ArchiveSourceType.GIT,
|
||||
gitCommitHash: '0123456789abcdef0123456789abcdef01234567',
|
||||
gitRef: 'refs/heads/main',
|
||||
},
|
||||
projectRootDirectory: '.',
|
||||
simulator: false,
|
||||
secrets: {
|
||||
credentialsByBundleIdentifier: {
|
||||
'dev.expo.nativeapp': {
|
||||
provisioningProfileBase64: 'cHJvZmlsZQ==',
|
||||
distributionCertificate: { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' },
|
||||
},
|
||||
},
|
||||
},
|
||||
appId: randomUUID(),
|
||||
initiatingUserId: randomUUID(),
|
||||
...overrides,
|
||||
} as Ios.Job;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createTestBuildContext } from '../../__tests__/utils/context';
|
||||
import { createTestIosJob, createTestXcodeJob } from '../../__tests__/utils/job';
|
||||
import { prepareProjectSourcesAsync } from '../../common/projectSources';
|
||||
import { runBuilderWithHooksAsync } from '../common';
|
||||
import { runCustomBuildAsync } from '../custom';
|
||||
import iosBuilder from '../ios';
|
||||
|
||||
jest.mock('../common', () => ({ runBuilderWithHooksAsync: jest.fn(async () => ({})) }));
|
||||
jest.mock('../custom', () => ({ runCustomBuildAsync: jest.fn(async () => ({})) }));
|
||||
jest.mock('../../common/projectSources');
|
||||
jest.mock('../../ios/xcodeBuildLogs');
|
||||
jest.mock('../../utils/prepareBuildExecutable', () => ({ prepareExecutableAsync: jest.fn() }));
|
||||
|
||||
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(iosBuilder, () => {
|
||||
it.each([
|
||||
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
|
||||
['a builder and the custom mode', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
|
||||
['a builder and the resign mode', { mode: BuildMode.RESIGN }, '"mode" must be [build]'],
|
||||
['a builder and the repack mode', { mode: BuildMode.REPACK }, '"mode" must be [build]'],
|
||||
])(
|
||||
'fails a job with %s in the validation of the Xcode runner',
|
||||
async (_description, overrides, expectedMessage) => {
|
||||
await expect(
|
||||
iosBuilder(createTestBuildContext(createTestXcodeJob(overrides), METADATA))
|
||||
).rejects.toMatchObject({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining(expectedMessage),
|
||||
});
|
||||
expect(runCustomBuildAsync).not.toHaveBeenCalled();
|
||||
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
|
||||
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('runs a valid job with the Xcode builder through the Xcode steps', async () => {
|
||||
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
|
||||
vol.mkdirSync('/workingdir/env', { recursive: true });
|
||||
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
|
||||
return { handled: true };
|
||||
});
|
||||
const ctx = createTestBuildContext(
|
||||
createTestXcodeJob({ simulator: true, secrets: {} }),
|
||||
METADATA
|
||||
);
|
||||
|
||||
await expect(iosBuilder(ctx)).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
|
||||
});
|
||||
expect(runBuilderWithHooksAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('routes a job without a builder by its mode', async () => {
|
||||
await iosBuilder(createTestBuildContext(createTestIosJob(), METADATA));
|
||||
expect(runBuilderWithHooksAsync).toHaveBeenCalledTimes(1);
|
||||
|
||||
await iosBuilder(
|
||||
createTestBuildContext({ ...createTestIosJob(), mode: BuildMode.CUSTOM }, METADATA)
|
||||
);
|
||||
expect(runCustomBuildAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { BuildMode, Ios, Metadata } from '@expo/eas-build-job';
|
||||
import { BuildStepGlobalContext } from '@expo/steps';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createTestBuildContext } from '../../__tests__/utils/context';
|
||||
import { createTestXcodeJob } from '../../__tests__/utils/job';
|
||||
import { prepareProjectSourcesAsync } from '../../common/projectSources';
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../../ios/xcodeBuildLogs';
|
||||
import { createXcodeWorkflowAsync, runXcodeBuildAsync, validateXcodeJob } from '../xcode';
|
||||
|
||||
jest.mock('../../common/projectSources');
|
||||
jest.mock('../../ios/xcodeBuildLogs');
|
||||
|
||||
const METADATA = { appIdentifier: 'dev.expo.nativeapp' } as Metadata;
|
||||
|
||||
async function createWorkflowAsync(
|
||||
job: Ios.Job,
|
||||
metadata?: Metadata
|
||||
): ReturnType<typeof createXcodeWorkflowAsync> {
|
||||
const customBuildCtx = new CustomBuildContext(createTestBuildContext(job, metadata));
|
||||
return await createXcodeWorkflowAsync(
|
||||
new BuildStepGlobalContext(customBuildCtx, false),
|
||||
customBuildCtx
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(validateXcodeJob, () => {
|
||||
it('accepts a signed job with an app identifier, and keys the schema does not know', () => {
|
||||
expect(() =>
|
||||
validateXcodeJob(createTestXcodeJob({ keyFromANewerServer: true }), METADATA)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('accepts a simulator job without an app identifier', () => {
|
||||
expect(() =>
|
||||
validateXcodeJob(createTestXcodeJob({ simulator: true, secrets: {} }), undefined)
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unknown builder', { builder: 'unknown' }, '"builder" must be [xcode]'],
|
||||
['a mode other than build', { mode: BuildMode.CUSTOM }, '"mode" must be [build]'],
|
||||
['a field native jobs do not read', { buildProfile: 'production' }, '"buildProfile"'],
|
||||
['a value of another type', { simulator: 'false' }, '"simulator" must be a boolean'],
|
||||
['no credentials for a device build', { secrets: {} }, 'credentialsByBundleIdentifier'],
|
||||
])('rejects a job with %s', (_description, overrides, expectedMessage) => {
|
||||
expect(() => validateXcodeJob(createTestXcodeJob(overrides), METADATA)).toThrow(
|
||||
expect.objectContaining({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining(expectedMessage),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a signed job without an app identifier', () => {
|
||||
expect(() => validateXcodeJob(createTestXcodeJob(), undefined)).toThrow(
|
||||
expect.objectContaining({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
message: expect.stringContaining('app identifier'),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(createXcodeWorkflowAsync, () => {
|
||||
it('builds a valid workflow from the public and the private functions', async () => {
|
||||
const workflow = await createWorkflowAsync(createTestXcodeJob(), METADATA);
|
||||
|
||||
expect(workflow.buildSteps.map(step => step.__metricsId)).toEqual([
|
||||
'eas/checkout',
|
||||
'eas/install_native_pods',
|
||||
'eas/detect_native_xcode',
|
||||
'eas/build_native_ios',
|
||||
'eas/verify_native_ios',
|
||||
'eas/update_resolved_version',
|
||||
'eas/upload_artifact',
|
||||
]);
|
||||
});
|
||||
|
||||
it('passes the values known from the job and the metadata to detection and verification', async () => {
|
||||
const workflow = await createWorkflowAsync(
|
||||
createTestXcodeJob({
|
||||
projectFile: 'App.xcworkspace',
|
||||
scheme: 'App',
|
||||
buildConfiguration: 'Staging',
|
||||
}),
|
||||
METADATA
|
||||
);
|
||||
|
||||
const rawInputsByMetricsId = Object.fromEntries(
|
||||
workflow.buildSteps.map(step => [
|
||||
step.__metricsId,
|
||||
Object.fromEntries((step.inputs ?? []).map(input => [input.id, input.rawValue])),
|
||||
])
|
||||
);
|
||||
expect(rawInputsByMetricsId['eas/detect_native_xcode']).toEqual({
|
||||
project_file: 'App.xcworkspace',
|
||||
scheme: 'App',
|
||||
build_configuration: 'Staging',
|
||||
expected_identifier: 'dev.expo.nativeapp',
|
||||
});
|
||||
expect(rawInputsByMetricsId['eas/verify_native_ios']).toMatchObject({
|
||||
expected_identifier: 'dev.expo.nativeapp',
|
||||
});
|
||||
});
|
||||
|
||||
it('runs the after_checkout hook of the job after the checkout step', async () => {
|
||||
const workflow = await createWorkflowAsync(
|
||||
createTestXcodeJob({ hooks: { after_checkout: [{ run: 'git submodule update --init' }] } }),
|
||||
METADATA
|
||||
);
|
||||
|
||||
const checkoutStep = workflow.buildSteps.find(step => step.__metricsId === 'eas/checkout')!;
|
||||
expect(workflow.hooksByAnchorStep.get(checkoutStep)).toMatchObject({
|
||||
anchor: 'checkout',
|
||||
before: [],
|
||||
after: [expect.anything()],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(runXcodeBuildAsync, () => {
|
||||
it('validates the job before it prepares the project', async () => {
|
||||
const ctx = createTestBuildContext(createTestXcodeJob({ builder: 'unknown' }), METADATA);
|
||||
|
||||
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
|
||||
trackingCode: 'NATIVE_INVALID_JOB',
|
||||
});
|
||||
expect(prepareProjectSourcesAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs the steps, uploads the Xcode logs once and attaches the artifacts to a failure', async () => {
|
||||
jest.mocked(prepareProjectSourcesAsync).mockImplementation(async () => {
|
||||
vol.mkdirSync('/workingdir/env', { recursive: true });
|
||||
vol.fromJSON({ 'README.md': '' }, '/workingdir/temporary-custom-build');
|
||||
return { handled: true };
|
||||
});
|
||||
const ctx = createTestBuildContext(
|
||||
createTestXcodeJob({ simulator: true, secrets: {} }),
|
||||
undefined
|
||||
);
|
||||
|
||||
await expect(runXcodeBuildAsync(ctx)).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_PROJECT_FILE_NOT_FOUND',
|
||||
artifacts: ctx.artifacts,
|
||||
});
|
||||
expect(vol.existsSync('/workingdir/build/README.md')).toBe(true);
|
||||
expect(findAndUploadXcodeBuildLogsAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -9,39 +9,22 @@ import {
|
||||
errors,
|
||||
} from '@expo/steps';
|
||||
import assert from 'assert';
|
||||
import fs from 'fs/promises';
|
||||
import nullthrows from 'nullthrows';
|
||||
import path from 'path';
|
||||
|
||||
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
|
||||
import { resolveEnvFromBuildProfileAsync } from '../common/easBuildInternal';
|
||||
import { prepareProjectSourcesAsync } from '../common/projectSources';
|
||||
import { Artifacts, BuildContext } from '../context';
|
||||
import { CustomBuildContext } from '../customBuildContext';
|
||||
import { Datadog } from '../datadog';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
|
||||
import { getEasFunctionGroups } from '../steps/easFunctionGroups';
|
||||
import { getEasFunctions } from '../steps/easFunctions';
|
||||
import { retryAsync } from '../utils/retry';
|
||||
|
||||
export async function runCustomBuildAsync(ctx: BuildContext<BuildJob>): Promise<Artifacts> {
|
||||
const customBuildCtx = new CustomBuildContext(ctx);
|
||||
|
||||
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
|
||||
await retryAsync(
|
||||
async () => {
|
||||
await fs.rm(customBuildCtx.projectSourceDirectory, { recursive: true, force: true });
|
||||
await fs.mkdir(customBuildCtx.projectSourceDirectory, { recursive: true });
|
||||
|
||||
await prepareProjectSourcesAsync(ctx, customBuildCtx.projectSourceDirectory);
|
||||
},
|
||||
{
|
||||
retryOptions: {
|
||||
retries: 3,
|
||||
retryIntervalMs: 1_000,
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
|
||||
|
||||
if (ctx.job.triggeredBy === BuildTrigger.GIT_BASED_INTEGRATION) {
|
||||
// We need to setup envs from eas.json
|
||||
|
||||
@@ -6,6 +6,7 @@ import nullthrows from 'nullthrows';
|
||||
|
||||
import { runBuilderWithHooksAsync } from './common';
|
||||
import { runCustomBuildAsync } from './custom';
|
||||
import { runXcodeBuildAsync } from './xcode';
|
||||
import { eagerBundleAsync, shouldUseEagerBundle } from '../common/eagerBundle';
|
||||
import { prebuildAsync } from '../common/prebuild';
|
||||
import { JobHooksRef, setupAsync } from '../common/setup';
|
||||
@@ -48,6 +49,9 @@ const INSTALL_PODS_KILL_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
|
||||
class InstallPodsTimeoutError extends Error {}
|
||||
|
||||
export default async function iosBuilder(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
|
||||
if (ctx.job.builder !== undefined) {
|
||||
return await runXcodeBuildAsync(ctx);
|
||||
}
|
||||
if (ctx.job.mode === BuildMode.BUILD) {
|
||||
await prepareExecutableAsync(ctx);
|
||||
return await runBuilderWithHooksAsync(ctx, buildAsync);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { BuildJob, BuildPhase } from '@expo/eas-build-job';
|
||||
import fs from 'fs/promises';
|
||||
|
||||
import { prepareProjectSourcesAsync } from '../common/projectSources';
|
||||
import { BuildContext } from '../context';
|
||||
import { retryAsync } from '../utils/retry';
|
||||
|
||||
export async function prepareProjectForStepsAsync(
|
||||
ctx: BuildContext<BuildJob>,
|
||||
projectSourceDirectory: string
|
||||
): Promise<void> {
|
||||
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
|
||||
await retryAsync(
|
||||
async () => {
|
||||
await fs.rm(projectSourceDirectory, { recursive: true, force: true });
|
||||
await fs.mkdir(projectSourceDirectory, { recursive: true });
|
||||
|
||||
await prepareProjectSourcesAsync(ctx, projectSourceDirectory);
|
||||
},
|
||||
{
|
||||
retryOptions: {
|
||||
retries: 3,
|
||||
retryIntervalMs: 1_000,
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Ios, Metadata, Step, SystemError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildStepGlobalContext,
|
||||
BuildWorkflow,
|
||||
StepsConfigParser,
|
||||
createLocalCompositeFunctionLoader,
|
||||
} from '@expo/steps';
|
||||
import path from 'node:path';
|
||||
|
||||
import { prepareProjectForStepsAsync } from './prepareProjectForSteps';
|
||||
import { Artifacts, BuildContext } from '../context';
|
||||
import { CustomBuildContext } from '../customBuildContext';
|
||||
import { findAndUploadXcodeBuildLogsAsync } from '../ios/xcodeBuildLogs';
|
||||
import { getEasFunctions } from '../steps/easFunctions';
|
||||
import { createBuildNativeIosBuildFunction } from '../steps/functions/native/xcode/buildNativeIos';
|
||||
import { createDetectNativeXcodeBuildFunction } from '../steps/functions/native/xcode/detectNativeXcode';
|
||||
import { createInstallNativePodsBuildFunction } from '../steps/functions/native/xcode/installNativePods';
|
||||
import { createVerifyNativeIosBuildFunction } from '../steps/functions/native/xcode/verifyNativeIos';
|
||||
|
||||
export async function runXcodeBuildAsync(ctx: BuildContext<Ios.Job>): Promise<Artifacts> {
|
||||
validateXcodeJob(ctx.job, ctx.metadata);
|
||||
|
||||
const customBuildCtx = new CustomBuildContext(ctx);
|
||||
await prepareProjectForStepsAsync(ctx, customBuildCtx.projectSourceDirectory);
|
||||
const globalContext = new BuildStepGlobalContext(customBuildCtx, /* skipCleanup */ false);
|
||||
const workflow = await createXcodeWorkflowAsync(globalContext, customBuildCtx);
|
||||
try {
|
||||
await workflow.executeAsync();
|
||||
} catch (err: any) {
|
||||
err.artifacts = ctx.artifacts;
|
||||
throw err;
|
||||
} finally {
|
||||
await findAndUploadXcodeBuildLogsAsync(ctx, { logger: ctx.logger });
|
||||
await customBuildCtx.drainPendingMetricUploads();
|
||||
}
|
||||
return ctx.artifacts;
|
||||
}
|
||||
|
||||
export function validateXcodeJob(job: Ios.Job, metadata: Metadata | undefined): void {
|
||||
const { error } = Ios.JobSchema.validate(job, {
|
||||
allowUnknown: true,
|
||||
convert: false,
|
||||
abortEarly: false,
|
||||
});
|
||||
if (error) {
|
||||
throw new SystemError(
|
||||
`EAS created an Xcode build job that is not valid: ${error.message}. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.`,
|
||||
{ trackingCode: 'NATIVE_INVALID_JOB', cause: error }
|
||||
);
|
||||
}
|
||||
if (!job.simulator && !metadata?.appIdentifier) {
|
||||
throw new SystemError(
|
||||
'EAS created an Xcode build job for devices without the app identifier that the signed app must have. Your project did not cause this. Run the build again, and contact Expo support if it keeps failing.',
|
||||
{ trackingCode: 'NATIVE_INVALID_JOB' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createXcodeWorkflowAsync(
|
||||
globalContext: BuildStepGlobalContext,
|
||||
customBuildCtx: CustomBuildContext<Ios.Job>
|
||||
): Promise<BuildWorkflow> {
|
||||
const { job, metadata } = customBuildCtx;
|
||||
const steps: Step[] = [
|
||||
{ uses: 'eas/checkout' },
|
||||
{ uses: 'eas/install_native_pods' },
|
||||
{
|
||||
id: 'detect_native_xcode',
|
||||
uses: 'eas/detect_native_xcode',
|
||||
with: {
|
||||
project_file: job.projectFile,
|
||||
scheme: job.scheme,
|
||||
build_configuration: job.buildConfiguration,
|
||||
expected_identifier: metadata?.appIdentifier,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'build_native_ios',
|
||||
uses: 'eas/build_native_ios',
|
||||
with: {
|
||||
project_file: '${ steps.detect_native_xcode.project_file }',
|
||||
scheme: '${ steps.detect_native_xcode.scheme }',
|
||||
build_configuration: '${ steps.detect_native_xcode.build_configuration }',
|
||||
xcodeproj_path: '${ steps.detect_native_xcode.xcodeproj_path }',
|
||||
targets: '${ steps.detect_native_xcode.targets }',
|
||||
},
|
||||
},
|
||||
{
|
||||
uses: 'eas/verify_native_ios',
|
||||
with: {
|
||||
archive_path: '${ steps.build_native_ios.archive_path }',
|
||||
expected_identifier: metadata?.appIdentifier,
|
||||
},
|
||||
},
|
||||
{
|
||||
uses: 'eas/update_resolved_version',
|
||||
with: { application_archive_path: '${ steps.build_native_ios.archive_path }' },
|
||||
},
|
||||
{
|
||||
uses: 'eas/upload_artifact',
|
||||
with: { type: 'application-archive', path: '${ steps.build_native_ios.archive_path }' },
|
||||
},
|
||||
];
|
||||
|
||||
return await new StepsConfigParser(globalContext, {
|
||||
steps,
|
||||
hooks: job.hooks,
|
||||
externalFunctions: [
|
||||
...getEasFunctions(customBuildCtx),
|
||||
createInstallNativePodsBuildFunction(),
|
||||
createDetectNativeXcodeBuildFunction(),
|
||||
createBuildNativeIosBuildFunction(),
|
||||
createVerifyNativeIosBuildFunction(),
|
||||
],
|
||||
loadCompositeFunction: createLocalCompositeFunctionLoader(
|
||||
path.join(customBuildCtx.projectSourceDirectory, job.projectRootDirectory ?? '.'),
|
||||
{ logger: customBuildCtx.logger }
|
||||
),
|
||||
}).parseAsync();
|
||||
}
|
||||
@@ -84,7 +84,7 @@ async function updateVersionsAsync(
|
||||
targetName,
|
||||
buildConfiguration,
|
||||
});
|
||||
const infoPlist = xcBuildConfiguration.buildSettings.INFOPLIST_FILE;
|
||||
const infoPlist = xcBuildConfiguration!.buildSettings.INFOPLIST_FILE;
|
||||
if (infoPlist) {
|
||||
const evaluatedInfoPlistPath = trimQuotes(
|
||||
evaluateTemplateString(infoPlist, {
|
||||
|
||||
@@ -28,5 +28,5 @@ export async function isTVOS(ctx: BuildContext<Ios.Job>): Promise<boolean> {
|
||||
targetName,
|
||||
buildConfiguration,
|
||||
});
|
||||
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv');
|
||||
return xcBuildConfiguration?.buildSettings?.SDKROOT?.includes('appletv') ?? false;
|
||||
}
|
||||
@@ -62,9 +62,13 @@ import { createStartWebPreviewRemoteSessionBuildFunction } from './functions/sta
|
||||
import { createStartServeSimMetricsBuildFunction } from './functions/startServeSimMetrics';
|
||||
import { createStartServeSimLogsBuildFunction } from './functions/startServeSimLogs';
|
||||
import { createCollectServeSimLogsBuildFunction } from './functions/collectServeSimLogs';
|
||||
import { createStartServeSimNetworkCaptureBuildFunction } from './functions/startServeSimNetworkCapture';
|
||||
import { createStartServeSimCrashesBuildFunction } from './functions/startServeSimCrashes';
|
||||
import { createCollectServeSimCrashesBuildFunction } from './functions/collectServeSimCrashes';
|
||||
import { createCollectAndroidEmulatorLogsBuildFunction } from './functions/collectAndroidEmulatorLogs';
|
||||
import { createStartSandboxBuildFunction } from './functions/startSandbox';
|
||||
import { createCollectServeSimMetricsBuildFunction } from './functions/collectServeSimMetrics';
|
||||
import { createCollectServeSimNetworkCaptureBuildFunction } from './functions/collectServeSimNetworkCapture';
|
||||
import { createUploadArtifactBuildFunction } from './functions/uploadArtifact';
|
||||
import { createUploadDeviceRunSessionScreenRecordingsBuildFunction } from './functions/uploadDeviceRunSessionScreenRecordings';
|
||||
import { createUploadEmbeddedBundleBuildFunction } from './functions/uploadEmbeddedBundle';
|
||||
@@ -129,11 +133,15 @@ export function getEasFunctions(ctx: CustomBuildContext): BuildFunction[] {
|
||||
createStartWebPreviewRemoteSessionBuildFunction(ctx, { warm: true }),
|
||||
createStartServeSimMetricsBuildFunction(),
|
||||
createStartServeSimLogsBuildFunction(),
|
||||
createStartServeSimCrashesBuildFunction(),
|
||||
createCollectServeSimCrashesBuildFunction(ctx),
|
||||
createCollectServeSimLogsBuildFunction(ctx),
|
||||
createCollectAndroidEmulatorLogsBuildFunction(ctx),
|
||||
createStartSandboxBuildFunction(ctx),
|
||||
createRunAgentBuildFunction(ctx),
|
||||
createCollectServeSimMetricsBuildFunction(ctx),
|
||||
createStartServeSimNetworkCaptureBuildFunction(),
|
||||
createCollectServeSimNetworkCaptureBuildFunction(ctx),
|
||||
createInstallMaestroBuildFunction(),
|
||||
createInstallMitmproxyBuildFunction(),
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
parseMaestroResults,
|
||||
parseMaestroResultsFromFileAttrs,
|
||||
parseMaestroRunnerReport,
|
||||
parseMaestroRunnerResults,
|
||||
} from '../maestroResultParser';
|
||||
|
||||
describe(parseFailedFlowsFromMaestroRunnerReport, () => {
|
||||
@@ -483,6 +484,271 @@ describe(parseMaestroResultsFromFileAttrs, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(parseMaestroRunnerResults, () => {
|
||||
function runnerJUnit(testcases: { name: string; file: string; failed?: boolean }[]): string {
|
||||
return [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<testsuites>',
|
||||
' <testsuite name="maestro-runner">',
|
||||
...testcases.flatMap(({ name, file, failed }) => [
|
||||
` <testcase id="${name}" name="${name}" classname="${name}" time="1.000" status="${failed ? 'ERROR' : 'SUCCESS'}">`,
|
||||
' <properties>',
|
||||
` <property name="file" value="${file}"/>`,
|
||||
' <property name="device.platform" value="android"/>',
|
||||
' </properties>',
|
||||
...(failed ? [' <failure message="Element not found">tapOn</failure>'] : []),
|
||||
' </testcase>',
|
||||
]),
|
||||
' </testsuite>',
|
||||
'</testsuites>',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
it('adds the tags of each flow from the report.json of its attempt', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/android-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'flows/auth/sign-in.yaml', failed: true },
|
||||
{ name: 'settings', file: 'flows/settings.yaml' },
|
||||
]),
|
||||
'/tests/android-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'sign-in',
|
||||
sourceFile: 'flows/auth/sign-in.yaml',
|
||||
status: 'failed',
|
||||
tags: ['auth', 'smoke'],
|
||||
},
|
||||
{ name: 'settings', sourceFile: 'flows/settings.yaml', status: 'passed' },
|
||||
],
|
||||
}),
|
||||
'/junit/android-maestro-junit-attempt-1.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'flows/auth/sign-in.yaml' },
|
||||
]),
|
||||
'/tests/android-maestro-runner-attempt-1/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'sign-in',
|
||||
sourceFile: 'flows/auth/sign-in.yaml',
|
||||
status: 'passed',
|
||||
tags: ['auth'],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
{
|
||||
name: 'sign-in',
|
||||
path: 'flows/auth/sign-in.yaml',
|
||||
status: 'failed',
|
||||
errorMessage: 'Element not found',
|
||||
duration: 1000,
|
||||
retryCount: 0,
|
||||
tags: ['auth', 'smoke'],
|
||||
properties: { file: 'flows/auth/sign-in.yaml', 'device.platform': 'android' },
|
||||
},
|
||||
expect.objectContaining({ path: 'flows/auth/sign-in.yaml', retryCount: 1, tags: ['auth'] }),
|
||||
expect.objectContaining({ path: 'flows/settings.yaml', retryCount: 0, tags: [] }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches an absolute sourceFile with a JUnit path relative to the working directory', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'sign-in',
|
||||
sourceFile: '/project/flows/sign-in.yaml',
|
||||
status: 'passed',
|
||||
tags: ['auth'],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({ path: 'flows/sign-in.yaml', tags: ['auth'] }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches a sourceFile under a symlinked directory with the JUnit path of its target', async () => {
|
||||
vol.fromJSON({
|
||||
'/project/flows/sign-in.yaml': '',
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'sign-in', sourceFile: 'linked/sign-in.yaml', status: 'passed', tags: ['auth'] },
|
||||
],
|
||||
}),
|
||||
});
|
||||
vol.symlinkSync('/project/flows', '/project/linked');
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({ path: 'flows/sign-in.yaml', tags: ['auth'] }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches a sourceFile whose symlink leaves the working directory by the path as given', async () => {
|
||||
vol.fromJSON({
|
||||
'/project/.keep': '',
|
||||
'/shared/sign-in.yaml': '',
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'linked/sign-in.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'sign-in', sourceFile: 'linked/sign-in.yaml', status: 'passed', tags: ['auth'] },
|
||||
],
|
||||
}),
|
||||
});
|
||||
vol.symlinkSync('/shared', '/project/linked');
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({ path: 'linked/sign-in.yaml', tags: ['auth'] }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not follow a symlink from the bare file name that maestro-runner <= 1.1.17 writes', async () => {
|
||||
vol.fromJSON({
|
||||
'/project/flows/sign-in.yaml': '',
|
||||
'/project/settings.yaml': '',
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'sign-in.yaml' },
|
||||
{ name: 'settings', file: 'settings.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'sign-in', sourceFile: 'flows/sign-in.yaml', status: 'passed', tags: ['auth'] },
|
||||
{ name: 'settings', sourceFile: 'settings.yaml', status: 'passed', tags: ['settings'] },
|
||||
],
|
||||
}),
|
||||
});
|
||||
vol.symlinkSync('/project/settings.yaml', '/project/sign-in.yaml');
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({ path: 'sign-in.yaml', tags: ['auth'] }),
|
||||
expect.objectContaining({ path: 'settings.yaml', tags: ['settings'] }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches by file name when JUnit has only the file name and it is unique', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'sign-in.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'sign-in',
|
||||
sourceFile: 'flows/auth/sign-in.yaml',
|
||||
status: 'passed',
|
||||
tags: ['auth'],
|
||||
},
|
||||
{
|
||||
name: 'settings',
|
||||
sourceFile: 'flows/settings.yaml',
|
||||
status: 'passed',
|
||||
tags: ['settings'],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([expect.objectContaining({ path: 'sign-in.yaml', tags: ['auth'] })]);
|
||||
});
|
||||
|
||||
it('adds no tags when two flows of the attempt have the same file name', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/ios-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'sign-in.yaml' },
|
||||
]),
|
||||
'/tests/ios-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{ name: 'a', sourceFile: 'flows/a/sign-in.yaml', status: 'passed', tags: ['a'] },
|
||||
{ name: 'b', sourceFile: 'flows/b/sign-in.yaml', status: 'passed', tags: ['b'] },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([expect.objectContaining({ path: 'sign-in.yaml', tags: [] })]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: 'is not valid JSON', content: '{' },
|
||||
{ name: 'has an unknown shape', content: JSON.stringify({ flows: [{ name: 'sign-in' }] }) },
|
||||
{
|
||||
name: 'does not have the flow',
|
||||
content: JSON.stringify({
|
||||
flows: [{ name: 'other', sourceFile: 'flows/other.yaml', status: 'passed', tags: ['x'] }],
|
||||
}),
|
||||
},
|
||||
])('keeps the JUnit result without tags when report.json $name', async ({ content }) => {
|
||||
vol.fromJSON({
|
||||
'/junit/android-maestro-junit-attempt-0.xml': runnerJUnit([
|
||||
{ name: 'sign-in', file: 'flows/sign-in.yaml' },
|
||||
]),
|
||||
'/tests/android-maestro-runner-attempt-0/report.json': content,
|
||||
});
|
||||
|
||||
const results = await parseMaestroRunnerResults({
|
||||
junitDirectory: '/junit',
|
||||
testsDirectory: '/tests',
|
||||
workingDirectory: '/project',
|
||||
});
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({ name: 'sign-in', path: 'flows/sign-in.yaml', tags: [] }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('junitFileHasFileAttrs', () => {
|
||||
it('returns true when every testcase has a non-empty file= attribute', async () => {
|
||||
vol.fromJSON({
|
||||
|
||||
@@ -358,6 +358,51 @@ describe(createReportMaestroTestResultsFunction, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('reports maestro-runner results with the tags from report.json', async () => {
|
||||
vol.fromJSON({
|
||||
'/junit/android-maestro-junit-attempt-0.xml': [
|
||||
'<testsuites><testsuite name="maestro-runner">',
|
||||
' <testcase id="sign-in" name="sign-in" classname="sign-in" time="2.000" status="SUCCESS">',
|
||||
' <properties><property name="file" value="flows/sign-in.yaml"/></properties>',
|
||||
' </testcase>',
|
||||
'</testsuite></testsuites>',
|
||||
].join('\n'),
|
||||
'/tests/android-maestro-runner-attempt-0/report.json': JSON.stringify({
|
||||
flows: [
|
||||
{
|
||||
name: 'sign-in',
|
||||
sourceFile: 'flows/sign-in.yaml',
|
||||
status: 'passed',
|
||||
tags: ['auth', 'smoke'],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
mockMutationFn.mockResolvedValue({
|
||||
data: {
|
||||
workflowDeviceTestCaseResult: {
|
||||
createWorkflowDeviceTestCaseResults: [{ id: 'id-1' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await createStep().executeAsync();
|
||||
|
||||
const variables = (mockGraphqlClient.mutation as jest.Mock).mock.calls[0][1];
|
||||
expect(variables.input.testCaseResults).toEqual([
|
||||
{
|
||||
name: 'sign-in',
|
||||
path: 'flows/sign-in.yaml',
|
||||
status: 'PASSED',
|
||||
errorMessage: null,
|
||||
duration: 2000,
|
||||
retryCount: 0,
|
||||
tags: ['auth', 'smoke'],
|
||||
properties: { file: 'flows/sign-in.yaml' },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('uses default directories when inputs are not provided', async () => {
|
||||
vol.fromJSON({
|
||||
'/home/expo/.maestro/tests/report.xml': JUNIT_PASS,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { type BuildStepContext, type BuildStepEnv } from '@expo/steps';
|
||||
import { access, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { type CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { getDeviceRunSessionIdOrThrow } from '../../utils/remoteDeviceRunSession';
|
||||
import { uploadServeSimCrashesFileAsync } from '../../utils/serveSimCrashesArtifacts';
|
||||
import { ServeSimCrashesRecorder } from '../../utils/serveSimCrashesRecorder';
|
||||
import { createCollectServeSimCrashesBuildFunction } from '../collectServeSimCrashes';
|
||||
import { createStartServeSimCrashesBuildFunction } from '../startServeSimCrashes';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('../../utils/serveSimCrashesRecorder');
|
||||
jest.mock('../../utils/serveSimCrashesArtifacts');
|
||||
jest.mock('../../utils/remoteDeviceRunSession');
|
||||
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
const ctx = {} as CustomBuildContext;
|
||||
const step = { logger } as BuildStepContext;
|
||||
const args = { inputs: {}, outputs: {}, env: {} as BuildStepEnv };
|
||||
|
||||
beforeEach(() => {
|
||||
jest.mocked(getDeviceRunSessionIdOrThrow).mockReturnValue('session-id');
|
||||
jest
|
||||
.mocked(ServeSimCrashesRecorder.finishAsync)
|
||||
.mockResolvedValue({ outputDirectory: null, crashes: [] });
|
||||
});
|
||||
|
||||
it('starts collection and tolerates startup failures', async () => {
|
||||
jest.mocked(ServeSimCrashesRecorder.startAsync).mockRejectedValueOnce(new Error('disk failure'));
|
||||
await expect(createStartServeSimCrashesBuildFunction().fn?.(step, args)).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalled();
|
||||
expect(Sentry.capture).toHaveBeenCalledWith(
|
||||
'Could not start serve-sim simulator crashes',
|
||||
expect.any(Error)
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads each report and removes the collection directory', async () => {
|
||||
const directory = '/tmp/crashes-collected';
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(`${directory}/A.ips`, 'private crash report');
|
||||
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
|
||||
outputDirectory: directory,
|
||||
crashes: [
|
||||
{ udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
|
||||
{ udid: 'B', filePath: `${directory}/B.ips`, size: 20, number: 1 },
|
||||
],
|
||||
});
|
||||
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
|
||||
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledTimes(2);
|
||||
expect(uploadServeSimCrashesFileAsync).toHaveBeenCalledWith(ctx, {
|
||||
deviceRunSessionId: 'session-id',
|
||||
crash: { udid: 'A', filePath: `${directory}/A.ips`, size: 20, number: 1 },
|
||||
logger,
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
await expect(access(directory)).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
});
|
||||
|
||||
it('skips empty collection and warns on finalization failure', async () => {
|
||||
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
|
||||
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
|
||||
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockRejectedValueOnce(new Error('failure'));
|
||||
await expect(
|
||||
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalled();
|
||||
expect(Sentry.capture).toHaveBeenCalledWith(
|
||||
'Could not finalize serve-sim simulator crashes',
|
||||
expect.any(Error)
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no crashes were recorded', [], false],
|
||||
['session resolution fails', [{ udid: 'A', filePath: 'A.ips', size: 20, number: 1 }], true],
|
||||
])('removes the collection directory when %s', async (_name, crashes, failSession) => {
|
||||
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'crashes-collected-'));
|
||||
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({ outputDirectory, crashes });
|
||||
if (failSession) {
|
||||
jest.mocked(getDeviceRunSessionIdOrThrow).mockImplementationOnce(() => {
|
||||
throw new Error('Missing session ID');
|
||||
});
|
||||
}
|
||||
await expect(
|
||||
createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args)
|
||||
).resolves.toBeUndefined();
|
||||
await expect(access(outputDirectory)).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
expect(uploadServeSimCrashesFileAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips remaining reports for an exhausted device and continues with other devices', async () => {
|
||||
jest.mocked(ServeSimCrashesRecorder.finishAsync).mockResolvedValue({
|
||||
outputDirectory: null,
|
||||
crashes: [
|
||||
{ udid: 'A', filePath: '/tmp/A-1.ips', size: 20, number: 1 },
|
||||
{ udid: 'A', filePath: '/tmp/A-2.ips', size: 20, number: 2 },
|
||||
{ udid: 'B', filePath: '/tmp/B-1.ips', size: 20, number: 1 },
|
||||
],
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const timeout = jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(controller.signal);
|
||||
jest.mocked(uploadServeSimCrashesFileAsync).mockImplementationOnce(async () => {
|
||||
controller.abort(new Error('Upload budget exhausted'));
|
||||
});
|
||||
try {
|
||||
await createCollectServeSimCrashesBuildFunction(ctx).fn?.(step, args);
|
||||
expect(
|
||||
jest.mocked(uploadServeSimCrashesFileAsync).mock.calls.map(([, { crash }]) => crash.filePath)
|
||||
).toEqual(['/tmp/A-1.ips', '/tmp/B-1.ips']);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Simulator crash upload reached its time limit for A; remaining reports will not be uploaded.'
|
||||
);
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { type BuildStepEnv } from '@expo/steps';
|
||||
import { access, mkdtemp } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { type CustomBuildContext } from '../../../customBuildContext';
|
||||
import { uploadServeSimNetworkCaptureFileAsync } from '../../utils/serveSimNetworkCaptureArtifacts';
|
||||
import { ServeSimNetworkCaptureRecorder } from '../../utils/serveSimNetworkCaptureRecorder';
|
||||
import { createCollectServeSimNetworkCaptureBuildFunction } from '../collectServeSimNetworkCapture';
|
||||
import { createStartServeSimNetworkCaptureBuildFunction } from '../startServeSimNetworkCapture';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('../../utils/serveSimNetworkCaptureArtifacts');
|
||||
jest.mock('../../utils/serveSimNetworkCaptureRecorder');
|
||||
|
||||
const ctx = {} as CustomBuildContext;
|
||||
const logger = {
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
} as unknown as bunyan;
|
||||
|
||||
type Fn = (stepCtx: unknown, options: unknown) => Promise<void>;
|
||||
function runFn(
|
||||
fn: unknown,
|
||||
options: { env: BuildStepEnv; inputs?: Record<string, { value: unknown }> }
|
||||
): Promise<void> {
|
||||
return (fn as Fn)({ logger }, { inputs: {}, ...options });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts the recorder with the session package version and never fails the step', async () => {
|
||||
const buildFunction = createStartServeSimNetworkCaptureBuildFunction();
|
||||
expect(buildFunction.id).toBe('start_serve_sim_network_capture');
|
||||
const { fn } = buildFunction as unknown as { fn: Fn };
|
||||
const env = {} as BuildStepEnv;
|
||||
await runFn(fn, { env, inputs: { package_version: { value: '0.5.0' } } });
|
||||
expect(ServeSimNetworkCaptureRecorder.startAsync).toHaveBeenCalledWith({
|
||||
logger,
|
||||
env,
|
||||
packageVersion: '0.5.0',
|
||||
});
|
||||
|
||||
jest.mocked(ServeSimNetworkCaptureRecorder.startAsync).mockRejectedValueOnce(new Error('ENOSPC'));
|
||||
await expect(
|
||||
runFn(fn, { env, inputs: { package_version: { value: undefined } } })
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ message: 'ENOSPC' }) },
|
||||
'Could not start the serve-sim network capture recorder.'
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads each recorded HAR as a numbered part per device, then removes the directory', async () => {
|
||||
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
|
||||
const captures = [
|
||||
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 },
|
||||
{ udid: 'SIM-B', filePath: path.join(outputDirectory, 'SIM-B-1.har'), size: 25 },
|
||||
{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-3.har'), size: 26 },
|
||||
];
|
||||
jest
|
||||
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
|
||||
.mockResolvedValueOnce({ outputDirectory, captures });
|
||||
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
|
||||
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
|
||||
const signal = expect.any(AbortSignal);
|
||||
expect(jest.mocked(uploadServeSimNetworkCaptureFileAsync).mock.calls).toEqual([
|
||||
[ctx, { deviceRunSessionId: 'drs-id', ...captures[0], part: 1, logger, signal }],
|
||||
[ctx, { deviceRunSessionId: 'drs-id', ...captures[1], part: 1, logger, signal }],
|
||||
[ctx, { deviceRunSessionId: 'drs-id', ...captures[2], part: 2, logger, signal }],
|
||||
]);
|
||||
await expect(access(outputDirectory)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('does not fail the step without a device run session, and still removes the directory', async () => {
|
||||
const outputDirectory = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-'));
|
||||
jest.mocked(ServeSimNetworkCaptureRecorder.finishAsync).mockResolvedValueOnce({
|
||||
outputDirectory,
|
||||
captures: [{ udid: 'SIM-A', filePath: path.join(outputDirectory, 'SIM-A-1.har'), size: 24 }],
|
||||
});
|
||||
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
|
||||
await expect(runFn(fn, { env: {} as BuildStepEnv })).resolves.toBeUndefined();
|
||||
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.any(Error) },
|
||||
'Could not upload the network capture.'
|
||||
);
|
||||
await expect(access(outputDirectory)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('skips the upload when nothing was recorded', async () => {
|
||||
jest
|
||||
.mocked(ServeSimNetworkCaptureRecorder.finishAsync)
|
||||
.mockResolvedValueOnce({ outputDirectory: null, captures: [] });
|
||||
const { fn } = createCollectServeSimNetworkCaptureBuildFunction(ctx) as unknown as { fn: Fn };
|
||||
await runFn(fn, { env: { DEVICE_RUN_SESSION_ID: 'drs-id' } as BuildStepEnv });
|
||||
expect(uploadServeSimNetworkCaptureFileAsync).not.toHaveBeenCalled();
|
||||
expect(logger.info).toHaveBeenCalledWith('No network capture was recorded; skipping upload.');
|
||||
});
|
||||
+30
@@ -201,6 +201,21 @@ describe('runAgentDeviceRemoteSessionAsync orchestration', () => {
|
||||
expect(mockDaemonStopAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not fail a session when only the agent-device tunnel cannot stop', async () => {
|
||||
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
|
||||
const tunnelError = new Error('Ngrok tunnel stop timed out after 4000ms.');
|
||||
mockTunnelStopAsync.mockRejectedValueOnce(tunnelError);
|
||||
|
||||
await expect(runAsync(logger, BuildRuntimePlatform.LINUX)).resolves.toBeUndefined();
|
||||
|
||||
expect(mockPreviewStopAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockDaemonStopAsync).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: tunnelError },
|
||||
'Could not stop the agent-device tunnel during remote session teardown.'
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the warm daemon after adoption and starts no daemon of its own', async () => {
|
||||
const logger = { info: jest.fn(), warn: jest.fn(), child: jest.fn().mockReturnThis() };
|
||||
const warmServer = { port: 3200 } as never;
|
||||
@@ -918,6 +933,21 @@ describe('runAgentDeviceRemoteSessionAsync orchestration', () => {
|
||||
await expect(session).rejects.toBe(failed);
|
||||
});
|
||||
|
||||
it('reports a startup Stop when only the agent-device tunnel cannot stop', async () => {
|
||||
const stopped = new DeviceRunSessionStoppedError('stopped during startup');
|
||||
let tasks!: StartupTasks;
|
||||
const session = startSession(startup => {
|
||||
tasks = startup;
|
||||
return { booted: Promise.resolve(), ready: tasks.untilAborted(new Promise(() => {})) };
|
||||
});
|
||||
session.catch(() => {});
|
||||
await flushAsync();
|
||||
mockTunnelStopAsync.mockRejectedValueOnce(new Error('tunnel stop timed out'));
|
||||
tasks.abort(stopped);
|
||||
await expect(session).rejects.toBe(stopped);
|
||||
expect(mockTunnelStopAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retires startup monitoring after reporting and before lifetime waiting', async () => {
|
||||
const retired = deferred();
|
||||
const retiring = jest.fn(() => retired.promise);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { retryAsync } from '../../../utils/retry';
|
||||
import { resolveAndroidEmulatorLocalEgressAsync } from '../../utils/androidLocalEgress';
|
||||
import { AndroidEmulatorLogRing } from '../../../utils/androidEmulatorLogCapture';
|
||||
import { getAndroidEmulatorLogCapture } from '../../utils/androidEmulatorLogs';
|
||||
import { installEmulatorCaptureAsync } from '../../utils/emulatorCapture';
|
||||
import { createStartAndroidEmulatorBuildFunction } from '../startAndroidEmulator';
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({
|
||||
@@ -28,6 +29,11 @@ jest.mock('../../utils/androidLocalEgress', () => ({
|
||||
|
||||
jest.mock('../../utils/androidEmulatorLogs');
|
||||
|
||||
jest.mock('../../utils/emulatorCapture', () => ({
|
||||
...jest.requireActual('../../utils/emulatorCapture'),
|
||||
installEmulatorCaptureAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
|
||||
AndroidEmulatorUtils: {
|
||||
defaultSystemImagePackage: 'system-images;android-30;default;x86_64',
|
||||
@@ -38,6 +44,7 @@ jest.mock('../../../utils/AndroidEmulatorUtils', () => ({
|
||||
waitForReadyAsync: jest.fn(),
|
||||
disableWindowAndTransitionAnimationsAsync: jest.fn(),
|
||||
deleteAsync: jest.fn(),
|
||||
findFreeConsolePortAsync: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -54,7 +61,12 @@ function createStep(callInputs?: Record<string, unknown>, envOverrides?: NodeJS.
|
||||
const step = fn.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs,
|
||||
});
|
||||
return Object.assign(step, { logger });
|
||||
return Object.assign(step, { logger, globalCtx });
|
||||
}
|
||||
|
||||
/** The logger that the step function gets: a child of the base logger. */
|
||||
function stepLogger(step: ReturnType<typeof createStep>) {
|
||||
return jest.mocked(step.logger.child).mock.results[0].value;
|
||||
}
|
||||
|
||||
function createStartResult(serialId: string) {
|
||||
@@ -470,4 +482,170 @@ describe(createStartAndroidEmulatorBuildFunction, () => {
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
describe('experimental emulator capture', () => {
|
||||
const LIBRARY = '/tmp/package/libexpo_emulator_capture.so';
|
||||
const mockedInstall = jest.mocked(installEmulatorCaptureAsync);
|
||||
|
||||
function captureStart(port: number) {
|
||||
return {
|
||||
deviceName: 'EasAndroidDevice01',
|
||||
env: expect.any(Object),
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
logCapture: expect.objectContaining({ sources: ['emulator-output', 'device-logcat'] }),
|
||||
consolePort: port,
|
||||
extraArgs: ['-gpu', 'lavapipe'],
|
||||
extraEnv: {
|
||||
LD_PRELOAD: LIBRARY,
|
||||
EXPO_EMULATOR_CAPTURE_SOCKET: `/tmp/job/expo-emulator-capture/emulator-${port}.sock`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockedInstall.mockReset().mockResolvedValue(LIBRARY);
|
||||
mockedAndroidUtils.findFreeConsolePortAsync
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(5554)
|
||||
.mockResolvedValueOnce(5556);
|
||||
mockedAndroidUtils.startAsync.mockResolvedValue(createStartResult('emulator-5554'));
|
||||
});
|
||||
|
||||
it('preloads the agent and turns the capture on for expo-device-hub', async () => {
|
||||
const step = createStep(
|
||||
{ experimental_emulator_capture_version: '0.1.0' },
|
||||
{ TMPDIR: '/tmp/job' }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedInstall).toHaveBeenCalledWith({
|
||||
version: '0.1.0',
|
||||
env: expect.any(Object),
|
||||
logger: expect.anything(),
|
||||
});
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(captureStart(5554));
|
||||
expect(step.globalCtx.env).toMatchObject({
|
||||
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
|
||||
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: LIBRARY,
|
||||
});
|
||||
expect(stepLogger(step).info).toHaveBeenCalledWith(
|
||||
'emulator-5554 preloads [email protected] with -gpu lavapipe, and its agent socket is /tmp/job/expo-emulator-capture/emulator-5554.sock. Later steps start expo-device-hub with the emulator capture on.'
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the temporary directory rule of Node when TMPDIR is empty', async () => {
|
||||
await createStep(
|
||||
{ experimental_emulator_capture_version: '0.1.0' },
|
||||
{ TMPDIR: '', TMP: '/tmp/from-tmp' }
|
||||
).executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
extraEnv: expect.objectContaining({
|
||||
EXPO_EMULATOR_CAPTURE_SOCKET: '/tmp/from-tmp/expo-emulator-capture/emulator-5554.sock',
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('uses /tmp when the job env names no temporary directory', async () => {
|
||||
await createStep({ experimental_emulator_capture_version: '0.1.0' }).executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
extraEnv: expect.objectContaining({
|
||||
EXPO_EMULATOR_CAPTURE_SOCKET: '/tmp/expo-emulator-capture/emulator-5554.sock',
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('does not turn the capture on when the emulator runs on another console port', async () => {
|
||||
mockedAndroidUtils.startAsync.mockResolvedValue(createStartResult('emulator-5560'));
|
||||
const step = createStep(
|
||||
{ experimental_emulator_capture_version: '0.1.0' },
|
||||
{ TMPDIR: '/tmp/job' }
|
||||
);
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
|
||||
expect(stepLogger(step).warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('emulator-5560 does not use console port 5554')
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps a library that the job already preloads, after the agent', async () => {
|
||||
await createStep(
|
||||
{ experimental_emulator_capture_version: '0.1.0' },
|
||||
{ TMPDIR: '/tmp/job', LD_PRELOAD: '/opt/other.so' }
|
||||
).executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
extraEnv: expect.objectContaining({ LD_PRELOAD: `${LIBRARY}:/opt/other.so` }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('chooses a new console port for each start attempt', async () => {
|
||||
mockedAndroidUtils.startAsync
|
||||
.mockRejectedValueOnce(new Error('emulator did not start'))
|
||||
.mockResolvedValue(createStartResult('emulator-5556'));
|
||||
|
||||
await createStep(
|
||||
{ experimental_emulator_capture_version: '0.1.0' },
|
||||
{ TMPDIR: '/tmp/job' }
|
||||
).executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenNthCalledWith(2, captureStart(5556));
|
||||
});
|
||||
|
||||
it('starts the emulator as without the input when the install fails', async () => {
|
||||
mockedInstall.mockResolvedValue(undefined);
|
||||
const step = createStep({ experimental_emulator_capture_version: '0.1.0' });
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedAndroidUtils.startAsync).toHaveBeenCalledWith({
|
||||
deviceName: 'EasAndroidDevice01',
|
||||
env: expect.any(Object),
|
||||
logcatDirectory: '/tmp/logcat-directory',
|
||||
logCapture: expect.objectContaining({ sources: ['emulator-output', 'device-logcat'] }),
|
||||
});
|
||||
expect(mockedAndroidUtils.findFreeConsolePortAsync).not.toHaveBeenCalled();
|
||||
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
|
||||
// The session step still rejects session types without the capture.
|
||||
expect(step.globalCtx.env.EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION).toBe('0.1.0');
|
||||
});
|
||||
|
||||
it('installs nothing without the input', async () => {
|
||||
const step = createStep();
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(mockedInstall).not.toHaveBeenCalled();
|
||||
expect(mockedAndroidUtils.findFreeConsolePortAsync).not.toHaveBeenCalled();
|
||||
expect(step.globalCtx.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
|
||||
expect(step.globalCtx.env.EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects the capture for more than one emulator before it starts one', async () => {
|
||||
await expect(
|
||||
createStep({ experimental_emulator_capture_version: '0.1.0', count: 2 }).executeAsync()
|
||||
).rejects.toThrow('experimental_emulator_capture_version supports one emulator');
|
||||
|
||||
expect(mockedInstall).not.toHaveBeenCalled();
|
||||
expect(mockedAndroidUtils.startAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a version that is not an exact npm version or a dist-tag', async () => {
|
||||
await expect(
|
||||
createStep({ experimental_emulator_capture_version: 'npm:[email protected]' }).executeAsync()
|
||||
).rejects.toThrow('must be an npm version or dist-tag of expo-emulator-capture');
|
||||
|
||||
expect(mockedInstall).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -850,6 +850,26 @@ describe('createStartAppiumRemoteSessionBuildFunction session lifecycle', () =>
|
||||
);
|
||||
}
|
||||
|
||||
it('does not fail a session when only the Appium tunnel cannot stop', async () => {
|
||||
const tunnelError = new Error('Ngrok tunnel stop timed out after 4000ms.');
|
||||
const logger = { info: jest.fn(), warn: jest.fn() };
|
||||
stopAppium.mockResolvedValueOnce(undefined);
|
||||
jest.mocked(startNgrokTunnelAsync).mockResolvedValueOnce({
|
||||
url: 'https://appium-abc.tunnel.example.com',
|
||||
subdomainId: 'appium-abc',
|
||||
stopAsync: jest.fn().mockRejectedValue(tunnelError),
|
||||
});
|
||||
|
||||
await expect(runSessionAsync(logger)).resolves.toBeUndefined();
|
||||
|
||||
expect(stopAppium).toHaveBeenCalledTimes(1);
|
||||
expect(finishHost).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: tunnelError },
|
||||
'Could not stop the Appium tunnel during remote session teardown.'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not allocate Appium or a host after parent cancellation during Xcode selection', async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new Error('parent step cancelled');
|
||||
|
||||
+28
-29
@@ -667,7 +667,7 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
|
||||
['succeeded', false],
|
||||
['failed', true],
|
||||
])(
|
||||
'fails after stopping the host and tools when the tools tunnel cannot close and the session %s',
|
||||
'stops the host and tools when the tools tunnel cannot close and the session %s',
|
||||
async (_description, sessionFails) => {
|
||||
const closeError = new Error('ngrok close failed');
|
||||
const sessionError = new Error('session failed');
|
||||
@@ -677,23 +677,26 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
|
||||
}
|
||||
const logger = { info: jest.fn(), warn: jest.fn() };
|
||||
const buildFunction = createStartArgentRemoteSessionBuildFunction({} as CustomBuildContext);
|
||||
// The tunnel may still be serving, so its failure fails a session that otherwise succeeded.
|
||||
await expect(
|
||||
buildFunction.fn!(
|
||||
{
|
||||
logger,
|
||||
global: { runtimePlatform: BuildRuntimePlatform.LINUX },
|
||||
} as unknown as BuildStepContext,
|
||||
{
|
||||
inputs: {
|
||||
package_version: { value: undefined },
|
||||
max_idle_time_minutes: { value: undefined },
|
||||
},
|
||||
outputs: {},
|
||||
env: {},
|
||||
} as never
|
||||
)
|
||||
).rejects.toBe(sessionFails ? sessionError : closeError);
|
||||
// A stopped tunnel's proxy drops every connection, so its failure does not fail a session.
|
||||
const running = buildFunction.fn!(
|
||||
{
|
||||
logger,
|
||||
global: { runtimePlatform: BuildRuntimePlatform.LINUX },
|
||||
} as unknown as BuildStepContext,
|
||||
{
|
||||
inputs: {
|
||||
package_version: { value: undefined },
|
||||
max_idle_time_minutes: { value: undefined },
|
||||
},
|
||||
outputs: {},
|
||||
env: {},
|
||||
} as never
|
||||
);
|
||||
if (sessionFails) {
|
||||
await expect(running).rejects.toBe(sessionError);
|
||||
} else {
|
||||
await expect(running).resolves.toBeUndefined();
|
||||
}
|
||||
expect(mockTunnelStopAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockPreviewStopAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockStopAsync).toHaveBeenCalledTimes(1);
|
||||
@@ -702,17 +705,13 @@ describe('createStartArgentRemoteSessionBuildFunction orchestration', () => {
|
||||
{ err: closeError },
|
||||
'Could not stop the Argent tunnel during remote session teardown.'
|
||||
);
|
||||
expect(jest.mocked(Sentry.capture).mock.calls).toEqual(
|
||||
sessionFails
|
||||
? [
|
||||
[
|
||||
'Could not stop the Argent tunnel after the remote session failed',
|
||||
closeError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
]
|
||||
: []
|
||||
);
|
||||
expect(jest.mocked(Sentry.capture).mock.calls).toEqual([
|
||||
[
|
||||
`Could not stop the Argent tunnel after the remote session ${sessionFails ? 'failed' : 'ended'}`,
|
||||
closeError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
]);
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
+22
-20
@@ -238,18 +238,29 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('uses preview activity to reset the configured idle timeout', async () => {
|
||||
await runAsync(BuildRuntimePlatform.DARWIN, { max_idle_time_minutes: { value: 5 } });
|
||||
const { idleTimeout } = jest.mocked(waitForDeviceRunSessionStoppedAsync).mock.calls[0][0];
|
||||
expect(idleTimeout?.maxIdleTimeMinutes).toBe(5);
|
||||
expect(idleTimeout?.getLastEventObservedAt()).toBeUndefined();
|
||||
const host = await jest.mocked(startDeviceSessionHostAsync).mock.results[0].value;
|
||||
const observedAt = new Date();
|
||||
jest.mocked(host.getLastPreviewActivityAt).mockReturnValue(observedAt);
|
||||
expect(idleTimeout?.getLastPreviewActivityAt?.()).toBe(observedAt);
|
||||
expect(stopAsync).toHaveBeenCalledTimes(1);
|
||||
it('lets the session host use the experimental emulator capture', async () => {
|
||||
await runAsync(BuildRuntimePlatform.LINUX);
|
||||
expect(startDeviceSessionHostAsync).toHaveBeenCalledWith(
|
||||
ctx,
|
||||
expect.objectContaining({ emulatorCapture: true })
|
||||
);
|
||||
});
|
||||
|
||||
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
|
||||
'uses preview activity to reset the configured idle timeout on %s',
|
||||
async runtimePlatform => {
|
||||
await runAsync(runtimePlatform, { max_idle_time_minutes: { value: 5 } });
|
||||
const { idleTimeout } = jest.mocked(waitForDeviceRunSessionStoppedAsync).mock.calls[0][0];
|
||||
expect(idleTimeout?.maxIdleTimeMinutes).toBe(5);
|
||||
expect(idleTimeout?.getLastEventObservedAt()).toBeUndefined();
|
||||
const host = await jest.mocked(startDeviceSessionHostAsync).mock.results[0].value;
|
||||
const observedAt = new Date();
|
||||
jest.mocked(host.getLastPreviewActivityAt).mockReturnValue(observedAt);
|
||||
expect(idleTimeout?.getLastPreviewActivityAt?.()).toBe(observedAt);
|
||||
expect(stopAsync).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
|
||||
'leaves the idle timer disabled when omitted on %s',
|
||||
async runtimePlatform => {
|
||||
@@ -269,16 +280,6 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an Android idle timeout before starting the host', async () => {
|
||||
await expect(
|
||||
runAsync(BuildRuntimePlatform.LINUX, {
|
||||
max_idle_time_minutes: { value: 5 },
|
||||
})
|
||||
).rejects.toThrow('Omit max_idle_time_minutes for Android sessions.');
|
||||
expect(startDeviceSessionHostAsync).not.toHaveBeenCalled();
|
||||
expect(waitForDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([BuildRuntimePlatform.DARWIN, BuildRuntimePlatform.LINUX])(
|
||||
'handles Stop while the %s host starts',
|
||||
async runtimePlatform => {
|
||||
@@ -508,6 +509,7 @@ describe(createStartWebPreviewRemoteSessionBuildFunction, () => {
|
||||
}
|
||||
: {}),
|
||||
packageVersion: '1.2.3',
|
||||
emulatorCapture: true,
|
||||
disableShare: false,
|
||||
frameAncestors: [],
|
||||
corsOrigins: [],
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
|
||||
import { rm } from 'node:fs/promises';
|
||||
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
|
||||
import { uploadServeSimCrashesFileAsync } from '../utils/serveSimCrashesArtifacts';
|
||||
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
|
||||
|
||||
const UPLOAD_TIMEOUT_MS = 30_000;
|
||||
|
||||
export function createCollectServeSimCrashesBuildFunction(ctx: CustomBuildContext): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'collect_serve_sim_crashes',
|
||||
name: 'Collect serve-sim simulator crashes',
|
||||
__metricsId: 'eas/collect_serve_sim_crashes',
|
||||
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
|
||||
fn: async ({ logger }, { env }) => {
|
||||
let outputDirectory: string | null = null;
|
||||
try {
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
outputDirectory = collected.outputDirectory;
|
||||
if (collected.crashes.length === 0) {
|
||||
logger.info('No simulator crashes collected; skipping upload.');
|
||||
return;
|
||||
}
|
||||
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
|
||||
for (const udid of new Set(collected.crashes.map(crash => crash.udid))) {
|
||||
const signal = AbortSignal.timeout(UPLOAD_TIMEOUT_MS);
|
||||
for (const crash of collected.crashes.filter(crash => crash.udid === udid)) {
|
||||
if (signal.aborted) {
|
||||
logger.warn(
|
||||
`Simulator crash upload reached its time limit for ${udid}; remaining reports will not be uploaded.`
|
||||
);
|
||||
break;
|
||||
}
|
||||
await uploadServeSimCrashesFileAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
crash,
|
||||
logger,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not finalize serve-sim simulator crashes', error);
|
||||
logger.warn(
|
||||
{ err: error },
|
||||
'Could not finalize simulator crashes; the session result is unchanged.'
|
||||
);
|
||||
} finally {
|
||||
if (outputDirectory) {
|
||||
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
|
||||
logger.warn({ err }, 'Could not remove the simulator crash directory.');
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
|
||||
import { rm } from 'node:fs/promises';
|
||||
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { getDeviceRunSessionIdOrThrow } from '../utils/remoteDeviceRunSession';
|
||||
import { uploadServeSimNetworkCaptureFileAsync } from '../utils/serveSimNetworkCaptureArtifacts';
|
||||
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
|
||||
|
||||
// Each HAR may be up to 500 MiB, so one slow upload gets its own long limit.
|
||||
const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export function createCollectServeSimNetworkCaptureBuildFunction(
|
||||
ctx: CustomBuildContext
|
||||
): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'collect_serve_sim_network_capture',
|
||||
name: 'Collect serve-sim network capture',
|
||||
__metricsId: 'eas/collect_serve_sim_network_capture',
|
||||
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
|
||||
fn: async ({ logger }, { env }) => {
|
||||
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
if (captures.length === 0) {
|
||||
logger.info('No network capture was recorded; skipping upload.');
|
||||
return;
|
||||
}
|
||||
const deviceRunSessionId = getDeviceRunSessionIdOrThrow(env);
|
||||
// A device's HARs are numbered parts, one per capture har run that recorded requests.
|
||||
const parts = new Map<string, number>();
|
||||
for (const { udid, filePath, size } of captures) {
|
||||
const part = (parts.get(udid) ?? 0) + 1;
|
||||
parts.set(udid, part);
|
||||
await uploadServeSimNetworkCaptureFileAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
udid,
|
||||
filePath,
|
||||
size,
|
||||
part,
|
||||
logger,
|
||||
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not upload the network capture', error);
|
||||
logger.warn({ err: error }, 'Could not upload the network capture.');
|
||||
} finally {
|
||||
if (outputDirectory) {
|
||||
await rm(outputDirectory, { recursive: true, force: true }).catch(err => {
|
||||
logger.warn(
|
||||
{ err },
|
||||
`Could not remove the network capture directory ${outputDirectory}.`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { SystemError, formatBytes } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import {
|
||||
@@ -15,7 +15,6 @@ import stream from 'stream';
|
||||
import { promisify } from 'util';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { decompressTarAsync, isFileTarGzAsync } from '../../utils/files';
|
||||
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError, UserError } from '@expo/eas-build-job';
|
||||
import { SystemError, UserError, formatBytes } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import {
|
||||
@@ -23,7 +23,6 @@ import bplistParser from 'bplist-parser';
|
||||
import plist from 'plist';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { decompressTarAsync, isFileTarGzAsync } from '../../utils/files';
|
||||
import { graphqlAbortContext } from '../../utils/graphqlAbort';
|
||||
import {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BuildFunction } from '@expo/steps';
|
||||
import { BuildFunction, BuildStepContext, BuildStepEnv } from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
|
||||
export function createInstallPodsBuildFunction(): BuildFunction {
|
||||
@@ -8,29 +8,36 @@ export function createInstallPodsBuildFunction(): BuildFunction {
|
||||
name: 'Install Pods',
|
||||
__metricsId: 'eas/install_pods',
|
||||
fn: async (stepsCtx, { env }) => {
|
||||
stepsCtx.logger.info('Installing pods');
|
||||
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
|
||||
const cocoapodsDeploymentFlag =
|
||||
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
|
||||
await runPodInstallAsync(stepsCtx, env);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
|
||||
logger: stepsCtx.logger,
|
||||
env: {
|
||||
...env,
|
||||
LANG: 'en_US.UTF-8',
|
||||
},
|
||||
cwd: stepsCtx.workingDirectory,
|
||||
lineTransformer: (line?: string) => {
|
||||
if (
|
||||
!line ||
|
||||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
|
||||
) {
|
||||
return null;
|
||||
} else {
|
||||
return line;
|
||||
}
|
||||
},
|
||||
});
|
||||
export async function runPodInstallAsync(
|
||||
stepsCtx: BuildStepContext,
|
||||
env: BuildStepEnv
|
||||
): Promise<void> {
|
||||
stepsCtx.logger.info('Installing pods');
|
||||
const verboseFlag = stepsCtx.global.env['EAS_VERBOSE'] === '1' ? ['--verbose'] : [];
|
||||
const cocoapodsDeploymentFlag =
|
||||
stepsCtx.global.env['POD_INSTALL_DEPLOYMENT'] === '1' ? ['--deployment'] : [];
|
||||
|
||||
await spawn('pod', ['install', ...verboseFlag, ...cocoapodsDeploymentFlag], {
|
||||
logger: stepsCtx.logger,
|
||||
env: {
|
||||
...env,
|
||||
LANG: 'en_US.UTF-8',
|
||||
},
|
||||
cwd: stepsCtx.workingDirectory,
|
||||
lineTransformer: (line?: string) => {
|
||||
if (
|
||||
!line ||
|
||||
/\[!\] '[\w-]+' uses the unencrypted 'http' protocol to transfer the Pod\./.exec(line)
|
||||
) {
|
||||
return null;
|
||||
} else {
|
||||
return line;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -211,7 +211,9 @@ const MaestroRunnerRecordedFlowSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
sourceFile: z.string().min(1),
|
||||
status: z.enum(['passed', 'failed']),
|
||||
tags: z.array(z.string()).optional(),
|
||||
});
|
||||
type MaestroRunnerRecordedFlow = z.infer<typeof MaestroRunnerRecordedFlowSchema>;
|
||||
const MaestroRunnerReportSchema = z.object({
|
||||
flows: z
|
||||
.array(
|
||||
@@ -379,6 +381,111 @@ export async function parseFailedFlowsFromFileAttrs(args: {
|
||||
return paths;
|
||||
}
|
||||
|
||||
const MAESTRO_RUNNER_ATTEMPT_DIRECTORY_PATTERN = /-maestro-runner-attempt-(\d+)$/;
|
||||
|
||||
export function maestroRunnerAttemptDirectoryName(args: {
|
||||
platform: string;
|
||||
attempt: number;
|
||||
}): string {
|
||||
return `${args.platform}-maestro-runner-attempt-${args.attempt}`;
|
||||
}
|
||||
|
||||
async function listMaestroRunnerAttemptDirectories(
|
||||
testsDirectory: string
|
||||
): Promise<{ attempt: number; reportDirectory: string }[]> {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await fs.readdir(testsDirectory);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries.flatMap(entry => {
|
||||
const match = entry.match(MAESTRO_RUNNER_ATTEMPT_DIRECTORY_PATTERN);
|
||||
return match
|
||||
? [{ attempt: parseInt(match[1], 10), reportDirectory: path.join(testsDirectory, entry) }]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
export async function hasMaestroRunnerAttemptDirectories(testsDirectory: string): Promise<boolean> {
|
||||
return (await listMaestroRunnerAttemptDirectories(testsDirectory)).length > 0;
|
||||
}
|
||||
|
||||
export async function parseMaestroRunnerResults(args: {
|
||||
junitDirectory: string;
|
||||
testsDirectory: string;
|
||||
workingDirectory: string;
|
||||
}): Promise<MaestroFlowResult[]> {
|
||||
const results = await parseMaestroResultsFromFileAttrs(args.junitDirectory);
|
||||
|
||||
const attempts = await listMaestroRunnerAttemptDirectories(args.testsDirectory);
|
||||
const flows = await Promise.all(
|
||||
attempts.map(({ reportDirectory }) =>
|
||||
parseMaestroRunnerFlowsWithPaths({
|
||||
reportDirectory,
|
||||
workingDirectory: args.workingDirectory,
|
||||
})
|
||||
)
|
||||
);
|
||||
const flowsByAttempt = new Map(attempts.map(({ attempt }, index) => [attempt, flows[index]]));
|
||||
const realWorkingDirectory = await resolveRealPath(args.workingDirectory);
|
||||
|
||||
return results.map(result => {
|
||||
const tags = findMaestroRunnerFlowTags({
|
||||
flows: flowsByAttempt.get(result.retryCount) ?? [],
|
||||
junitFlowPath: result.path,
|
||||
workingDirectory: args.workingDirectory,
|
||||
realWorkingDirectory,
|
||||
});
|
||||
return tags ? { ...result, tags } : result;
|
||||
});
|
||||
}
|
||||
|
||||
type MaestroRunnerFlowWithPaths = MaestroRunnerRecordedFlow & {
|
||||
resolvedPath: string;
|
||||
realPath: string;
|
||||
};
|
||||
|
||||
// maestro-runner >= 1.1.18 resolves symlinks in the JUnit path, but not in report.json.
|
||||
async function parseMaestroRunnerFlowsWithPaths(args: {
|
||||
reportDirectory: string;
|
||||
workingDirectory: string;
|
||||
}): Promise<MaestroRunnerFlowWithPaths[]> {
|
||||
const report = await parseMaestroRunnerReport(args.reportDirectory);
|
||||
return await Promise.all(
|
||||
(report?.flows ?? []).map(async flow => {
|
||||
const resolvedPath = path.resolve(args.workingDirectory, flow.sourceFile);
|
||||
return { ...flow, resolvedPath, realPath: await resolveRealPath(resolvedPath) };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveRealPath(filePath: string): Promise<string> {
|
||||
const realPathResult = await asyncResult(fs.realpath(filePath));
|
||||
return realPathResult.ok ? realPathResult.value : filePath;
|
||||
}
|
||||
|
||||
function findMaestroRunnerFlowTags(args: {
|
||||
flows: MaestroRunnerFlowWithPaths[];
|
||||
junitFlowPath: string;
|
||||
workingDirectory: string;
|
||||
realWorkingDirectory: string;
|
||||
}): string[] | undefined {
|
||||
const junitPath = path.resolve(args.workingDirectory, args.junitFlowPath);
|
||||
const junitRealPath = path.resolve(args.realWorkingDirectory, args.junitFlowPath);
|
||||
const samePath = args.flows.find(
|
||||
flow => flow.resolvedPath === junitPath || flow.realPath === junitRealPath
|
||||
);
|
||||
if (samePath) {
|
||||
return samePath.tags;
|
||||
}
|
||||
// maestro-runner <= 1.1.17 writes only the file name to JUnit.
|
||||
const sameFileName = args.flows.filter(
|
||||
flow => path.basename(flow.sourceFile) === args.junitFlowPath
|
||||
);
|
||||
return sameFileName.length === 1 ? sameFileName[0].tags : undefined;
|
||||
}
|
||||
|
||||
export async function parseMaestroResults(
|
||||
junitDirectory: string,
|
||||
nameToPath: Map<string, string> | null
|
||||
|
||||
@@ -18,6 +18,7 @@ import { buildFlowNameToPathMap } from './maestroFlowDiscovery';
|
||||
import {
|
||||
copyLatestAttemptXml,
|
||||
junitFileHasFileAttrs,
|
||||
maestroRunnerAttemptDirectoryName,
|
||||
mergeJUnitReports,
|
||||
parseFailedFlowNamesFromJUnitFile,
|
||||
parseFailedFlowsFromFileAttrs,
|
||||
@@ -353,7 +354,7 @@ export function createMaestroTestsBuildFunction(ctx: CustomBuildContext): BuildF
|
||||
// maestro-runner writes all report formats and screenshot metadata here.
|
||||
const runnerOutputDirectory = path.join(
|
||||
testsDirectory,
|
||||
`${platform}-maestro-runner-attempt-${attempt}`
|
||||
maestroRunnerAttemptDirectoryName({ platform, attempt })
|
||||
);
|
||||
const outputPath = mayHaveJUnitReports
|
||||
? path.join(junitReportDirectory, `${platform}-maestro-junit-attempt-${attempt}.xml`)
|
||||
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
import { vol } from 'memfs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import IosCredentialsManager from '../../../../utils/ios/credentials/manager';
|
||||
import { DistributionType } from '../../../../utils/ios/credentials/provisioningProfile';
|
||||
import { runFastlaneGym } from '../../../../utils/ios/fastlane';
|
||||
import {
|
||||
assertSigningBuildSettingsAreEffectiveAsync,
|
||||
writeSigningBuildSettingsAsync,
|
||||
} from '../../../../utils/ios/xcodeProject/signing';
|
||||
import { createBuildNativeIosBuildFunction } from '../buildNativeIos';
|
||||
|
||||
jest.mock('../../../../utils/ios/credentials/manager');
|
||||
jest.mock('../../../../utils/ios/fastlane');
|
||||
jest.mock('../../../../utils/ios/xcodeProject/signing');
|
||||
|
||||
const projectDirectory = '/project';
|
||||
const TARGETS = [
|
||||
{ id: 'APP', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
|
||||
{ id: 'WIDGET', name: 'Widget', bundleIdentifier: 'dev.expo.nativeapp.widget' },
|
||||
];
|
||||
const DISTRIBUTION_CERTIFICATE = { dataBase64: 'Y2VydGlmaWNhdGU=', password: '' };
|
||||
const APP_CREDENTIALS = {
|
||||
provisioningProfileBase64: 'YXBw',
|
||||
distributionCertificate: DISTRIBUTION_CERTIFICATE,
|
||||
};
|
||||
const WIDGET_CREDENTIALS = {
|
||||
provisioningProfileBase64: 'd2lkZ2V0',
|
||||
distributionCertificate: DISTRIBUTION_CERTIFICATE,
|
||||
};
|
||||
|
||||
function infoPlist(bundleIdentifier: string): string {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${bundleIdentifier}</string></dict></plist>`;
|
||||
}
|
||||
|
||||
function createBuildStep({
|
||||
job,
|
||||
projectFile = '/project/NativeApp.xcodeproj',
|
||||
targets = TARGETS,
|
||||
}: {
|
||||
job: Record<string, unknown>;
|
||||
projectFile?: string;
|
||||
targets?: typeof TARGETS;
|
||||
}): ReturnType<
|
||||
ReturnType<typeof createBuildNativeIosBuildFunction>['createBuildStepFromFunctionCall']
|
||||
> {
|
||||
const globalCtx = createGlobalContextMock({
|
||||
projectTargetDirectory: projectDirectory,
|
||||
staticContextContent: { job },
|
||||
});
|
||||
return createBuildNativeIosBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: {
|
||||
project_file: projectFile,
|
||||
scheme: 'NativeApp',
|
||||
build_configuration: 'Release',
|
||||
xcodeproj_path: '/project/NativeApp.xcodeproj',
|
||||
targets,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function mockGymProducing(relativePaths: Record<string, string>): { gymfile: () => string } {
|
||||
let gymfileDirectory = '';
|
||||
jest.mocked(runFastlaneGym).mockImplementation(async options => {
|
||||
gymfileDirectory = options.gymfileDirectory!;
|
||||
vol.fromJSON(relativePaths, gymfileDirectory);
|
||||
});
|
||||
return {
|
||||
gymfile: () => vol.readFileSync(path.join(gymfileDirectory, 'Gymfile'), 'utf-8') as string,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vol.fromJSON({ [path.join(os.tmpdir(), 'placeholder')]: '', '/project/placeholder': '' });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(createBuildNativeIosBuildFunction, () => {
|
||||
it('signs every detected target with the credentials of its bundle identifier and archives', async () => {
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.APP_STORE,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
|
||||
Widget: { name: 'Widget Profile', uuid: 'widget-uuid', teamId: 'ABCDE12345' },
|
||||
},
|
||||
} as any);
|
||||
const gym = mockGymProducing({ 'output/NativeApp.ipa': '' });
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: {
|
||||
credentialsByBundleIdentifier: {
|
||||
'dev.expo.nativeapp.widget': WIDGET_CREDENTIALS,
|
||||
'dev.expo.nativeapp': APP_CREDENTIALS,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(IosCredentialsManager).toHaveBeenCalledWith({
|
||||
NativeApp: APP_CREDENTIALS,
|
||||
Widget: WIDGET_CREDENTIALS,
|
||||
});
|
||||
const expectedSigning = expect.objectContaining({
|
||||
xcodeprojPath: '/project/NativeApp.xcodeproj',
|
||||
buildConfiguration: 'Release',
|
||||
targetSignings: [
|
||||
{
|
||||
target: TARGETS[0],
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'App Profile',
|
||||
DEVELOPMENT_TEAM: 'ABCDE12345',
|
||||
CODE_SIGN_IDENTITY: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
},
|
||||
{
|
||||
target: TARGETS[1],
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: 'Widget Profile',
|
||||
DEVELOPMENT_TEAM: 'ABCDE12345',
|
||||
CODE_SIGN_IDENTITY: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(writeSigningBuildSettingsAsync).toHaveBeenCalledWith(expectedSigning);
|
||||
expect(assertSigningBuildSettingsAreEffectiveAsync).toHaveBeenCalledWith(expectedSigning);
|
||||
const gymfile = gym.gymfile();
|
||||
expect(gymfile).toContain('project("/project/NativeApp.xcodeproj")');
|
||||
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
|
||||
expect(gymfile).toContain('scheme("NativeApp")');
|
||||
expect(gymfile).toContain('configuration("Release")');
|
||||
expect(gymfile).toContain('method: "app-store"');
|
||||
expect(gymfile).toContain('"dev.expo.nativeapp" => "app-uuid"');
|
||||
expect(gymfile).toContain('"dev.expo.nativeapp.widget" => "widget-uuid"');
|
||||
expect(gymfile).toContain('--keychain /keychains/build.keychain');
|
||||
expect(step.outputById.archive_path.value).toMatch(
|
||||
/native-ios-build-[^/]+\/output\/NativeApp\.ipa$/
|
||||
);
|
||||
expect(path.isAbsolute(step.outputById.archive_path.value as string)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses the common name of the certificate as the identity for a development profile', async () => {
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.DEVELOPMENT,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: {
|
||||
name: 'Development Profile',
|
||||
uuid: 'app-uuid',
|
||||
teamId: 'ABCDE12345',
|
||||
certificateCommonName: 'Apple Development: Example (ABCDE12345)',
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
mockGymProducing({ 'output/NativeApp.ipa': '' });
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(
|
||||
jest.mocked(writeSigningBuildSettingsAsync).mock.calls[0][0].targetSignings[0].buildSettings
|
||||
.CODE_SIGN_IDENTITY
|
||||
).toBe('Apple Development: Example (ABCDE12345)');
|
||||
});
|
||||
|
||||
it('builds for the simulator without credentials and returns the app with the bundle identifier', async () => {
|
||||
const products = 'derived-data/Build/Products/Release-iphonesimulator';
|
||||
const gym = mockGymProducing({
|
||||
[`${products}/Clip.app/Info.plist`]: infoPlist('dev.expo.nativeapp.clip'),
|
||||
[`${products}/NativeApp.app/Info.plist`]: infoPlist('dev.expo.nativeapp'),
|
||||
});
|
||||
const step = createBuildStep({
|
||||
job: { simulator: true, secrets: {} },
|
||||
projectFile: '/project/NativeApp.xcworkspace',
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(IosCredentialsManager).not.toHaveBeenCalled();
|
||||
expect(writeSigningBuildSettingsAsync).not.toHaveBeenCalled();
|
||||
const gymfile = gym.gymfile();
|
||||
expect(gymfile).toContain('workspace("/project/NativeApp.xcworkspace")');
|
||||
expect(gymfile).toContain('destination("generic/platform=iOS Simulator")');
|
||||
expect(gymfile).toContain('xcargs("-skipPackagePluginValidation -skipMacroValidation")');
|
||||
expect(gymfile).not.toContain('export_options');
|
||||
expect(step.outputById.archive_path.value).toMatch(/Release-iphonesimulator\/NativeApp\.app$/);
|
||||
expect(runFastlaneGym).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workingDir: projectDirectory,
|
||||
gymfileDirectory: expect.stringContaining('native-ios-build-'),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fails before it prepares credentials when a target has none', async () => {
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_MISSING_CREDENTIALS',
|
||||
message: expect.stringContaining(
|
||||
'no credentials for "dev.expo.nativeapp.widget" (target "Widget")'
|
||||
),
|
||||
});
|
||||
expect(IosCredentialsManager).not.toHaveBeenCalled();
|
||||
expect(runFastlaneGym).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails when the build produced no archive', async () => {
|
||||
mockGymProducing({ 'output/placeholder': '' });
|
||||
jest.mocked(IosCredentialsManager.prototype.prepare).mockResolvedValue({
|
||||
keychainPath: '/keychains/build.keychain',
|
||||
distributionType: DistributionType.AD_HOC,
|
||||
teamId: 'ABCDE12345',
|
||||
targetProvisioningProfiles: {
|
||||
NativeApp: { name: 'App Profile', uuid: 'app-uuid', teamId: 'ABCDE12345' },
|
||||
},
|
||||
} as any);
|
||||
const step = createBuildStep({
|
||||
job: {
|
||||
simulator: false,
|
||||
secrets: { credentialsByBundleIdentifier: { 'dev.expo.nativeapp': APP_CREDENTIALS } },
|
||||
},
|
||||
targets: [TARGETS[0]],
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_NO_BUILD_OUTPUT',
|
||||
});
|
||||
});
|
||||
});
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { vol } from 'memfs';
|
||||
import path from 'path';
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import { createDetectNativeXcodeBuildFunction } from '../detectNativeXcode';
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
|
||||
|
||||
const originalFs = jest.requireActual('fs');
|
||||
|
||||
const projectDirectory = '/project';
|
||||
const fixturesDirectory = path.join(
|
||||
__dirname,
|
||||
'../../../../utils/ios/xcodeProject/__tests__/fixtures'
|
||||
);
|
||||
const FRAMEWORK_ONLY_SCHEME = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme version = "1.3">
|
||||
<BuildAction>
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry buildForArchiving = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "BBCC7F97904CEBE3743A2D6F"
|
||||
BuildableName = "Core.framework"
|
||||
BlueprintName = "Core"
|
||||
ReferencedContainer = "container:NativeApp.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<LaunchAction buildConfiguration = "Debug"></LaunchAction>
|
||||
<ArchiveAction buildConfiguration = "Release"></ArchiveAction>
|
||||
</Scheme>`;
|
||||
|
||||
function writeProject(extraFiles: Record<string, string> = {}): void {
|
||||
vol.fromJSON(
|
||||
{
|
||||
'NativeApp.xcodeproj/project.pbxproj': originalFs.readFileSync(
|
||||
path.join(fixturesDirectory, 'native-app.pbxproj'),
|
||||
'utf-8'
|
||||
),
|
||||
'NativeApp.xcodeproj/xcshareddata/xcschemes/NativeApp.xcscheme': originalFs.readFileSync(
|
||||
path.join(fixturesDirectory, 'native-app.xcscheme'),
|
||||
'utf-8'
|
||||
),
|
||||
...extraFiles,
|
||||
},
|
||||
projectDirectory
|
||||
);
|
||||
}
|
||||
|
||||
function mockBuildSettings(bundleIdentifierByTargetName: Record<string, string>): void {
|
||||
jest.mocked(spawn).mockResolvedValue({
|
||||
stdout: JSON.stringify(
|
||||
Object.entries(bundleIdentifierByTargetName).map(([target, bundleIdentifier]) => ({
|
||||
action: 'build',
|
||||
target,
|
||||
buildSettings: { PRODUCT_BUNDLE_IDENTIFIER: bundleIdentifier },
|
||||
}))
|
||||
),
|
||||
} as any);
|
||||
}
|
||||
|
||||
function createDetectStep({
|
||||
job,
|
||||
callInputs = {},
|
||||
}: {
|
||||
job: Record<string, unknown>;
|
||||
callInputs?: Record<string, unknown>;
|
||||
}): ReturnType<
|
||||
ReturnType<typeof createDetectNativeXcodeBuildFunction>['createBuildStepFromFunctionCall']
|
||||
> {
|
||||
const globalCtx = createGlobalContextMock({
|
||||
projectTargetDirectory: projectDirectory,
|
||||
staticContextContent: { job },
|
||||
});
|
||||
return createDetectNativeXcodeBuildFunction().createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs,
|
||||
});
|
||||
}
|
||||
|
||||
const signedJob = { simulator: false };
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(createDetectNativeXcodeBuildFunction, () => {
|
||||
it('detects the project, the scheme, the archive configuration and the targets to sign', async () => {
|
||||
writeProject();
|
||||
mockBuildSettings({
|
||||
NativeApp: 'dev.expo.nativeapp',
|
||||
Widget: 'dev.expo.nativeapp.widget',
|
||||
});
|
||||
const step = createDetectStep({
|
||||
job: signedJob,
|
||||
callInputs: { expected_identifier: 'dev.expo.nativeapp' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(step.outputById.project_file.value).toBe('/project/NativeApp.xcodeproj');
|
||||
expect(step.outputById.scheme.value).toBe('NativeApp');
|
||||
expect(step.outputById.build_configuration.value).toBe('Release');
|
||||
expect(step.outputById.xcodeproj_path.value).toBe('/project/NativeApp.xcodeproj');
|
||||
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
|
||||
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
|
||||
{
|
||||
id: '5CAE5500641C3F327B201839',
|
||||
name: 'Widget',
|
||||
bundleIdentifier: 'dev.expo.nativeapp.widget',
|
||||
},
|
||||
]);
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'xcodebuild',
|
||||
[
|
||||
'-project',
|
||||
'/project/NativeApp.xcodeproj',
|
||||
'-target',
|
||||
'NativeApp',
|
||||
'-target',
|
||||
'Widget',
|
||||
'-configuration',
|
||||
'Release',
|
||||
'-showBuildSettings',
|
||||
'-json',
|
||||
],
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('uses the Run configuration and only the application target for a simulator build', async () => {
|
||||
writeProject();
|
||||
mockBuildSettings({ NativeApp: 'dev.expo.nativeapp' });
|
||||
const step = createDetectStep({ job: { simulator: true } });
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(step.outputById.build_configuration.value).toBe('Debug');
|
||||
expect(JSON.parse(step.outputById.targets.value as string)).toEqual([
|
||||
{ id: '2870BA69F546F142D461562E', name: 'NativeApp', bundleIdentifier: 'dev.expo.nativeapp' },
|
||||
]);
|
||||
expect(jest.mocked(spawn).mock.calls[0][1]).toEqual(
|
||||
expect.arrayContaining(['-target', 'NativeApp', '-configuration', 'Debug'])
|
||||
);
|
||||
expect(jest.mocked(spawn).mock.calls[0][1]).not.toContain('Widget');
|
||||
});
|
||||
|
||||
it('uses the given build configuration', async () => {
|
||||
writeProject();
|
||||
mockBuildSettings({
|
||||
NativeApp: 'dev.expo.nativeapp',
|
||||
Widget: 'dev.expo.nativeapp.widget',
|
||||
});
|
||||
const step = createDetectStep({
|
||||
job: signedJob,
|
||||
callInputs: { build_configuration: 'Debug' },
|
||||
});
|
||||
|
||||
await step.executeAsync();
|
||||
|
||||
expect(step.outputById.build_configuration.value).toBe('Debug');
|
||||
});
|
||||
|
||||
it('fails with the build configurations of the target when the given one does not exist', async () => {
|
||||
writeProject();
|
||||
const step = createDetectStep({
|
||||
job: signedJob,
|
||||
callInputs: { build_configuration: 'Staging' },
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
|
||||
message: expect.stringContaining(
|
||||
'"Staging". Build configurations of the target: Debug, Release.'
|
||||
),
|
||||
});
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails when the bundle identifier differs from the expected identifier', async () => {
|
||||
writeProject();
|
||||
mockBuildSettings({
|
||||
NativeApp: 'dev.expo.nativeapp',
|
||||
Widget: 'dev.expo.nativeapp.widget',
|
||||
});
|
||||
const step = createDetectStep({
|
||||
job: signedJob,
|
||||
callInputs: { expected_identifier: 'dev.expo.other' },
|
||||
});
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
|
||||
message: expect.stringMatching(/"dev\.expo\.other".*"NativeApp".*"dev\.expo\.nativeapp"/),
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when a target to sign has no bundle identifier', async () => {
|
||||
writeProject();
|
||||
mockBuildSettings({ NativeApp: 'dev.expo.nativeapp' });
|
||||
const step = createDetectStep({ job: signedJob });
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
|
||||
message: expect.stringContaining('The target "Widget" has no bundle identifier'),
|
||||
});
|
||||
});
|
||||
|
||||
it('fails with the other schemes when the scheme builds no application', async () => {
|
||||
writeProject({
|
||||
'NativeApp.xcodeproj/xcshareddata/xcschemes/Core.xcscheme': FRAMEWORK_ONLY_SCHEME,
|
||||
});
|
||||
const step = createDetectStep({ job: signedJob, callInputs: { scheme: 'Core' } });
|
||||
|
||||
await expect(step.executeAsync()).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_NO_APPLICATION_TARGET',
|
||||
message: expect.stringMatching(/scheme "Core".*Other shared schemes: NativeApp\./),
|
||||
});
|
||||
});
|
||||
});
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
import { vol } from 'memfs';
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import { createInstallNativePodsBuildFunction } from '../installNativePods';
|
||||
|
||||
jest.mock('@expo/turtle-spawn', () => ({ __esModule: true, default: jest.fn() }));
|
||||
|
||||
const projectDirectory = '/project';
|
||||
|
||||
async function runInstallNativePodsAsync(): Promise<void> {
|
||||
const globalCtx = createGlobalContextMock({ projectTargetDirectory: projectDirectory });
|
||||
await createInstallNativePodsBuildFunction()
|
||||
.createBuildStepFromFunctionCall(globalCtx)
|
||||
.executeAsync();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vol.reset();
|
||||
});
|
||||
|
||||
describe(createInstallNativePodsBuildFunction, () => {
|
||||
it('runs pod install in the project directory when it has a Podfile', async () => {
|
||||
vol.fromJSON({ Podfile: '', 'App.xcodeproj/project.pbxproj': '' }, projectDirectory);
|
||||
|
||||
await runInstallNativePodsAsync();
|
||||
|
||||
expect(spawn).toHaveBeenCalledTimes(1);
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'pod',
|
||||
['install'],
|
||||
expect.objectContaining({ cwd: projectDirectory })
|
||||
);
|
||||
});
|
||||
|
||||
it('does nothing when the project directory has no Podfile', async () => {
|
||||
vol.fromJSON({ 'App.xcodeproj/project.pbxproj': '', 'ios/Podfile': '' }, projectDirectory);
|
||||
|
||||
await runInstallNativePodsAsync();
|
||||
|
||||
expect(spawn).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
jest.unmock('fs/promises');
|
||||
jest.unmock('node:fs/promises');
|
||||
|
||||
import { createGlobalContextMock } from '../../../../../__tests__/utils/context';
|
||||
import { createVerifyNativeIosBuildFunction } from '../verifyNativeIos';
|
||||
|
||||
const IPA_PATH = path.join(__dirname, '../../../__tests__/fixtures/SmallestAppExample.ipa');
|
||||
const IPA_BUNDLE_IDENTIFIER = 'dev.expo.SmallestAppExample';
|
||||
|
||||
async function writeAppAsync(bundleIdentifier: string, platformName: string): Promise<string> {
|
||||
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'verify-native-ios-'));
|
||||
const appPath = path.join(directory, 'NativeApp.app');
|
||||
await fs.promises.mkdir(appPath);
|
||||
await fs.promises.writeFile(
|
||||
path.join(appPath, 'Info.plist'),
|
||||
`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleIdentifier</key><string>${bundleIdentifier}</string>
|
||||
<key>DTPlatformName</key><string>${platformName}</string>
|
||||
</dict></plist>`
|
||||
);
|
||||
return appPath;
|
||||
}
|
||||
|
||||
async function verifyAsync({
|
||||
simulator,
|
||||
archivePath,
|
||||
expectedIdentifier,
|
||||
}: {
|
||||
simulator: boolean;
|
||||
archivePath: string;
|
||||
expectedIdentifier?: string;
|
||||
}): Promise<void> {
|
||||
const globalCtx = createGlobalContextMock({ staticContextContent: { job: { simulator } } });
|
||||
await createVerifyNativeIosBuildFunction()
|
||||
.createBuildStepFromFunctionCall(globalCtx, {
|
||||
callInputs: { archive_path: archivePath, expected_identifier: expectedIdentifier },
|
||||
})
|
||||
.executeAsync();
|
||||
}
|
||||
|
||||
describe(createVerifyNativeIosBuildFunction, () => {
|
||||
it('accepts an IPA for devices with the expected identifier', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: false,
|
||||
archivePath: IPA_PATH,
|
||||
expectedIdentifier: IPA_BUNDLE_IDENTIFIER,
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts a simulator app with the expected identifier', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: true,
|
||||
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
|
||||
expectedIdentifier: 'dev.expo.nativeapp',
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts an artifact when no identifier is expected', async () => {
|
||||
await expect(verifyAsync({ simulator: false, archivePath: IPA_PATH })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails when the identifier of the artifact differs', async () => {
|
||||
await expect(
|
||||
verifyAsync({ simulator: false, archivePath: IPA_PATH, expectedIdentifier: 'dev.expo.other' })
|
||||
).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
|
||||
message: expect.stringMatching(/"dev\.expo\.SmallestAppExample".*"dev\.expo\.other"/),
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when a simulator build produced an artifact for devices', async () => {
|
||||
await expect(verifyAsync({ simulator: true, archivePath: IPA_PATH })).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when a device build produced an artifact for the simulator', async () => {
|
||||
await expect(
|
||||
verifyAsync({
|
||||
simulator: false,
|
||||
archivePath: await writeAppAsync('dev.expo.nativeapp', 'iphonesimulator'),
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
errorCode: 'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
message: expect.stringContaining('"iphonesimulator"'),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
import { Ios, UserError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildStepContext,
|
||||
BuildStepEnv,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import { templateString } from '@expo/template-file';
|
||||
import fg from 'fast-glob';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { GymfileArchiveTemplate } from '../../../../templates/GymfileArchive';
|
||||
import { GymfileSimulatorTemplate } from '../../../../templates/GymfileSimulator';
|
||||
import IosCredentialsManager from '../../../utils/ios/credentials/manager';
|
||||
import { DistributionType } from '../../../utils/ios/credentials/provisioningProfile';
|
||||
import { runFastlaneGym } from '../../../utils/ios/fastlane';
|
||||
import { XcodeTargetWithBundleIdentifier } from '../../../utils/ios/xcodeProject/pbxproj';
|
||||
import { isWorkspace } from '../../../utils/ios/xcodeProject/projectFile';
|
||||
import {
|
||||
assertSigningBuildSettingsAreEffectiveAsync,
|
||||
writeSigningBuildSettingsAsync,
|
||||
} from '../../../utils/ios/xcodeProject/signing';
|
||||
import { parseInfoPlistBuffer } from '../../readIpaInfo';
|
||||
|
||||
interface ExportSigning {
|
||||
keychainPath: string;
|
||||
distributionType: DistributionType;
|
||||
provisioningProfileUuidByBundleIdentifier: Record<string, string>;
|
||||
}
|
||||
|
||||
export function createBuildNativeIosBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'build_native_ios',
|
||||
name: 'Build with Xcode',
|
||||
__metricsId: 'eas/build_native_ios',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'project_file',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'scheme',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'build_configuration',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'xcodeproj_path',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'targets',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.JSON,
|
||||
}),
|
||||
],
|
||||
outputProviders: [BuildStepOutput.createProvider({ id: 'archive_path', required: true })],
|
||||
fn: async (stepsCtx, { inputs, outputs, env }) => {
|
||||
const job = stepsCtx.global.staticContext.job as Ios.Job;
|
||||
const projectFilePath = inputs.project_file.value as string;
|
||||
const scheme = inputs.scheme.value as string;
|
||||
const buildConfiguration = inputs.build_configuration.value as string;
|
||||
const targets = inputs.targets.value as unknown as XcodeTargetWithBundleIdentifier[];
|
||||
const [applicationTarget] = targets;
|
||||
|
||||
const exportSigning = job.simulator
|
||||
? undefined
|
||||
: await configureSigningAsync(stepsCtx, {
|
||||
credentialsByBundleIdentifier: job.secrets?.credentialsByBundleIdentifier ?? {},
|
||||
targets,
|
||||
xcodeprojPath: inputs.xcodeproj_path.value as string,
|
||||
buildConfiguration,
|
||||
env,
|
||||
});
|
||||
|
||||
const buildDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'native-ios-build-'));
|
||||
const derivedDataPath = path.join(buildDirectory, 'derived-data');
|
||||
const outputDirectory = path.join(buildDirectory, 'output');
|
||||
await fs.promises.writeFile(
|
||||
path.join(buildDirectory, 'Gymfile'),
|
||||
createGymfile({
|
||||
projectFilePath,
|
||||
scheme,
|
||||
buildConfiguration,
|
||||
derivedDataPath,
|
||||
outputDirectory,
|
||||
resultBundlePath: path.join(buildDirectory, 'build.xcresult'),
|
||||
logsDirectory: stepsCtx.global.buildLogsDirectory,
|
||||
exportSigning,
|
||||
})
|
||||
);
|
||||
await fs.promises.mkdir(stepsCtx.global.buildLogsDirectory, { recursive: true });
|
||||
await runFastlaneGym({
|
||||
workingDir: stepsCtx.workingDirectory,
|
||||
gymfileDirectory: buildDirectory,
|
||||
logger: stepsCtx.logger,
|
||||
buildLogsDirectory: stepsCtx.global.buildLogsDirectory,
|
||||
env,
|
||||
});
|
||||
|
||||
const archivePath = job.simulator
|
||||
? await findSimulatorAppAsync(derivedDataPath, applicationTarget.bundleIdentifier)
|
||||
: (await fg('*.ipa', { cwd: outputDirectory, absolute: true }))[0];
|
||||
if (!archivePath) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_NO_BUILD_OUTPUT',
|
||||
job.simulator
|
||||
? `The build finished, but EAS found no ".app" with the bundle identifier "${applicationTarget.bundleIdentifier}" in "${derivedDataPath}/Build/Products". Check in the Xcode logs which products the scheme "${scheme}" built.`
|
||||
: `The build finished, but EAS found no ".ipa" in "${outputDirectory}". Check the Xcode logs for an export error.`
|
||||
);
|
||||
}
|
||||
outputs.archive_path.set(archivePath);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function configureSigningAsync(
|
||||
{ logger }: BuildStepContext,
|
||||
{
|
||||
credentialsByBundleIdentifier,
|
||||
targets,
|
||||
xcodeprojPath,
|
||||
buildConfiguration,
|
||||
env,
|
||||
}: {
|
||||
credentialsByBundleIdentifier: Record<string, Ios.TargetCredentials>;
|
||||
targets: XcodeTargetWithBundleIdentifier[];
|
||||
xcodeprojPath: string;
|
||||
buildConfiguration: string;
|
||||
env: BuildStepEnv;
|
||||
}
|
||||
): Promise<ExportSigning> {
|
||||
const targetsWithoutCredentials = targets.filter(
|
||||
({ bundleIdentifier }) => !credentialsByBundleIdentifier[bundleIdentifier]
|
||||
);
|
||||
if (targetsWithoutCredentials.length > 0) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_MISSING_CREDENTIALS',
|
||||
`The build job has no credentials for ${targetsWithoutCredentials
|
||||
.map(({ name, bundleIdentifier }) => `"${bundleIdentifier}" (target "${name}")`)
|
||||
.join(
|
||||
', '
|
||||
)}. EAS signs the application target and every target it depends on, except frameworks, and each one needs credentials for its bundle identifier. Add each bundle identifier with a distribution certificate and a provisioning profile on the Credentials page of the project on expo.dev, then run the build again.`
|
||||
);
|
||||
}
|
||||
|
||||
const credentialsByTargetName = Object.fromEntries(
|
||||
targets.map(({ name, bundleIdentifier }) => [
|
||||
name,
|
||||
credentialsByBundleIdentifier[bundleIdentifier],
|
||||
])
|
||||
);
|
||||
const { keychainPath, distributionType, targetProvisioningProfiles } =
|
||||
await new IosCredentialsManager(credentialsByTargetName).prepare(logger);
|
||||
|
||||
const targetSignings = targets.map(target => {
|
||||
const profile = targetProvisioningProfiles[target.name];
|
||||
logger.info(
|
||||
`Assigning provisioning profile '${profile.name}' (Apple Team ID: ${profile.teamId}) to target '${target.name}'`
|
||||
);
|
||||
return {
|
||||
target,
|
||||
buildSettings: {
|
||||
PROVISIONING_PROFILE_SPECIFIER: profile.name,
|
||||
DEVELOPMENT_TEAM: profile.teamId,
|
||||
CODE_SIGN_IDENTITY:
|
||||
distributionType === DistributionType.DEVELOPMENT
|
||||
? profile.certificateCommonName
|
||||
: 'iPhone Distribution',
|
||||
CODE_SIGN_STYLE: 'Manual',
|
||||
},
|
||||
};
|
||||
});
|
||||
await writeSigningBuildSettingsAsync({ xcodeprojPath, buildConfiguration, targetSignings });
|
||||
await assertSigningBuildSettingsAreEffectiveAsync({
|
||||
xcodeprojPath,
|
||||
buildConfiguration,
|
||||
targetSignings,
|
||||
env,
|
||||
logger,
|
||||
});
|
||||
|
||||
return {
|
||||
keychainPath,
|
||||
distributionType,
|
||||
provisioningProfileUuidByBundleIdentifier: Object.fromEntries(
|
||||
targets.map(({ name, bundleIdentifier }) => [
|
||||
bundleIdentifier,
|
||||
targetProvisioningProfiles[name].uuid,
|
||||
])
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function createGymfile({
|
||||
projectFilePath,
|
||||
scheme,
|
||||
buildConfiguration,
|
||||
derivedDataPath,
|
||||
outputDirectory,
|
||||
resultBundlePath,
|
||||
logsDirectory,
|
||||
exportSigning,
|
||||
}: {
|
||||
projectFilePath: string;
|
||||
scheme: string;
|
||||
buildConfiguration: string;
|
||||
derivedDataPath: string;
|
||||
outputDirectory: string;
|
||||
resultBundlePath: string;
|
||||
logsDirectory: string;
|
||||
exportSigning?: ExportSigning;
|
||||
}): string {
|
||||
const sharedVars = {
|
||||
SCHEME: scheme,
|
||||
SCHEME_BUILD_CONFIGURATION: buildConfiguration,
|
||||
DERIVED_DATA_PATH: derivedDataPath,
|
||||
RESULT_BUNDLE_PATH: resultBundlePath,
|
||||
CLEAN: 'false',
|
||||
LOGS_DIRECTORY: logsDirectory,
|
||||
};
|
||||
return [
|
||||
`${isWorkspace(projectFilePath) ? 'workspace' : 'project'}(${JSON.stringify(projectFilePath)})`,
|
||||
// xcodebuild refuses Swift package plugins and macros until someone approves them in the Xcode UI.
|
||||
'xcargs("-skipPackagePluginValidation -skipMacroValidation")',
|
||||
exportSigning
|
||||
? templateString({
|
||||
input: GymfileArchiveTemplate,
|
||||
vars: {
|
||||
...sharedVars,
|
||||
OUTPUT_DIRECTORY: outputDirectory,
|
||||
KEYCHAIN_PATH: exportSigning.keychainPath,
|
||||
EXPORT_METHOD: exportSigning.distributionType,
|
||||
PROFILES: Object.entries(exportSigning.provisioningProfileUuidByBundleIdentifier).map(
|
||||
([bundleIdentifier, uuid]) => ({ BUNDLE_ID: bundleIdentifier, UUID: uuid })
|
||||
),
|
||||
// A lodash template throws when it reads a variable that was not passed.
|
||||
ICLOUD_CONTAINER_ENVIRONMENT: undefined,
|
||||
},
|
||||
mustache: false,
|
||||
})
|
||||
: templateString({
|
||||
input: GymfileSimulatorTemplate,
|
||||
vars: {
|
||||
...sharedVars,
|
||||
SCHEME_SIMULATOR_DESTINATION: 'generic/platform=iOS Simulator',
|
||||
},
|
||||
mustache: false,
|
||||
}),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function findSimulatorAppAsync(
|
||||
derivedDataPath: string,
|
||||
bundleIdentifier: string
|
||||
): Promise<string | undefined> {
|
||||
const appPaths = await fg('Build/Products/*-iphonesimulator/*.app', {
|
||||
cwd: derivedDataPath,
|
||||
onlyDirectories: true,
|
||||
absolute: true,
|
||||
});
|
||||
for (const appPath of appPaths) {
|
||||
const infoPlist = parseInfoPlistBuffer(
|
||||
await fs.promises.readFile(path.join(appPath, 'Info.plist'))
|
||||
);
|
||||
if (infoPlist.CFBundleIdentifier === bundleIdentifier) {
|
||||
return appPath;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { IOSConfig } from '@expo/config-plugins';
|
||||
import { Ios, UserError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import path from 'node:path';
|
||||
import { XcodeProject } from 'xcode';
|
||||
|
||||
import { readBuildSettingsByTargetNameAsync } from '../../../utils/ios/xcodeProject/buildSettings';
|
||||
import {
|
||||
XcodeTarget,
|
||||
XcodeTargetWithBundleIdentifier,
|
||||
findApplicationTargetById,
|
||||
findSignableDependencyTargets,
|
||||
getBuildConfigurations,
|
||||
openXcodeProject,
|
||||
} from '../../../utils/ios/xcodeProject/pbxproj';
|
||||
import { resolveProjectFilePathAsync } from '../../../utils/ios/xcodeProject/projectFile';
|
||||
import {
|
||||
XcodeSchemeDetails,
|
||||
findSharedSchemesAsync,
|
||||
readSchemeAsync,
|
||||
selectScheme,
|
||||
} from '../../../utils/ios/xcodeProject/schemes';
|
||||
|
||||
export function createDetectNativeXcodeBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'detect_native_xcode',
|
||||
name: 'Detect Xcode project',
|
||||
__metricsId: 'eas/detect_native_xcode',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'project_file',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'scheme',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'build_configuration',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'expected_identifier',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
outputProviders: [
|
||||
BuildStepOutput.createProvider({ id: 'project_file', required: true }),
|
||||
BuildStepOutput.createProvider({ id: 'scheme', required: true }),
|
||||
BuildStepOutput.createProvider({ id: 'build_configuration', required: true }),
|
||||
BuildStepOutput.createProvider({ id: 'xcodeproj_path', required: true }),
|
||||
BuildStepOutput.createProvider({ id: 'targets', required: true }),
|
||||
],
|
||||
fn: async (stepsCtx, { inputs, outputs, env }) => {
|
||||
const { logger, workingDirectory } = stepsCtx;
|
||||
const job = stepsCtx.global.staticContext.job as Ios.Job;
|
||||
const needsSigning = !job.simulator;
|
||||
|
||||
const projectFilePath = await resolveProjectFilePathAsync(
|
||||
workingDirectory,
|
||||
inputs.project_file.value as string | undefined
|
||||
);
|
||||
const schemes = await findSharedSchemesAsync(projectFilePath);
|
||||
const scheme = selectScheme(schemes, {
|
||||
requestedName: inputs.scheme.value as string | undefined,
|
||||
logger,
|
||||
});
|
||||
const { applicationTargetReference, archiveConfiguration, launchConfiguration } =
|
||||
await readSchemeAsync(scheme);
|
||||
|
||||
const application = openApplicationTarget(applicationTargetReference);
|
||||
if (!application) {
|
||||
const otherSchemeNames = schemes
|
||||
.map(({ name }) => name)
|
||||
.filter(name => name !== scheme.name);
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_NO_APPLICATION_TARGET',
|
||||
`The scheme "${scheme.name}" does not build an iOS application target, so EAS has no app to sign and upload. ${
|
||||
otherSchemeNames.length > 0
|
||||
? `Other shared schemes: ${otherSchemeNames.sort().join(', ')}. Set "xcode_scheme" to the scheme of the app.`
|
||||
: 'Share the scheme of the app in Xcode (Product > Scheme > Manage Schemes) and commit its ".xcscheme" file.'
|
||||
}`
|
||||
);
|
||||
}
|
||||
const { project, xcodeprojPath, target: applicationTarget } = application;
|
||||
|
||||
const buildConfiguration =
|
||||
(inputs.build_configuration.value as string | undefined) ??
|
||||
(needsSigning ? archiveConfiguration : launchConfiguration);
|
||||
const buildConfigurationNames = getBuildConfigurations(project, applicationTarget.id).map(
|
||||
({ name }) => IOSConfig.XcodeUtils.unquote(name)
|
||||
);
|
||||
if (!buildConfiguration || !buildConfigurationNames.includes(buildConfiguration)) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_BUILD_CONFIGURATION_NOT_FOUND',
|
||||
`${
|
||||
buildConfiguration
|
||||
? `The target "${applicationTarget.name}" has no build configuration named "${buildConfiguration}".`
|
||||
: `The scheme "${scheme.name}" names no build configuration for its ${needsSigning ? 'Archive' : 'Run'} action.`
|
||||
} Build configurations of the target: ${buildConfigurationNames.join(', ')}. Set "xcode_configuration" to one of them.`
|
||||
);
|
||||
}
|
||||
|
||||
const xcodeTargets = [
|
||||
applicationTarget,
|
||||
...(needsSigning ? findSignableDependencyTargets(project, applicationTarget.id) : []),
|
||||
];
|
||||
const buildSettingsByTargetName = await readBuildSettingsByTargetNameAsync({
|
||||
xcodeprojPath,
|
||||
targetNames: xcodeTargets.map(({ name }) => name),
|
||||
buildConfiguration,
|
||||
env,
|
||||
logger,
|
||||
});
|
||||
const targets: XcodeTargetWithBundleIdentifier[] = xcodeTargets.map(target => {
|
||||
const bundleIdentifier = buildSettingsByTargetName[target.name]?.PRODUCT_BUNDLE_IDENTIFIER;
|
||||
if (!bundleIdentifier) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_NO_BUNDLE_IDENTIFIER',
|
||||
`The target "${target.name}" has no bundle identifier in the build configuration "${buildConfiguration}". EAS signs the application target and every target it depends on, except frameworks, and picks the credentials by bundle identifier. Set PRODUCT_BUNDLE_IDENTIFIER for this target in Xcode. The Xcode builder cannot build a project whose application depends directly on a target that has no bundle identifier, such as a static library.`
|
||||
);
|
||||
}
|
||||
return { ...target, bundleIdentifier };
|
||||
});
|
||||
|
||||
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
|
||||
const [{ bundleIdentifier: applicationIdentifier }] = targets;
|
||||
if (expectedIdentifier && applicationIdentifier !== expectedIdentifier) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_APP_IDENTIFIER_MISMATCH',
|
||||
`"app_identifier" is "${expectedIdentifier}", but the target "${applicationTarget.name}" has the bundle identifier "${applicationIdentifier}" in the build configuration "${buildConfiguration}". Set "app_identifier" to "${applicationIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
|
||||
);
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Building the scheme "${scheme.name}" of "${path.basename(projectFilePath)}" with the build configuration "${buildConfiguration}".`
|
||||
);
|
||||
for (const { name, bundleIdentifier } of targets) {
|
||||
logger.info(`Target "${name}": ${bundleIdentifier}`);
|
||||
}
|
||||
|
||||
outputs.project_file.set(projectFilePath);
|
||||
outputs.scheme.set(scheme.name);
|
||||
outputs.build_configuration.set(buildConfiguration);
|
||||
outputs.xcodeproj_path.set(xcodeprojPath);
|
||||
outputs.targets.set(JSON.stringify(targets));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function openApplicationTarget(
|
||||
reference: XcodeSchemeDetails['applicationTargetReference']
|
||||
): { project: XcodeProject; xcodeprojPath: string; target: XcodeTarget } | undefined {
|
||||
if (!reference) {
|
||||
return undefined;
|
||||
}
|
||||
const project = openXcodeProject(reference.xcodeprojPath);
|
||||
const target = findApplicationTargetById(project, reference.targetId);
|
||||
return target && { project, xcodeprojPath: reference.xcodeprojPath, target };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { BuildFunction } from '@expo/steps';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { runPodInstallAsync } from '../../installPods';
|
||||
|
||||
export function createInstallNativePodsBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'install_native_pods',
|
||||
name: 'Install Pods',
|
||||
__metricsId: 'eas/install_native_pods',
|
||||
fn: async (stepsCtx, { env }) => {
|
||||
if (!fs.existsSync(path.join(stepsCtx.workingDirectory, 'Podfile'))) {
|
||||
stepsCtx.logger.info('The project directory has no Podfile. Skipping "pod install".');
|
||||
return;
|
||||
}
|
||||
await runPodInstallAsync(stepsCtx, env);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Ios, UserError } from '@expo/eas-build-job';
|
||||
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { parseInfoPlistBuffer, readIpaInfoAsync } from '../../readIpaInfo';
|
||||
|
||||
export function createVerifyNativeIosBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'verify_native_ios',
|
||||
name: 'Verify the build artifact',
|
||||
__metricsId: 'eas/verify_native_ios',
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'archive_path',
|
||||
required: true,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
BuildStepInput.createProvider({
|
||||
id: 'expected_identifier',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
fn: async (stepsCtx, { inputs }) => {
|
||||
const job = stepsCtx.global.staticContext.job as Ios.Job;
|
||||
const archivePath = inputs.archive_path.value as string;
|
||||
const expectedIdentifier = inputs.expected_identifier.value as string | undefined;
|
||||
const expectedPlatformName = job.simulator ? 'iphonesimulator' : 'iphoneos';
|
||||
|
||||
const { bundleIdentifier, platformName } = await readArtifactInfoAsync(archivePath);
|
||||
if (platformName !== expectedPlatformName) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_ARTIFACT_PLATFORM_MISMATCH',
|
||||
`The build artifact "${path.basename(archivePath)}" was built for "${platformName}", but this build is for ${
|
||||
job.simulator ? 'the iOS simulator' : 'iOS devices'
|
||||
} and needs "${expectedPlatformName}". Check that the scheme builds an iOS app.`
|
||||
);
|
||||
}
|
||||
if (expectedIdentifier && bundleIdentifier !== expectedIdentifier) {
|
||||
throw new UserError(
|
||||
'NATIVE_XCODE_ARTIFACT_IDENTIFIER_MISMATCH',
|
||||
`The build artifact "${path.basename(archivePath)}" has the bundle identifier "${bundleIdentifier}", but "app_identifier" is "${expectedIdentifier}". Set "app_identifier" to "${bundleIdentifier}", or set "xcode_scheme" and "xcode_configuration" to the ones that build "${expectedIdentifier}".`
|
||||
);
|
||||
}
|
||||
stepsCtx.logger.info(
|
||||
`Verified "${path.basename(archivePath)}": ${bundleIdentifier}, built for ${platformName}.`
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function readArtifactInfoAsync(
|
||||
archivePath: string
|
||||
): Promise<{ bundleIdentifier: unknown; platformName: unknown }> {
|
||||
if ((await fs.promises.stat(archivePath)).isDirectory()) {
|
||||
const infoPlist = parseInfoPlistBuffer(
|
||||
await fs.promises.readFile(path.join(archivePath, 'Info.plist'))
|
||||
);
|
||||
return {
|
||||
bundleIdentifier: infoPlist.CFBundleIdentifier,
|
||||
platformName: infoPlist.DTPlatformName,
|
||||
};
|
||||
}
|
||||
const { bundleIdentifier, dtPlatformName } = await readIpaInfoAsync(archivePath);
|
||||
return { bundleIdentifier, platformName: dtPlatformName };
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import { z } from 'zod';
|
||||
import { buildFlowNameToPathMap } from './maestroFlowDiscovery';
|
||||
import {
|
||||
MaestroFlowResult,
|
||||
hasMaestroRunnerAttemptDirectories,
|
||||
isFileAttrRun,
|
||||
parseJUnitTestCases,
|
||||
parseMaestroResults,
|
||||
parseMaestroResultsFromFileAttrs,
|
||||
parseMaestroRunnerResults,
|
||||
} from './maestroResultParser';
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
|
||||
@@ -73,8 +75,15 @@ export function createReportMaestroTestResultsFunction(ctx: CustomBuildContext):
|
||||
// map testcase names back to paths.
|
||||
const usedFileAttrs = isFileAttrRun(await parseJUnitTestCases(junitDirectory));
|
||||
|
||||
const testsDirectory = (inputs.tests_directory.value as string | undefined) ?? '';
|
||||
let flowResults: MaestroFlowResult[];
|
||||
if (usedFileAttrs) {
|
||||
if (usedFileAttrs && (await hasMaestroRunnerAttemptDirectories(testsDirectory))) {
|
||||
flowResults = await parseMaestroRunnerResults({
|
||||
junitDirectory,
|
||||
testsDirectory,
|
||||
workingDirectory: stepsCtx.workingDirectory,
|
||||
});
|
||||
} else if (usedFileAttrs) {
|
||||
flowResults = await parseMaestroResultsFromFileAttrs(junitDirectory);
|
||||
} else {
|
||||
// Legacy (Maestro < 2.6.0) — DELETE this arm once the fleet is on >= 2.6.0.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Platform } from '@expo/eas-build-job';
|
||||
import { Platform, formatBytes } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import {
|
||||
@@ -17,7 +17,6 @@ import * as tar from 'tar';
|
||||
import { promisify } from 'util';
|
||||
import z from 'zod';
|
||||
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { PUBLIC_CACHE_KEY_PREFIX_BY_PLATFORM } from '../../utils/cacheKey';
|
||||
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
|
||||
import { TurtleFetchError, turtleFetch } from '../../utils/turtleFetch';
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
BuildStepInputValueTypeName,
|
||||
BuildStepOutput,
|
||||
} from '@expo/steps';
|
||||
import path from 'path';
|
||||
|
||||
import { runFastlaneGym } from '../utils/ios/fastlane';
|
||||
import { BuildStatusText, BuildStepOutputName } from '../utils/slackMessageDynamicFields';
|
||||
@@ -39,6 +40,7 @@ export function runFastlaneFunction(): BuildFunction {
|
||||
try {
|
||||
await runFastlaneGym({
|
||||
workingDir: stepCtx.workingDirectory,
|
||||
gymfileDirectory: path.join(stepCtx.workingDirectory, 'ios'),
|
||||
env,
|
||||
logger: stepCtx.logger,
|
||||
buildLogsDirectory: stepCtx.global.buildLogsDirectory,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Platform } from '@expo/eas-build-job';
|
||||
import { Platform, formatBytes } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import {
|
||||
@@ -14,7 +14,6 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import { compressCacheAsync, uploadCacheAsync } from './saveCache';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import {
|
||||
CcacheBuildTarget,
|
||||
generateDefaultBuildCacheKeyAsync,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Platform } from '@expo/eas-build-job';
|
||||
import { Platform, formatBytes } from '@expo/eas-build-job';
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { asyncResult } from '@expo/results';
|
||||
import { BuildFunction, BuildStepInput, BuildStepInputValueTypeName } from '@expo/steps';
|
||||
@@ -12,7 +12,6 @@ import * as tar from 'tar';
|
||||
import z from 'zod';
|
||||
|
||||
import { uploadWithSignedUrl } from '../../storage/uploadWithSignedUrl';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { retryOnDNSFailure } from '../../utils/retryOnDNSFailure';
|
||||
import { getCacheVersion } from '../utils/cache';
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import { type StartupTasks } from '../utils/startupTasks';
|
||||
import {
|
||||
type DetachedProcessHandle,
|
||||
DeviceRunSessionStoppedError,
|
||||
TOOL_TUNNEL_TEARDOWN_OPTIONS,
|
||||
finishRemoteSessionAsync,
|
||||
getDeviceRunSessionIdOrThrow,
|
||||
getNgrokAuthtokenOrThrow,
|
||||
@@ -213,6 +214,7 @@ export async function runAgentDeviceRemoteSessionAsync(
|
||||
authtoken: ngrokAuthtoken,
|
||||
healthCheck: { path: '/health' },
|
||||
logger: taskLogger,
|
||||
signal: tasks.signal,
|
||||
});
|
||||
tasks.signal.throwIfAborted();
|
||||
taskLogger.info(`Tunnel is ready at ${agentDeviceTunnel.url}.`);
|
||||
@@ -351,7 +353,7 @@ export async function runAgentDeviceRemoteSessionAsync(
|
||||
? [['startup cleanup', Promise.reject(result.reason)]]
|
||||
: []
|
||||
),
|
||||
['agent-device tunnel', agentDeviceTunnel?.stopAsync()],
|
||||
['agent-device tunnel', agentDeviceTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['agent-device daemon', toolTeardown],
|
||||
[
|
||||
'session host',
|
||||
|
||||
@@ -25,6 +25,11 @@ import { retryAsync } from '../../utils/retry';
|
||||
import { resolveAndroidEmulatorLocalEgressAsync } from '../utils/androidLocalEgress';
|
||||
import { ALL_ANDROID_EMULATOR_LOG_SOURCES } from '../../utils/androidEmulatorLogSources';
|
||||
import { getAndroidEmulatorLogCapture } from '../utils/androidEmulatorLogs';
|
||||
import {
|
||||
EMULATOR_CAPTURE_REQUESTED_ENV,
|
||||
installEmulatorCaptureAsync,
|
||||
parseExperimentalEmulatorCaptureVersionInput,
|
||||
} from '../utils/emulatorCapture';
|
||||
import { parseLogSourcesInput } from '../utils/logSourcesInput';
|
||||
|
||||
const ANDROID_STARTUP_ATTEMPT_TIMEOUT_MS = [60_000, 120_000, 180_000];
|
||||
@@ -81,6 +86,12 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
defaultValue: 1,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.NUMBER,
|
||||
}),
|
||||
// Experimental: the expo-emulator-capture version that the emulator preloads.
|
||||
BuildStepInput.createProvider({
|
||||
id: 'experimental_emulator_capture_version',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
outputProviders: [
|
||||
BuildStepOutput.createProvider({
|
||||
@@ -89,10 +100,32 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger, global }, { inputs, outputs, env }) => {
|
||||
const count = Number(inputs.count.value ?? 1);
|
||||
const emulatorCaptureVersion = parseExperimentalEmulatorCaptureVersionInput(
|
||||
inputs.experimental_emulator_capture_version.value
|
||||
);
|
||||
if (emulatorCaptureVersion && count > 1) {
|
||||
throw new UserError(
|
||||
'EAS_EMULATOR_CAPTURE_INVALID_INPUT',
|
||||
'experimental_emulator_capture_version supports one emulator. Remove it, or set count to 1.'
|
||||
);
|
||||
}
|
||||
const logSources = parseLogSourcesInput(inputs.log_sources.value, {
|
||||
runtimePlatform: global.runtimePlatform,
|
||||
fallback: ALL_ANDROID_EMULATOR_LOG_SOURCES,
|
||||
});
|
||||
if (emulatorCaptureVersion) {
|
||||
// Marks the request for the session step, which rejects session types that cannot use
|
||||
// the capture. The mark does not depend on the install, so the rejection does not either.
|
||||
global.updateEnv({
|
||||
...global.env,
|
||||
[EMULATOR_CAPTURE_REQUESTED_ENV]: emulatorCaptureVersion,
|
||||
});
|
||||
}
|
||||
const emulatorCaptureLibrary = emulatorCaptureVersion
|
||||
? await installEmulatorCaptureAsync({ version: emulatorCaptureVersion, env, logger })
|
||||
: undefined;
|
||||
|
||||
const logcatDirectory = await fs.promises.mkdtemp(
|
||||
path.join(os.tmpdir(), 'eas-android-emulator-logcat-')
|
||||
);
|
||||
@@ -100,7 +133,7 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
outputs.logcat_directory.set(logcatDirectory);
|
||||
|
||||
const deviceName = `${inputs.device_name.value}` as AndroidVirtualDeviceName;
|
||||
const { serialId, emulatorPromise, shouldAdjustAnimationScale } =
|
||||
const { serialId, emulatorPromise, shouldAdjustAnimationScale, emulatorCaptureSocketPath } =
|
||||
await startAndroidEmulatorAsync({
|
||||
deviceName,
|
||||
systemImagePackage: `${inputs.system_image_package.value}`,
|
||||
@@ -113,9 +146,21 @@ export function createStartAndroidEmulatorBuildFunction(): BuildFunction {
|
||||
logCapture,
|
||||
env,
|
||||
logger,
|
||||
emulatorCaptureLibrary,
|
||||
});
|
||||
if (emulatorCaptureLibrary && emulatorCaptureSocketPath) {
|
||||
// The session step starts expo-device-hub with the job env. A Hub version without the
|
||||
// emulator capture ignores these variables.
|
||||
global.updateEnv({
|
||||
...global.env,
|
||||
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
|
||||
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: emulatorCaptureLibrary,
|
||||
});
|
||||
logger.info(
|
||||
`${serialId} preloads expo-emulator-capture@${emulatorCaptureVersion} with -gpu lavapipe, and its agent socket is ${emulatorCaptureSocketPath}. Later steps start expo-device-hub with the emulator capture on.`
|
||||
);
|
||||
}
|
||||
|
||||
const count = Number(inputs.count.value ?? 1);
|
||||
if (count > 1) {
|
||||
logger.info(`Requested ${count} emulators, shutting down ${deviceName} for cloning.`);
|
||||
await spawn('adb', ['-s', serialId, 'shell', 'reboot', '-p'], {
|
||||
@@ -222,6 +267,7 @@ export async function startAndroidEmulatorAsync({
|
||||
logCapture,
|
||||
env,
|
||||
logger,
|
||||
emulatorCaptureLibrary,
|
||||
}: {
|
||||
deviceName: AndroidVirtualDeviceName;
|
||||
systemImagePackage: string;
|
||||
@@ -233,10 +279,14 @@ export async function startAndroidEmulatorAsync({
|
||||
logCapture: AndroidEmulatorLogCapture;
|
||||
env: BuildStepEnv;
|
||||
logger: bunyan;
|
||||
/** The expo-emulator-capture agent library that the emulator preloads (experimental). */
|
||||
emulatorCaptureLibrary?: string;
|
||||
}): Promise<{
|
||||
serialId: AndroidDeviceSerialId;
|
||||
emulatorPromise: Promise<unknown>;
|
||||
shouldAdjustAnimationScale: boolean;
|
||||
/** The capture agent's socket, when the emulator preloads the agent on the expected serial. */
|
||||
emulatorCaptureSocketPath?: string;
|
||||
}> {
|
||||
if (env.EAS_NO_EMULATOR_HOST_SUPPORT_CHECK !== '1') {
|
||||
await assertAndroidEmulatorHostSupportAsync({ env });
|
||||
@@ -284,8 +334,16 @@ export async function startAndroidEmulatorAsync({
|
||||
}
|
||||
);
|
||||
|
||||
// expo-device-hub gets the job env and finds the agent sockets in `<tmpdir>/expo-emulator-capture`,
|
||||
// where Node's os.tmpdir() applies this rule to that env. On EAS, TMPDIR is not set.
|
||||
const captureSocketDirectory = path.join(
|
||||
env.TMPDIR || env.TMP || env.TEMP || '/tmp',
|
||||
'expo-emulator-capture'
|
||||
);
|
||||
let emulatorPromise = null;
|
||||
let serialId = null;
|
||||
// Set by the attempt that starts; the cast keeps the type wide after the retry callback.
|
||||
let captureLaunch = undefined as { consolePort: number; socketPath: string } | undefined;
|
||||
await retryAsync(
|
||||
async attemptCount => {
|
||||
const timeoutMs = ANDROID_STARTUP_ATTEMPT_TIMEOUT_MS[attemptCount];
|
||||
@@ -308,12 +366,37 @@ export async function startAndroidEmulatorAsync({
|
||||
});
|
||||
|
||||
logger.info(`Starting emulator device${attemptSuffix}.`);
|
||||
// expo-device-hub finds the capture agent's socket by the serial, so the console port,
|
||||
// which sets the serial, is chosen before the start, again for each attempt.
|
||||
const consolePort = emulatorCaptureLibrary
|
||||
? await AndroidEmulatorUtils.findFreeConsolePortAsync()
|
||||
: undefined;
|
||||
const launch =
|
||||
consolePort !== undefined
|
||||
? {
|
||||
consolePort,
|
||||
socketPath: path.join(captureSocketDirectory, `emulator-${consolePort}.sock`),
|
||||
}
|
||||
: undefined;
|
||||
const startResult = await AndroidEmulatorUtils.startAsync({
|
||||
deviceName,
|
||||
env,
|
||||
logcatDirectory,
|
||||
logCapture,
|
||||
...(localEgress ? { launchGate: localEgress.launchGate } : {}),
|
||||
...(emulatorCaptureLibrary && launch
|
||||
? {
|
||||
consolePort: launch.consolePort,
|
||||
// The Linux agent kept 60 fps with the lavapipe renderer.
|
||||
extraArgs: ['-gpu', 'lavapipe'],
|
||||
extraEnv: {
|
||||
// A library that the job already preloads stays preloaded, after the agent.
|
||||
LD_PRELOAD: [emulatorCaptureLibrary, env.LD_PRELOAD].filter(Boolean).join(':'),
|
||||
// The agent creates the directory.
|
||||
EXPO_EMULATOR_CAPTURE_SOCKET: launch.socketPath,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
attemptSerialId = startResult.serialId;
|
||||
await AndroidEmulatorUtils.waitForReadyAsync({
|
||||
@@ -335,6 +418,7 @@ export async function startAndroidEmulatorAsync({
|
||||
|
||||
serialId = attemptSerialId;
|
||||
emulatorPromise = startResult.emulatorPromise;
|
||||
captureLaunch = launch;
|
||||
} catch (err) {
|
||||
logger.warn({ err }, `${deviceName} failed to start on attempt ${attempt}/${maxAttempts}.`);
|
||||
try {
|
||||
@@ -368,7 +452,19 @@ export async function startAndroidEmulatorAsync({
|
||||
if (!serialId || !emulatorPromise) {
|
||||
throw new Error(`Failed to start emulator ${deviceName}.`);
|
||||
}
|
||||
return { serialId, emulatorPromise, shouldAdjustAnimationScale };
|
||||
// The Hub looks for the socket by serial. $ANDROID_EMULATOR_EXTRA_ARGS can override -port.
|
||||
if (captureLaunch && serialId !== `emulator-${captureLaunch.consolePort}`) {
|
||||
logger.warn(
|
||||
`${serialId} does not use console port ${captureLaunch.consolePort}, so expo-device-hub cannot find its capture agent socket ${captureLaunch.socketPath}. The session streams without the emulator capture. Remove -port from $ANDROID_EMULATOR_EXTRA_ARGS.`
|
||||
);
|
||||
captureLaunch = undefined;
|
||||
}
|
||||
return {
|
||||
serialId,
|
||||
emulatorPromise,
|
||||
shouldAdjustAnimationScale,
|
||||
emulatorCaptureSocketPath: captureLaunch?.socketPath,
|
||||
};
|
||||
}
|
||||
|
||||
async function assertAndroidEmulatorHostSupportAsync({
|
||||
|
||||
@@ -52,6 +52,7 @@ import { preparePreinstalledWdaAsync } from '../utils/preinstalledWda';
|
||||
import { watchDeviceRunSessionStartup } from '../utils/deviceRunSessionStartup';
|
||||
import {
|
||||
DeviceRunSessionStoppedError,
|
||||
TOOL_TUNNEL_TEARDOWN_OPTIONS,
|
||||
createCorsOriginsInputProvider,
|
||||
createFrameAncestorsInputProvider,
|
||||
createIosSessionStartupInputProviders,
|
||||
@@ -328,6 +329,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
|
||||
authtoken: ngrokAuthtoken,
|
||||
healthCheck: { path: '/status' },
|
||||
logger,
|
||||
signal: startupSignal,
|
||||
});
|
||||
|
||||
// The preview host uses the same device selected for Appium.
|
||||
@@ -415,7 +417,7 @@ export function createStartAppiumRemoteSessionBuildFunction(
|
||||
logger,
|
||||
sessionFailed,
|
||||
teardown: [
|
||||
['Appium tunnel', appiumTunnel?.stopAsync()],
|
||||
['Appium tunnel', appiumTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['Appium server', appiumTeardown],
|
||||
[
|
||||
'session host',
|
||||
|
||||
@@ -44,6 +44,7 @@ import { ARGENT_EVENT_LOG_FILENAME, startArgentEventCollectionAsync } from '../u
|
||||
import { watchDeviceRunSessionStartup } from '../utils/deviceRunSessionStartup';
|
||||
import {
|
||||
DeviceRunSessionStoppedError,
|
||||
TOOL_TUNNEL_TEARDOWN_OPTIONS,
|
||||
createCorsOriginsInputProvider,
|
||||
createFrameAncestorsInputProvider,
|
||||
createIosSessionStartupInputProviders,
|
||||
@@ -386,6 +387,7 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
rewriteHostHeader: true,
|
||||
healthCheck: { path: '/tools', statuses: [200, 401] },
|
||||
logger,
|
||||
signal: startupSignal,
|
||||
});
|
||||
const publicToolsUrl = toolsTunnel.url;
|
||||
logger.info(`Tunnel is ready at ${publicToolsUrl}.`);
|
||||
@@ -481,7 +483,7 @@ export function createStartArgentRemoteSessionBuildFunction(
|
||||
logger,
|
||||
sessionFailed,
|
||||
teardown: [
|
||||
['Argent tunnel', toolsTunnel?.stopAsync()],
|
||||
['Argent tunnel', toolsTunnel?.stopAsync(), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['Argent tool-server', toolTeardown],
|
||||
[
|
||||
'session host',
|
||||
|
||||
@@ -170,6 +170,7 @@ export function createStartLocalEgressBuildFunction(): BuildFunction {
|
||||
baseDomain: ngrokTunnelDomain,
|
||||
authtoken: ngrokAuthtoken,
|
||||
logger,
|
||||
signal: startupSignal,
|
||||
}),
|
||||
startupSignal,
|
||||
async listener => await listener?.stopAsync(),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { BuildFunction, BuildRuntimePlatform } from '@expo/steps';
|
||||
|
||||
import { Sentry } from '../../sentry';
|
||||
import { ServeSimCrashesRecorder } from '../utils/serveSimCrashesRecorder';
|
||||
|
||||
export function createStartServeSimCrashesBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'start_serve_sim_crashes',
|
||||
name: 'Start serve-sim simulator crashes',
|
||||
__metricsId: 'eas/start_serve_sim_crashes',
|
||||
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
|
||||
fn: async ({ logger }) => {
|
||||
try {
|
||||
await ServeSimCrashesRecorder.startAsync({ logger });
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not start serve-sim simulator crashes', error);
|
||||
logger.warn(
|
||||
{ err: error },
|
||||
'Could not start simulator crash collection; the session will continue.'
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildRuntimePlatform,
|
||||
BuildStepInput,
|
||||
BuildStepInputValueTypeName,
|
||||
} from '@expo/steps';
|
||||
|
||||
import { Sentry } from '../../sentry';
|
||||
import { ServeSimNetworkCaptureRecorder } from '../utils/serveSimNetworkCaptureRecorder';
|
||||
|
||||
export function createStartServeSimNetworkCaptureBuildFunction(): BuildFunction {
|
||||
return new BuildFunction({
|
||||
namespace: 'eas',
|
||||
id: 'start_serve_sim_network_capture',
|
||||
name: 'Start serve-sim network capture',
|
||||
__metricsId: 'eas/start_serve_sim_network_capture',
|
||||
supportedRuntimePlatforms: [BuildRuntimePlatform.DARWIN],
|
||||
inputProviders: [
|
||||
BuildStepInput.createProvider({
|
||||
id: 'package_version',
|
||||
required: false,
|
||||
allowedValueTypeName: BuildStepInputValueTypeName.STRING,
|
||||
}),
|
||||
],
|
||||
fn: async ({ logger }, { inputs, env }) => {
|
||||
try {
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
packageVersion: inputs.package_version.value as string | undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not start the serve-sim network capture recorder', error);
|
||||
logger.warn({ err: error }, 'Could not start the serve-sim network capture recorder.');
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import {
|
||||
BuildFunction,
|
||||
BuildRuntimePlatform,
|
||||
@@ -87,16 +86,6 @@ export function createStartWebPreviewRemoteSessionBuildFunction(
|
||||
const maxDurationSeconds = inputs.max_duration_seconds?.value as number | undefined;
|
||||
const packageVersion = inputs.package_version?.value as string | undefined;
|
||||
const { runtimePlatform } = global;
|
||||
if (
|
||||
maxIdleTimeMinutes !== undefined &&
|
||||
maxIdleTimeMinutes > 0 &&
|
||||
runtimePlatform !== BuildRuntimePlatform.DARWIN
|
||||
) {
|
||||
throw new UserError(
|
||||
'UNSUPPORTED_WEB_PREVIEW_IDLE_TIMEOUT',
|
||||
'Web preview idle timeouts require iOS preview activity reporting. Omit max_idle_time_minutes for Android sessions.'
|
||||
);
|
||||
}
|
||||
const startupStop = new AbortController();
|
||||
const watchSignal = signal
|
||||
? AbortSignal.any([signal, startupStop.signal])
|
||||
@@ -152,6 +141,7 @@ export function createStartWebPreviewRemoteSessionBuildFunction(
|
||||
signal: startupSignal,
|
||||
onStartupError: error => startupAbortController.abort(error),
|
||||
packageVersion: resolvedPackageVersion,
|
||||
emulatorCapture: true,
|
||||
disableShare: inputs.public_preview?.value === false,
|
||||
privatePreviewUrl: inputs.private_preview_url?.value as string | undefined,
|
||||
frameAncestors: parseFrameAncestorsInput(inputs.frame_ancestors?.value),
|
||||
|
||||
@@ -217,8 +217,12 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads a screenshot display rotation as artifact metadata', async () => {
|
||||
const data = Buffer.from('png-data');
|
||||
it('uploads the screenshot size, source and display rotation as artifact metadata', async () => {
|
||||
const data = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aF9sAAAAASUVORK5CYII=',
|
||||
'base64'
|
||||
);
|
||||
const logger = createLoggerMock();
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
|
||||
jest.mocked(fetch).mockResolvedValueOnce(new Response(Readable.from([data])));
|
||||
@@ -232,7 +236,7 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
logger: createLoggerMock(),
|
||||
logger,
|
||||
artifact: {
|
||||
id: 'artifact-id',
|
||||
artifactType: 'screenshot',
|
||||
@@ -245,12 +249,48 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
ctx,
|
||||
expect.objectContaining({
|
||||
kind: 'screenshot',
|
||||
metadata: { displayRotation: 'landscape-right' },
|
||||
metadata: {
|
||||
source: 'agent-device',
|
||||
displayRotation: 'landscape-right',
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads a screenshot without its size and warns when its header cannot be read', async () => {
|
||||
const data = Buffer.from('not-an-image');
|
||||
const logger = createLoggerMock();
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
|
||||
jest.mocked(fetch).mockResolvedValueOnce(new Response(Readable.from([data])));
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockImplementationOnce(async (_ctx, { openStream }) => {
|
||||
await readStreamAsync(openStream());
|
||||
});
|
||||
|
||||
await uploadAgentDeviceArtifactAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
logger,
|
||||
artifact: { id: 'artifact-id', artifactType: 'screenshot', filename: 'shot.png' },
|
||||
});
|
||||
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync)).toHaveBeenCalledWith(
|
||||
ctx,
|
||||
expect.objectContaining({ kind: 'screenshot', metadata: { source: 'agent-device' } })
|
||||
);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ file: expect.stringMatching(/shot\.png$/) }),
|
||||
expect.stringContaining('without its width and height')
|
||||
);
|
||||
});
|
||||
|
||||
it('uploads no metadata when the artifact has no display rotation', async () => {
|
||||
it('uploads no metadata for a non-screenshot artifact without a display rotation', async () => {
|
||||
const data = Buffer.from('artifact-data');
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
|
||||
@@ -266,7 +306,7 @@ describe(uploadAgentDeviceArtifactAsync, () => {
|
||||
daemonUrl: 'http://127.0.0.1:1234',
|
||||
daemonToken: 'daemon-token',
|
||||
logger: createLoggerMock(),
|
||||
artifact: { id: 'artifact-id', artifactType: 'screenshot', filename: 'shot.png' },
|
||||
artifact: { id: 'artifact-id', artifactType: 'screen-recording', filename: 'session.mp4' },
|
||||
});
|
||||
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync).mock.calls[0][1]).not.toHaveProperty(
|
||||
|
||||
@@ -155,17 +155,18 @@ describe(uploadArgentArtifactAsync, () => {
|
||||
});
|
||||
});
|
||||
|
||||
async function uploadAsync(artifact: {
|
||||
id: string;
|
||||
kind?: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
isDirectory?: boolean;
|
||||
}): Promise<CustomBuildContext> {
|
||||
async function uploadAsync(
|
||||
artifact: {
|
||||
id: string;
|
||||
kind?: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
isDirectory?: boolean;
|
||||
},
|
||||
data = Buffer.from('artifact-data')
|
||||
): Promise<CustomBuildContext> {
|
||||
const ctx = {} as unknown as CustomBuildContext;
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response(Readable.from([Buffer.from('artifact-data')])));
|
||||
jest.mocked(fetch).mockResolvedValueOnce(new Response(Readable.from([data])));
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockImplementationOnce(async (_ctx, { openStream }) => {
|
||||
@@ -200,6 +201,45 @@ describe(uploadArgentArtifactAsync, () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ kind: undefined, expectedKind: 'screenshot' },
|
||||
{ kind: 'screenshot-diff', expectedKind: 'screenshot-diff' },
|
||||
])('sends the size of a $expectedKind read from its header', async ({ kind, expectedKind }) => {
|
||||
const png = Buffer.alloc(33);
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png);
|
||||
png.writeUInt32BE(13, 8);
|
||||
png.write('IHDR', 12, 'latin1');
|
||||
png.writeUInt32BE(1179, 16);
|
||||
png.writeUInt32BE(2556, 20);
|
||||
const ctx = await uploadAsync(
|
||||
{ id: 'artifact-id', kind, filename: 'screen.png', mimeType: 'image/png' },
|
||||
png
|
||||
);
|
||||
|
||||
expect(jest.mocked(uploadDeviceRunSessionArtifactAsync)).toHaveBeenCalledWith(
|
||||
ctx,
|
||||
expect.objectContaining({
|
||||
kind: expectedKind,
|
||||
metadata: { source: 'argent', width: 1179, height: 2556 },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no screenshot metadata for other artifacts', async () => {
|
||||
await uploadAsync({ id: 'artifact-id', filename: 'session.mp4', mimeType: 'video/mp4' });
|
||||
await uploadAsync({
|
||||
id: 'artifact-id',
|
||||
kind: 'screenshot',
|
||||
filename: 'screenshots',
|
||||
mimeType: 'image/png',
|
||||
isDirectory: true,
|
||||
});
|
||||
|
||||
for (const [, input] of jest.mocked(uploadDeviceRunSessionArtifactAsync).mock.calls) {
|
||||
expect(input).not.toHaveProperty('metadata');
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the semantic kind reported by Argent', async () => {
|
||||
const ctx = await uploadAsync({
|
||||
id: 'artifact-id',
|
||||
|
||||
@@ -45,6 +45,17 @@ function createCtx(): CustomBuildContext {
|
||||
} as unknown as CustomBuildContext;
|
||||
}
|
||||
|
||||
function webpPreview(width: number, height: number): Buffer {
|
||||
const image = Buffer.alloc(30);
|
||||
image.write('RIFF', 0, 'latin1');
|
||||
image.writeUInt32LE(22, 4);
|
||||
image.write('WEBPVP8X', 8, 'latin1');
|
||||
image.writeUInt32LE(10, 16);
|
||||
image.writeUIntLE(width - 1, 24, 3);
|
||||
image.writeUIntLE(height - 1, 27, 3);
|
||||
return image;
|
||||
}
|
||||
|
||||
function uploadSessionResponse(): InstanceType<typeof Response> {
|
||||
return new Response(JSON.stringify({ data: { uploadSession } }), {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
@@ -226,6 +237,89 @@ describe('session preview upload session from the worker API', () => {
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sends no metadata when the preview size cannot be read', async () => {
|
||||
start();
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(turtleFetch).toHaveBeenCalledWith(
|
||||
PREVIEW_UPLOAD_SESSION_URL,
|
||||
'POST',
|
||||
expect.not.objectContaining({ json: expect.anything() })
|
||||
);
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sends the preview size and refreshes it only when the size changes', async () => {
|
||||
const captureAsync = jest
|
||||
.fn<Promise<Buffer>, [AbortSignal]>()
|
||||
.mockResolvedValueOnce(webpPreview(148, 320))
|
||||
.mockResolvedValueOnce(webpPreview(148, 320))
|
||||
.mockResolvedValue(webpPreview(320, 148));
|
||||
preview = startDeviceRunSessionPreview({
|
||||
ctx: createCtx(),
|
||||
deviceRunSessionId: 'session-id',
|
||||
captureAsync,
|
||||
logger,
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(captureAsync).toHaveBeenCalledTimes(3);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
expect(jest.mocked(turtleFetch).mock.calls.map(([, , options]) => options.json)).toEqual([
|
||||
{ metadata: { source: 'preview', width: 148, height: 320 } },
|
||||
{ metadata: { source: 'preview', width: 320, height: 148 } },
|
||||
]);
|
||||
expect(jest.mocked(turtleFetch).mock.invocationCallOrder[1]).toBeGreaterThan(
|
||||
jest.mocked(fetch).mock.invocationCallOrder[2]
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps the stored size when the upload of a resized preview fails', async () => {
|
||||
const captureAsync = jest
|
||||
.fn<Promise<Buffer>, [AbortSignal]>()
|
||||
.mockResolvedValueOnce(webpPreview(148, 320))
|
||||
.mockResolvedValue(webpPreview(320, 148));
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response('', { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response('', { status: 503 }));
|
||||
preview = startDeviceRunSessionPreview({
|
||||
ctx: createCtx(),
|
||||
deviceRunSessionId: 'session-id',
|
||||
captureAsync,
|
||||
logger,
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
await preview.stopAsync();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(jest.mocked(turtleFetch).mock.calls.map(([, , options]) => options.json)).toEqual([
|
||||
{ metadata: { source: 'preview', width: 148, height: 320 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('sends the size again after a failed size refresh', async () => {
|
||||
const captureAsync = jest
|
||||
.fn<Promise<Buffer>, [AbortSignal]>()
|
||||
.mockResolvedValueOnce(webpPreview(148, 320))
|
||||
.mockResolvedValueOnce(webpPreview(320, 148))
|
||||
.mockResolvedValue(webpPreview(148, 320));
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockImplementationOnce(async () => uploadSessionResponse())
|
||||
.mockRejectedValueOnce(new Error('response lost'));
|
||||
preview = startDeviceRunSessionPreview({
|
||||
ctx: createCtx(),
|
||||
deviceRunSessionId: 'session-id',
|
||||
captureAsync,
|
||||
logger,
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
expect(jest.mocked(turtleFetch).mock.calls.map(([, , options]) => options.json)).toEqual([
|
||||
{ metadata: { source: 'preview', width: 148, height: 320 } },
|
||||
{ metadata: { source: 'preview', width: 320, height: 148 } },
|
||||
{ metadata: { source: 'preview', width: 148, height: 320 } },
|
||||
]);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('logs a failure and uploads nothing when the job has no device run session token', async () => {
|
||||
start({
|
||||
env: {},
|
||||
@@ -315,10 +409,8 @@ describe(captureDeviceRunSessionPreviewAsync, () => {
|
||||
}) as ReturnType<typeof spawn>;
|
||||
}
|
||||
return (async () => {
|
||||
if (command === 'xcrun') {
|
||||
expect(args.slice(0, 4)).toEqual(['simctl', 'io', 'selected-device', 'screenshot']);
|
||||
await writeFile(args[4], Uint8Array.from(png));
|
||||
} else if (command === 'sips') {
|
||||
expect(command).not.toBe('xcrun');
|
||||
if (command === 'sips') {
|
||||
expect(args.slice(0, 2)).toEqual(['-Z', '320']);
|
||||
expect(await readFile(args[2])).toEqual(png);
|
||||
await writeFile(args[args.indexOf('--out') + 1], Uint8Array.from(resized));
|
||||
@@ -340,6 +432,10 @@ describe(captureDeviceRunSessionPreviewAsync, () => {
|
||||
await captureDeviceRunSessionPreviewAsync({
|
||||
runtimePlatform,
|
||||
device,
|
||||
captureIosScreenshotAsync: async (file, signal) => {
|
||||
signal.throwIfAborted();
|
||||
await writeFile(file, Uint8Array.from(png));
|
||||
},
|
||||
env: {},
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
@@ -372,6 +468,9 @@ describe(captureDeviceRunSessionPreviewAsync, () => {
|
||||
captureDeviceRunSessionPreviewAsync({
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
device: 'device',
|
||||
captureIosScreenshotAsync: async () => {
|
||||
throw new Error('capture failed');
|
||||
},
|
||||
env: {},
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
createScreenshotMetadataAsync,
|
||||
readImageSize,
|
||||
} from '../deviceRunSessionScreenshotMetadata';
|
||||
|
||||
function png(width: number, height: number): Buffer {
|
||||
const header = Buffer.alloc(33);
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);
|
||||
header.writeUInt32BE(13, 8);
|
||||
header.write('IHDR', 12, 'latin1');
|
||||
header.writeUInt32BE(width, 16);
|
||||
header.writeUInt32BE(height, 20);
|
||||
return header;
|
||||
}
|
||||
|
||||
function webp(chunk: string, data: Buffer): Buffer {
|
||||
const header = Buffer.alloc(20);
|
||||
header.write('RIFF', 0, 'latin1');
|
||||
header.writeUInt32LE(12 + data.length, 4);
|
||||
header.write('WEBP', 8, 'latin1');
|
||||
header.write(chunk, 12, 'latin1');
|
||||
header.writeUInt32LE(data.length, 16);
|
||||
return Buffer.concat([header, data]);
|
||||
}
|
||||
|
||||
function vp8(width: number, height: number): Buffer {
|
||||
const data = Buffer.alloc(10);
|
||||
Buffer.from([0x9d, 0x01, 0x2a]).copy(data, 3);
|
||||
data.writeUInt16LE(width, 6);
|
||||
data.writeUInt16LE(height, 8);
|
||||
return webp('VP8 ', data);
|
||||
}
|
||||
|
||||
function vp8l(width: number, height: number): Buffer {
|
||||
const data = Buffer.alloc(10);
|
||||
data[0] = 0x2f;
|
||||
data.writeUInt32LE((width - 1) | ((height - 1) << 14), 1);
|
||||
return webp('VP8L', data);
|
||||
}
|
||||
|
||||
function vp8x(width: number, height: number): Buffer {
|
||||
const data = Buffer.alloc(10);
|
||||
data.writeUIntLE(width - 1, 4, 3);
|
||||
data.writeUIntLE(height - 1, 7, 3);
|
||||
return webp('VP8X', data);
|
||||
}
|
||||
|
||||
function jpegSegment(marker: number, payload: Buffer): Buffer {
|
||||
const header = Buffer.from([0xff, marker, 0, 0]);
|
||||
header.writeUInt16BE(payload.length + 2, 2);
|
||||
return Buffer.concat([header, payload]);
|
||||
}
|
||||
|
||||
function jpegFrame(marker: number, width: number, height: number, components = 3): Buffer {
|
||||
const payload = Buffer.alloc(6 + 3 * components);
|
||||
payload[0] = 8;
|
||||
payload.writeUInt16BE(height, 1);
|
||||
payload.writeUInt16BE(width, 3);
|
||||
payload[5] = components;
|
||||
return jpegSegment(marker, payload);
|
||||
}
|
||||
|
||||
const JPEG_START = Buffer.from([0xff, 0xd8]);
|
||||
|
||||
describe(readImageSize, () => {
|
||||
it('reads the PNG IHDR size', () => {
|
||||
expect(readImageSize(png(1179, 2556))).toEqual({ width: 1179, height: 2556 });
|
||||
});
|
||||
|
||||
it('reads the lossy WebP frame size without its scale bits', () => {
|
||||
expect(readImageSize(vp8(0x4000 | 1179, 0xc000 | 2556))).toEqual({
|
||||
width: 1179,
|
||||
height: 2556,
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the lossless WebP size', () => {
|
||||
expect(readImageSize(vp8l(1179, 2556))).toEqual({ width: 1179, height: 2556 });
|
||||
});
|
||||
|
||||
it('reads the size of a minimal lossless WebP shorter than other WebP headers', () => {
|
||||
const minimalLossless = Buffer.from(
|
||||
'5249464614000000574542505650384c080000002f0fc00310888808',
|
||||
'hex'
|
||||
);
|
||||
expect(readImageSize(minimalLossless)).toEqual({ width: 16, height: 16 });
|
||||
});
|
||||
|
||||
it('reads the extended WebP canvas size', () => {
|
||||
expect(readImageSize(vp8x(1179, 2556))).toEqual({ width: 1179, height: 2556 });
|
||||
});
|
||||
|
||||
it('reads the JPEG frame size after other segments', () => {
|
||||
const jpeg = Buffer.concat([
|
||||
JPEG_START,
|
||||
jpegSegment(0xe1, Buffer.alloc(300)),
|
||||
Buffer.from([0xff]),
|
||||
jpegSegment(0xc4, Buffer.alloc(20)),
|
||||
jpegFrame(0xc2, 1179, 2556),
|
||||
]);
|
||||
expect(readImageSize(jpeg)).toEqual({ width: 1179, height: 2556 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an empty buffer', Buffer.alloc(0)],
|
||||
['a truncated PNG', png(1179, 2556).subarray(0, 20)],
|
||||
['a PNG without IHDR first', Buffer.concat([png(1, 1).subarray(0, 12), Buffer.alloc(21)])],
|
||||
['a zero-width PNG', png(0, 2556)],
|
||||
['a truncated WebP', vp8x(1179, 2556).subarray(0, 26)],
|
||||
['a WebP with an unknown chunk', webp('ALPH', Buffer.alloc(10))],
|
||||
['a lossy WebP without a start code', webp('VP8 ', Buffer.alloc(10))],
|
||||
[
|
||||
'a JPEG truncated in its frame header',
|
||||
Buffer.concat([JPEG_START, jpegFrame(0xc0, 1179, 2556)]).subarray(0, 8),
|
||||
],
|
||||
[
|
||||
'a JPEG truncated before its frame',
|
||||
Buffer.concat([JPEG_START, jpegSegment(0xe1, Buffer.alloc(300))]),
|
||||
],
|
||||
[
|
||||
'a JPEG with scan data before a frame',
|
||||
Buffer.concat([JPEG_START, jpegSegment(0xda, Buffer.alloc(10)), jpegFrame(0xc0, 1, 1)]),
|
||||
],
|
||||
[
|
||||
'a JPEG frame without components',
|
||||
Buffer.concat([JPEG_START, jpegFrame(0xc0, 1179, 2556, 0)]),
|
||||
],
|
||||
['a JPEG frame shorter than its header', Buffer.from('ffd8ffc0000208049b09fc', 'hex')],
|
||||
['a JPEG frame longer than the read bytes', Buffer.from('ffd8ffc0ffff08049b09fc', 'hex')],
|
||||
[
|
||||
'a JPEG frame whose length does not match its components',
|
||||
Buffer.concat([
|
||||
JPEG_START,
|
||||
jpegSegment(
|
||||
0xc0,
|
||||
Buffer.concat([Buffer.from([8, 0x09, 0xfc, 0x04, 0x9b, 3]), Buffer.alloc(6)])
|
||||
),
|
||||
]),
|
||||
],
|
||||
['a GIF', Buffer.from('GIF89a\x01\x00\x01\x00\x00\x00\x00', 'latin1')],
|
||||
['a log file', Buffer.from('2026-11-10T12:00:00Z app started\n'.repeat(4))],
|
||||
])('returns undefined for %s', (_description, header) => {
|
||||
expect(readImageSize(header)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe(createScreenshotMetadataAsync, () => {
|
||||
let directory: string;
|
||||
let logger: bunyan;
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(os.tmpdir(), 'screenshot-metadata-test-'));
|
||||
logger = { warn: jest.fn() } as unknown as bunyan;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('adds the image size to the screenshot metadata', async () => {
|
||||
const file = path.join(directory, 'shot.png');
|
||||
await writeFile(file, Buffer.concat([png(1179, 2556), Buffer.alloc(128 * 1024)]));
|
||||
await expect(
|
||||
createScreenshotMetadataAsync(file, {
|
||||
source: 'agent-device',
|
||||
displayRotation: 'landscape-left',
|
||||
logger,
|
||||
})
|
||||
).resolves.toEqual({
|
||||
source: 'agent-device',
|
||||
displayRotation: 'landscape-left',
|
||||
width: 1179,
|
||||
height: 2556,
|
||||
});
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('warns and leaves out the size when the header is not a supported image', async () => {
|
||||
const file = path.join(directory, 'shot.png');
|
||||
await writeFile(file, 'not-an-image');
|
||||
await expect(
|
||||
createScreenshotMetadataAsync(file, { source: 'manual', logger })
|
||||
).resolves.toEqual({ source: 'manual' });
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ file },
|
||||
'Uploading the screenshot without its width and height because it does not start with a complete PNG, WebP or JPEG header.'
|
||||
);
|
||||
});
|
||||
|
||||
it('warns and leaves out the size when the file cannot be read', async () => {
|
||||
const file = path.join(directory, 'missing.png');
|
||||
await expect(
|
||||
createScreenshotMetadataAsync(file, { source: 'manual', logger })
|
||||
).resolves.toEqual({ source: 'manual' });
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ code: 'ENOENT' }), file },
|
||||
'Uploading the screenshot without its width and height because its header could not be read.'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -8,12 +8,14 @@ import path from 'node:path';
|
||||
import type { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from '../deviceRunSessionScreenshotMetadata';
|
||||
import {
|
||||
startDeviceRunSessionScreenshotsAsync,
|
||||
uploadDeviceRunSessionScreenshotsAsync,
|
||||
} from '../deviceRunSessionScreenshots';
|
||||
|
||||
jest.mock('../deviceRunSessionArtifacts');
|
||||
jest.mock('../deviceRunSessionScreenshotMetadata');
|
||||
jest.mock('../../../sentry');
|
||||
const ctx = {} as CustomBuildContext;
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
@@ -27,6 +29,9 @@ beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(os.tmpdir(), 'screenshots-test-'));
|
||||
uploaded = [];
|
||||
failedUploads = new Map();
|
||||
jest
|
||||
.mocked(createScreenshotMetadataAsync)
|
||||
.mockResolvedValue({ source: 'manual', width: 1179, height: 2556 });
|
||||
jest
|
||||
.mocked(uploadDeviceRunSessionArtifactAsync)
|
||||
.mockImplementation(async (_ctx, { openStream }) => {
|
||||
@@ -68,9 +73,13 @@ it('uploads completed captures with their bytes and stable IDs, ignoring partial
|
||||
filename: 'screenshot-2026-09-24T08-45-59-123Z.png',
|
||||
kind: 'screenshot',
|
||||
size: 11,
|
||||
metadata: { __eas_type: 'screenshot' },
|
||||
metadata: { __eas_type: 'screenshot', source: 'manual', width: 1179, height: 2556 },
|
||||
})
|
||||
);
|
||||
expect(createScreenshotMetadataAsync).toHaveBeenCalledWith(path.join(directory, filename), {
|
||||
source: 'manual',
|
||||
logger,
|
||||
});
|
||||
expect(await readdir(directory)).not.toContain(filename);
|
||||
expect((await lstat(path.join(directory, link))).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
@@ -152,6 +152,9 @@ it('publishes a manual preview PNG through the worker API and HTTP upload path',
|
||||
platform: 'ios',
|
||||
buildId: 'installed-build',
|
||||
gitCommitHash: installedCommit,
|
||||
source: 'manual',
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
});
|
||||
await expect(stat(path.join(directory, filename))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
|
||||
@@ -176,6 +176,18 @@ describe(DeviceRunSessionWorkerApi, () => {
|
||||
data: { uploadSession: { url: 'https://uploads.test/preview', headers: {} } },
|
||||
expected: { url: 'https://uploads.test/preview', headers: {} },
|
||||
},
|
||||
{
|
||||
name: 'createPreviewUploadSessionAsync with metadata',
|
||||
call: (api: DeviceRunSessionWorkerApi) =>
|
||||
api.createPreviewUploadSessionAsync({
|
||||
metadata: { source: 'preview', width: 148, height: 320 },
|
||||
}),
|
||||
method: 'POST',
|
||||
route: 'preview-upload-session',
|
||||
json: { metadata: { source: 'preview', width: 148, height: 320 } },
|
||||
data: { uploadSession: { url: 'https://uploads.test/preview', headers: {} } },
|
||||
expected: { url: 'https://uploads.test/preview', headers: {} },
|
||||
},
|
||||
{
|
||||
name: 'fetchTurnIceServersAsync',
|
||||
call: (api: DeviceRunSessionWorkerApi) => api.fetchTurnIceServersAsync(),
|
||||
|
||||
@@ -40,11 +40,18 @@ import {
|
||||
spawnDetached,
|
||||
startNgrokTunnelAsync,
|
||||
} from '../remoteDeviceRunSession';
|
||||
import { runServeSimActionAsync, stageServeSimAppAsync } from '../serveSimActions';
|
||||
import { startServeSimActivityPolling } from '../serveSimActivity';
|
||||
import {
|
||||
runServeSimActionAsync,
|
||||
runServeSimActionWithResultAsync,
|
||||
stageServeSimAppAsync,
|
||||
} from '../serveSimActions';
|
||||
import { startPreviewActivityPolling } from '../previewActivity';
|
||||
import { readServeSimServersAsync } from '../serveSimMetricsRecorder';
|
||||
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
|
||||
import * as previewCapture from '../serveSimPreviewCapture';
|
||||
|
||||
jest.mock('@ngrok/ngrok');
|
||||
jest.mock('../serveSimCrashesRecorder');
|
||||
jest.mock('@expo/turtle-spawn');
|
||||
jest.mock('../../../utils/IosSimulatorUtils', () => ({
|
||||
IosSimulatorUtils: { disableApsdAsync: jest.fn(), waitForReadyAsync: jest.fn() },
|
||||
@@ -54,7 +61,7 @@ jest.mock('../serveSimActions');
|
||||
jest.mock('../iosAppArtifact', () => ({
|
||||
readIosApplicationIdentifierAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../serveSimActivity');
|
||||
jest.mock('../previewActivity');
|
||||
jest.mock('../localEgress', () => ({
|
||||
...jest.requireActual('../localEgress'),
|
||||
readLocalEgressHandoffAsync: jest.fn().mockResolvedValue(null),
|
||||
@@ -147,6 +154,7 @@ const stopSessionPreview = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockReset().mockResolvedValue(undefined);
|
||||
jest
|
||||
.mocked(startNgrokTunnelAsync)
|
||||
.mockReset()
|
||||
@@ -165,6 +173,12 @@ beforeEach(() => {
|
||||
.mockImplementation(async ({ artifactPath }) => installedBundleIds[artifactPath]);
|
||||
jest.mocked(verifyLocalEgressGuardAsync).mockReset().mockResolvedValue(undefined);
|
||||
jest.mocked(readLocalEgressHandoffAsync).mockReset().mockResolvedValue(null);
|
||||
jest
|
||||
.mocked(runServeSimActionWithResultAsync)
|
||||
.mockReset()
|
||||
.mockResolvedValue(
|
||||
JSON.stringify({ 'screenshot.capture': { properties: { automation: { type: 'boolean' } } } })
|
||||
);
|
||||
stopSessionPreview.mockResolvedValue(undefined);
|
||||
jest.mocked(startDeviceRunSessionPreview).mockReturnValue({ stopAsync: stopSessionPreview });
|
||||
jest.mocked(ensureFfmpegInstalledOnceAsync).mockResolvedValue(undefined);
|
||||
@@ -633,7 +647,7 @@ it('starts the readiness budget after refusals that exceed the normal startup de
|
||||
it('reports preview activity from serve-sim on iOS and stops polling when finished', async () => {
|
||||
const observedAt = new Date('2026-10-19T12:00:00Z');
|
||||
const stopActivity = jest.fn().mockResolvedValue(undefined);
|
||||
jest.mocked(startServeSimActivityPolling).mockReturnValue({
|
||||
jest.mocked(startPreviewActivityPolling).mockReturnValue({
|
||||
getLastActivityObservedAt: () => observedAt,
|
||||
stopAsync: stopActivity,
|
||||
});
|
||||
@@ -650,7 +664,8 @@ it('reports preview activity from serve-sim on iOS and stops polling when finish
|
||||
]
|
||||
);
|
||||
|
||||
expect(startServeSimActivityPolling).toHaveBeenCalledWith({
|
||||
expect(startPreviewActivityPolling).toHaveBeenCalledWith({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token: 'preview-token',
|
||||
logger: expect.anything(),
|
||||
@@ -677,15 +692,33 @@ it('does not start polling preview activity when startup is cancelled', async ()
|
||||
signal: controller.signal,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
expect(startServeSimActivityPolling).not.toHaveBeenCalled();
|
||||
expect(startPreviewActivityPolling).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports no preview activity on Android, where expo-device-hub keeps no event log', async () => {
|
||||
it('reports preview activity from expo-device-hub on Android and stops polling when finished', async () => {
|
||||
const observedAt = new Date('2026-11-13T12:00:00Z');
|
||||
const stopActivity = jest.fn().mockResolvedValue(undefined);
|
||||
jest.mocked(startPreviewActivityPolling).mockReturnValue({
|
||||
getLastActivityObservedAt: () => observedAt,
|
||||
stopAsync: stopActivity,
|
||||
});
|
||||
const host = await startHostAsync();
|
||||
const port = Number(
|
||||
jest.mocked(spawnDetached).mock.calls[0][0].args[
|
||||
jest.mocked(spawnDetached).mock.calls[0][0].args.indexOf('--port') + 1
|
||||
]
|
||||
);
|
||||
|
||||
expect(startPreviewActivityPolling).toHaveBeenCalledWith({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token: expect.any(String),
|
||||
logger: expect.anything(),
|
||||
});
|
||||
expect(host.getLastPreviewActivityAt()).toBe(observedAt);
|
||||
|
||||
expect(startServeSimActivityPolling).not.toHaveBeenCalled();
|
||||
expect(host.getLastPreviewActivityAt()).toBeUndefined();
|
||||
await host.finishAsync();
|
||||
expect(stopActivity).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stops a host that became ready on a different Simulator', async () => {
|
||||
@@ -845,6 +878,73 @@ it('drains an in-flight tunnel when finishing and rejects new opens', async () =
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not retry a rejected preview tunnel open after finishing', async () => {
|
||||
const host = await startHostAsync();
|
||||
await (await host.openPreviewAsync()).closeAsync();
|
||||
const forwardCalls = jest.mocked(ngrok.forward).mock.calls.length;
|
||||
const tunnel = deferred<Awaited<ReturnType<typeof ngrok.forward>>>();
|
||||
jest.mocked(ngrok.forward).mockReturnValueOnce(tunnel.promise);
|
||||
const opening = host.openPreviewAsync();
|
||||
const finishing = host.finishAsync();
|
||||
tunnel.reject(
|
||||
new Error('failed to start listener: internal server error error_code: ERR_NGROK_802')
|
||||
);
|
||||
await expect(opening).rejects.toThrow('ERR_NGROK_802');
|
||||
await finishing;
|
||||
expect(jest.mocked(ngrok.forward).mock.calls.length).toBe(forwardCalls + 1);
|
||||
expect(logger.warn).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.stringContaining('; retrying.')
|
||||
);
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not retry a rejected preview tunnel open after startup fails', async () => {
|
||||
jest.useFakeTimers({ doNotFake: ['setImmediate'] });
|
||||
const forwardCalls = jest.mocked(ngrok.forward).mock.calls.length;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockRejectedValueOnce(
|
||||
new Error('failed to start listener: internal server error error_code: ERR_NGROK_802')
|
||||
);
|
||||
const startGate = deferred<void>();
|
||||
const startupError = new Error('startup failure');
|
||||
const startAsync = jest.fn(async () => {
|
||||
await startGate.promise;
|
||||
throw startupError;
|
||||
});
|
||||
const outcome = startDeviceSessionHostAsync(
|
||||
ctx,
|
||||
{
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
preview: { baseDomain, authtoken },
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: 30_000,
|
||||
},
|
||||
{
|
||||
port: 3200,
|
||||
turnArgs: Promise.resolve([]),
|
||||
requiresPreviewRetirement: true,
|
||||
startAsync,
|
||||
stopAsync: stopServer,
|
||||
}
|
||||
).catch(error => error);
|
||||
const retrying = () =>
|
||||
jest
|
||||
.mocked(logger.warn)
|
||||
.mock.calls.some(([, message]) => String(message).endsWith('; retrying.'));
|
||||
for (let i = 0; i < 50 && !retrying(); i++) {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
}
|
||||
expect(retrying()).toBe(true);
|
||||
startGate.resolve();
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
expect(await outcome).toBe(startupError);
|
||||
expect(jest.mocked(ngrok.forward).mock.calls.length).toBe(forwardCalls + 1);
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps cleanup and upload best-effort when tunnel close and finalization fail', async () => {
|
||||
jest.mocked(spawnDetached).mockImplementationOnce(options => {
|
||||
directories.push(options.args[options.args.indexOf('--android-recording-directory') + 1]);
|
||||
@@ -1116,6 +1216,75 @@ it.each([
|
||||
await host.finishAsync();
|
||||
});
|
||||
|
||||
it('keeps the experimental emulator capture off in expo-device-hub by default', async () => {
|
||||
const host = await startHostAsync();
|
||||
const options = jest.mocked(spawnDetached).mock.calls[0][0];
|
||||
expect(options.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBe('0');
|
||||
await host.finishAsync();
|
||||
});
|
||||
|
||||
it('rejects an emulator capture request in a session type without the capture', async () => {
|
||||
await expect(
|
||||
startDeviceSessionHostAsync(ctx, {
|
||||
preview: { baseDomain, authtoken },
|
||||
runtimePlatform: BuildRuntimePlatform.LINUX,
|
||||
env: { ...env, EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION: '0.1.0' },
|
||||
logger,
|
||||
separateLogPhase: true,
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
).rejects.toThrow(
|
||||
'The experimental emulator capture ([email protected]) works only in web preview sessions for now.'
|
||||
);
|
||||
expect(spawnDetached).not.toHaveBeenCalled();
|
||||
expect(startNgrokTunnelAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes the emulator capture that the emulator start turned on to expo-device-hub', async () => {
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
preview: { baseDomain, authtoken },
|
||||
runtimePlatform: BuildRuntimePlatform.LINUX,
|
||||
env: {
|
||||
...env,
|
||||
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
|
||||
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: '/tmp/package/libexpo_emulator_capture.so',
|
||||
EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION: '0.1.0',
|
||||
},
|
||||
logger,
|
||||
separateLogPhase: true,
|
||||
timeoutMs: 10_000,
|
||||
emulatorCapture: true,
|
||||
});
|
||||
const options = jest.mocked(spawnDetached).mock.calls[0][0];
|
||||
expect(options.env).toMatchObject({
|
||||
EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '1',
|
||||
EXPO_DEVICE_HUB_EMULATOR_CAPTURE_LIBRARY: '/tmp/package/libexpo_emulator_capture.so',
|
||||
});
|
||||
// The env turns the capture on, because an expo-device-hub without it rejects unknown flags.
|
||||
expect(options.args).not.toContain('--experimental-emulator-capture');
|
||||
await host.finishAsync();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['the turtle-v2 copy by default', undefined, 'https://storage.googleapis.com/turtle-v2/scrcpy'],
|
||||
['the step env value when it is set', 'https://mirror.test/scrcpy', 'https://mirror.test/scrcpy'],
|
||||
])(
|
||||
'points expo-device-hub at %s for the scrcpy server',
|
||||
async (_description, override, expected) => {
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
preview: { baseDomain, authtoken },
|
||||
runtimePlatform: BuildRuntimePlatform.LINUX,
|
||||
env: override ? { ...env, SERVE_EMU_SCRCPY_BASE_URL: override } : env,
|
||||
logger,
|
||||
separateLogPhase: true,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
const options = jest.mocked(spawnDetached).mock.calls[0][0];
|
||||
expect(options.env.SERVE_EMU_SCRCPY_BASE_URL).toBe(expected);
|
||||
await host.finishAsync();
|
||||
}
|
||||
);
|
||||
|
||||
it('lets the session add frame ancestors and CORS origins after the website origins', async () => {
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
preview: { baseDomain, authtoken },
|
||||
@@ -1163,6 +1332,7 @@ it('leaves iOS recording to its existing build steps', async () => {
|
||||
const options = jest.mocked(spawnDetached).mock.calls[0][0];
|
||||
expect(options.args).not.toContain('--android-recording-directory');
|
||||
expect(options.env.EXPO_DEVICE_HUB_RECORDING_CONTROL_TOKEN).toBeUndefined();
|
||||
expect(options.env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE).toBeUndefined();
|
||||
await host.finishAsync();
|
||||
expect(jest.mocked(turtleFetch).mock.calls.some(([, method]) => method === 'POST')).toBe(false);
|
||||
expect(uploadDeviceRunSessionScreenRecordingsAsync).not.toHaveBeenCalled();
|
||||
@@ -1479,6 +1649,119 @@ it.each([BuildRuntimePlatform.LINUX, BuildRuntimePlatform.DARWIN])(
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['missing automation', 'invalid catalog', 'unavailable catalog'])(
|
||||
'skips automated thumbnails with %s without stopping the iOS session',
|
||||
async failure => {
|
||||
if (failure === 'unavailable catalog') {
|
||||
jest
|
||||
.mocked(runServeSimActionWithResultAsync)
|
||||
.mockRejectedValueOnce(new Error('unknown action'));
|
||||
} else {
|
||||
jest
|
||||
.mocked(runServeSimActionWithResultAsync)
|
||||
.mockResolvedValueOnce(
|
||||
failure === 'invalid catalog'
|
||||
? 'invalid JSON'
|
||||
: JSON.stringify({ 'screenshot.capture': { properties: {} } })
|
||||
);
|
||||
}
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: 10_000,
|
||||
preview: { baseDomain, authtoken },
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(runServeSimActionWithResultAsync).toHaveBeenCalledTimes(1);
|
||||
expect(startDeviceRunSessionPreview).not.toHaveBeenCalled();
|
||||
expect(ensureMacosPreviewEncoderInstalledAsync).not.toHaveBeenCalled();
|
||||
expect(stopServer).not.toHaveBeenCalled();
|
||||
await host.finishAsync();
|
||||
}
|
||||
);
|
||||
|
||||
it('cancels catalog inspection during shutdown without sending a thumbnail capture', async () => {
|
||||
let inspectionSignal: AbortSignal | undefined;
|
||||
jest.mocked(runServeSimActionWithResultAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
inspectionSignal = signal;
|
||||
return await new Promise<string>((_resolve, reject) => {
|
||||
signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
});
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: 10_000,
|
||||
preview: { baseDomain, authtoken },
|
||||
});
|
||||
expect(inspectionSignal?.aborted).toBe(false);
|
||||
await host.finishAsync();
|
||||
expect(inspectionSignal?.aborted).toBe(true);
|
||||
expect(startDeviceRunSessionPreview).not.toHaveBeenCalled();
|
||||
expect(ensureMacosPreviewEncoderInstalledAsync).not.toHaveBeenCalled();
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('finishes manual screenshots even when thumbnail cleanup fails', async () => {
|
||||
const finishScreenshots = jest.fn().mockResolvedValue(undefined);
|
||||
const collector = jest
|
||||
.spyOn(screenshotCollector, 'startDeviceRunSessionScreenshotsAsync')
|
||||
.mockResolvedValueOnce({
|
||||
directory: '/tmp/manual-screenshots',
|
||||
finishAsync: finishScreenshots,
|
||||
});
|
||||
const cleanup = jest.fn().mockRejectedValue(new Error('unlink refused'));
|
||||
const factory = jest.spyOn(previewCapture, 'createServeSimPreviewCapture').mockReturnValueOnce({
|
||||
isSupportedAsync: jest.fn().mockResolvedValue(true),
|
||||
captureAsync: jest.fn(),
|
||||
cleanupAfterHostStoppedAsync: cleanup,
|
||||
});
|
||||
try {
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: 10_000,
|
||||
preview: { baseDomain, authtoken },
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await host.finishAsync();
|
||||
expect(cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(finishScreenshots).toHaveBeenCalledWith(true);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ err: expect.any(Error) }),
|
||||
'Could not remove session preview capture files.'
|
||||
);
|
||||
} finally {
|
||||
factory.mockRestore();
|
||||
collector.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('drains thumbnail capture before stopping the iOS host', async () => {
|
||||
const stopped = deferred<void>();
|
||||
stopSessionPreview.mockReturnValueOnce(stopped.promise);
|
||||
const host = await startDeviceSessionHostAsync(ctx, {
|
||||
runtimePlatform: BuildRuntimePlatform.DARWIN,
|
||||
env,
|
||||
logger,
|
||||
timeoutMs: 10_000,
|
||||
preview: { baseDomain, authtoken },
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const finishing = host.finishAsync();
|
||||
try {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopServer).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
stopped.resolve();
|
||||
await finishing;
|
||||
}
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['success', 'failure'])(
|
||||
'keeps macOS readiness nonblocking and drains encoder setup %s before ending the phase',
|
||||
async result => {
|
||||
@@ -2080,6 +2363,22 @@ it('cancels an in-flight install while Simulator setup is pending', async () =>
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('finishes in-flight crash collection before stopping the host', async () => {
|
||||
const host = await startHostAsync();
|
||||
const collecting = deferred<void>();
|
||||
const entered = deferred<void>();
|
||||
jest.mocked(ServeSimCrashesRecorder.stopAsync).mockImplementationOnce(async () => {
|
||||
entered.resolve();
|
||||
await collecting.promise;
|
||||
});
|
||||
const finishing = host.finishAsync();
|
||||
await entered.promise;
|
||||
expect(stopServer).not.toHaveBeenCalled();
|
||||
collecting.resolve();
|
||||
await finishing;
|
||||
expect(stopServer).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('redacts bearer tokens from preview readiness diagnostics while preserving the failure', async () => {
|
||||
const output = [
|
||||
'Native addon failed to initialize',
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { createMockLogger } from '../../../__tests__/utils/logger';
|
||||
import { installIsolatedNpmPackageAsync } from '../../../utils/installIsolatedNpmPackageAsync';
|
||||
import {
|
||||
installEmulatorCaptureAsync,
|
||||
parseExperimentalEmulatorCaptureVersionInput,
|
||||
} from '../emulatorCapture';
|
||||
|
||||
jest.mock('../../../utils/installIsolatedNpmPackageAsync', () => ({
|
||||
installIsolatedNpmPackageAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const TEMPORARY_DIRECTORY = '/tmp/eas-test';
|
||||
const AGENT = 'node_modules/expo-emulator-capture/dist/linux-x64/libexpo_emulator_capture.so';
|
||||
const mockedInstall = jest.mocked(installIsolatedNpmPackageAsync);
|
||||
const { platform, arch } = process;
|
||||
|
||||
function setHost(hostPlatform: NodeJS.Platform, hostArch: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: hostPlatform });
|
||||
Object.defineProperty(process, 'arch', { value: hostArch });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(os, 'tmpdir').mockReturnValue(TEMPORARY_DIRECTORY);
|
||||
fs.mkdirSync(TEMPORARY_DIRECTORY, { recursive: true });
|
||||
mockedInstall.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
setHost(platform, arch);
|
||||
});
|
||||
|
||||
describe(parseExperimentalEmulatorCaptureVersionInput, () => {
|
||||
it.each([undefined, null, ''])('turns the capture off for %p', value => {
|
||||
expect(parseExperimentalEmulatorCaptureVersionInput(value)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(['0.1.0', '0.1.0-canary-20261106-2b670aa', 'canary', 'latest'])('accepts %s', value => {
|
||||
expect(parseExperimentalEmulatorCaptureVersionInput(value)).toBe(value);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'^0.1.0',
|
||||
'../0.1.0',
|
||||
'npm:[email protected]',
|
||||
'file:/tmp/agent',
|
||||
'0.1.0 ',
|
||||
'-0.1.0',
|
||||
'x'.repeat(129),
|
||||
1,
|
||||
])('rejects %p', value => {
|
||||
expect(() => parseExperimentalEmulatorCaptureVersionInput(value)).toThrow(UserError);
|
||||
});
|
||||
});
|
||||
|
||||
describe(installEmulatorCaptureAsync, () => {
|
||||
const env = { PATH: '/usr/bin', EAS_BUILD_NPM_CACHE_URL: 'https://npm-cache.example' };
|
||||
|
||||
it('installs the package in its own directory and returns its agent library', async () => {
|
||||
setHost('linux', 'x64');
|
||||
mockedInstall.mockImplementation(async ({ directory }) => {
|
||||
fs.mkdirSync(path.dirname(path.join(directory, AGENT)), { recursive: true });
|
||||
fs.writeFileSync(path.join(directory, AGENT), '');
|
||||
});
|
||||
const logger = createMockLogger();
|
||||
|
||||
const library = await installEmulatorCaptureAsync({ version: '0.1.0', env, logger });
|
||||
|
||||
expect(mockedInstall).toHaveBeenCalledWith({
|
||||
packageSpec: '[email protected]',
|
||||
directory: expect.stringMatching(/^\/tmp\/eas-test\/eas-emulator-capture-package-/),
|
||||
npmCacheUrl: 'https://npm-cache.example',
|
||||
pathEnv: '/usr/bin',
|
||||
logger,
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(library).toBe(path.join(mockedInstall.mock.calls[0][0].directory, AGENT));
|
||||
});
|
||||
|
||||
it('returns undefined when the install fails', async () => {
|
||||
setHost('linux', 'x64');
|
||||
mockedInstall.mockRejectedValue(new Error('npm error 404'));
|
||||
const logger = createMockLogger();
|
||||
|
||||
await expect(
|
||||
installEmulatorCaptureAsync({ version: '0.1.0', env, logger })
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ err: expect.any(Error) }),
|
||||
expect.stringContaining('Could not install [email protected]')
|
||||
);
|
||||
});
|
||||
|
||||
it('returns undefined when the package has no Linux agent library', async () => {
|
||||
setHost('linux', 'x64');
|
||||
mockedInstall.mockResolvedValue(undefined);
|
||||
const logger = createMockLogger();
|
||||
|
||||
await expect(
|
||||
installEmulatorCaptureAsync({ version: 'latest', env, logger })
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('expo-emulator-capture@latest has no Linux x86-64 agent at')
|
||||
);
|
||||
});
|
||||
|
||||
it('returns undefined on a host that is not Linux x86-64', async () => {
|
||||
setHost('darwin', 'arm64');
|
||||
const logger = createMockLogger();
|
||||
|
||||
await expect(
|
||||
installEmulatorCaptureAsync({ version: '0.1.0', env, logger })
|
||||
).resolves.toBeUndefined();
|
||||
expect(mockedInstall).not.toHaveBeenCalled();
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Linux x86-64'));
|
||||
});
|
||||
});
|
||||
@@ -563,26 +563,276 @@ it('does not queue more native opens while a timed-out open is still pending', a
|
||||
expect(replacement.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('bounds initial tunnel creation and retires a late listener', async () => {
|
||||
const ERR_802 = 'failed to start listener: internal server error error_code: ERR_NGROK_802';
|
||||
|
||||
it('bounds initial tunnel creation, does not retry a timed-out open, and retires a late listener', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(
|
||||
new Promise(resolve => {
|
||||
resolveOpening = resolve;
|
||||
})
|
||||
);
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out after 19000ms');
|
||||
await jest.advanceTimersByTimeAsync(19_000);
|
||||
await rejected;
|
||||
// ngrok runs opens one at a time, so a retry would only wait behind the stuck open.
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.stringContaining('); retrying.')
|
||||
);
|
||||
resolveOpening(initial as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ outcome: 'opened', elapsedMs: 19_000 }),
|
||||
'ngrok tunnel open for web-preview-fixed.example.test opened after 19000 ms, after it timed out or was cancelled.'
|
||||
);
|
||||
});
|
||||
|
||||
it('retries a rejected close after initial tunnel creation timed out', async () => {
|
||||
it('keeps a first open that settles after the reopen time-out', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(16_000);
|
||||
resolveOpening(initial as never);
|
||||
const tunnel = await opening;
|
||||
try {
|
||||
expect(tunnel.url).toBe(url);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
expect(initial.close).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fails without a retry when the first open fails for another reason after 15 seconds', async () => {
|
||||
let rejectOpening!: (error: Error) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(new Promise((_, reject) => (rejectOpening = reject)))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const error = new Error('invalid authtoken');
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toBe(error);
|
||||
await jest.advanceTimersByTimeAsync(16_000);
|
||||
rejectOpening(error);
|
||||
await rejected;
|
||||
await jest.advanceTimersByTimeAsync(10_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not retry a timed-out open that ngrok rejects later', async () => {
|
||||
let rejectOpening!: (error: Error) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(new Promise((_, reject) => (rejectOpening = reject)))
|
||||
.mockResolvedValue(replacement as never);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
|
||||
await jest.advanceTimersByTimeAsync(19_000);
|
||||
await rejected;
|
||||
rejectOpening(new Error(ERR_802));
|
||||
await jest.advanceTimersByTimeAsync(10_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries an initial open that ngrok rejects on a new agent session', async () => {
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockRejectedValueOnce(new Error(ERR_802))
|
||||
.mockResolvedValue(initial as never);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(1_000);
|
||||
const tunnel = await opening;
|
||||
try {
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
expect(jest.mocked(ngrok.forward).mock.calls[0][0]).not.toHaveProperty('force_new_session');
|
||||
expect(jest.mocked(ngrok.forward).mock.calls[1][0]).toMatchObject({ force_new_session: true });
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ attempt: 1 }),
|
||||
'Could not open ngrok tunnel web-preview-fixed.example.test (attempt 1 of 3); retrying.'
|
||||
);
|
||||
expect(tunnel.url).toBe(url);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('retries an initial open whose error carries the ngrok error code', async () => {
|
||||
const error = Object.assign(new Error('failed to start listener'), {
|
||||
errorCode: 'ERR_NGROK_802',
|
||||
});
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue(initial as never);
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
await jest.advanceTimersByTimeAsync(1_000);
|
||||
const tunnel = await opening;
|
||||
try {
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('gives a retry the reopen time-out', async () => {
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockRejectedValueOnce(new Error(ERR_802))
|
||||
.mockReturnValueOnce(new Promise(() => {}));
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out after 15000ms');
|
||||
await jest.advanceTimersByTimeAsync(1_000 + 15_000);
|
||||
await rejected;
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('fails after three rejected initial opens', async () => {
|
||||
jest.mocked(ngrok.forward).mockReset().mockRejectedValue(new Error(ERR_802));
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('ERR_NGROK_802');
|
||||
await jest.advanceTimersByTimeAsync(1_000 + 2_000);
|
||||
await rejected;
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(3);
|
||||
expect(jest.mocked(ngrok.forward).mock.calls[2][0]).toMatchObject({ force_new_session: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['another reason', 'invalid authtoken'],
|
||||
['a longer error code', 'internal server error error_code: ERR_NGROK_8021'],
|
||||
])('does not retry an initial open that fails for %s', async (_, message) => {
|
||||
jest.mocked(ngrok.forward).mockReset().mockRejectedValue(new Error(message));
|
||||
await expect(startNgrokTunnelAsync(options)).rejects.toThrow(message);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fails with the abort reason when the caller aborts during the retry backoff', async () => {
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockRejectedValueOnce(new Error(ERR_802))
|
||||
.mockResolvedValue(initial as never);
|
||||
const startup = new AbortController();
|
||||
const reason = new Error('startup aborted');
|
||||
const opening = startNgrokTunnelAsync({ ...options, signal: startup.signal });
|
||||
const rejected = expect(opening).rejects.toBe(reason);
|
||||
await jest.advanceTimersByTimeAsync(500);
|
||||
startup.abort(reason);
|
||||
await rejected;
|
||||
await jest.advanceTimersByTimeAsync(10_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not open when the caller aborts while the local target starts', async () => {
|
||||
const startup = new AbortController();
|
||||
const reason = new Error('startup aborted');
|
||||
const opening = startNgrokTunnelAsync({ ...options, signal: startup.signal });
|
||||
startup.abort(reason);
|
||||
await expect(opening).rejects.toBe(reason);
|
||||
expect(ngrok.forward).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([1, 2])(
|
||||
'fails with the abort reason and retires the late listener when the caller aborts while open %s is pending',
|
||||
async pendingAttempt => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
const pending = new Promise<ngrok.Listener>(resolve => (resolveOpening = resolve));
|
||||
const forward = jest.mocked(ngrok.forward).mockReset();
|
||||
if (pendingAttempt === 2) {
|
||||
forward.mockRejectedValueOnce(new Error(ERR_802));
|
||||
}
|
||||
forward.mockReturnValueOnce(pending as never).mockResolvedValue(replacement as never);
|
||||
const startup = new AbortController();
|
||||
const reason = new Error('startup aborted');
|
||||
const opening = startNgrokTunnelAsync({ ...options, signal: startup.signal });
|
||||
const rejected = expect(opening).rejects.toBe(reason);
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(pendingAttempt);
|
||||
startup.abort(reason);
|
||||
await rejected;
|
||||
resolveOpening(initial as never);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(30_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(pendingAttempt);
|
||||
}
|
||||
);
|
||||
|
||||
it('stops retrying without a new open when the retry signal aborts during the backoff', async () => {
|
||||
const error = new Error(ERR_802);
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue(initial as never);
|
||||
const retries = new AbortController();
|
||||
const opening = startNgrokTunnelAsync({ ...options, retrySignal: retries.signal });
|
||||
const rejected = expect(opening).rejects.toBe(error);
|
||||
await jest.advanceTimersByTimeAsync(500);
|
||||
retries.abort();
|
||||
await rejected;
|
||||
await jest.advanceTimersByTimeAsync(10_000);
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('lets the open in progress finish when the retry signal aborts', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
.mockReset()
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const retries = new AbortController();
|
||||
const opening = startNgrokTunnelAsync({ ...options, retrySignal: retries.signal });
|
||||
await jest.advanceTimersByTimeAsync(5_000);
|
||||
retries.abort();
|
||||
resolveOpening(initial as never);
|
||||
const tunnel = await opening;
|
||||
try {
|
||||
expect(tunnel.url).toBe(url);
|
||||
expect(initial.close).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops listening for the startup signal after startup fails', async () => {
|
||||
jest.mocked(ngrok.forward).mockReset().mockRejectedValue(new Error('invalid authtoken'));
|
||||
const startup = new AbortController();
|
||||
const removeEventListener = jest.spyOn(startup.signal, 'removeEventListener');
|
||||
await expect(startNgrokTunnelAsync({ ...options, signal: startup.signal })).rejects.toThrow(
|
||||
'invalid authtoken'
|
||||
);
|
||||
expect(removeEventListener).toHaveBeenCalledWith('abort', expect.any(Function));
|
||||
});
|
||||
|
||||
it('keeps the tunnel open when the startup signal aborts after startup', async () => {
|
||||
const startup = new AbortController();
|
||||
const tunnel = await startNgrokTunnelAsync({ ...options, signal: startup.signal });
|
||||
try {
|
||||
startup.abort();
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
expect(initial.close).not.toHaveBeenCalled();
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await tunnel.stopAsync();
|
||||
}
|
||||
expect(initial.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('retries a rejected close of a late listener after initial tunnel creation timed out', async () => {
|
||||
let resolveOpening!: (value: ngrok.Listener) => void;
|
||||
jest
|
||||
.mocked(ngrok.forward)
|
||||
@@ -590,7 +840,7 @@ it('retries a rejected close after initial tunnel creation timed out', async ()
|
||||
.mockReturnValueOnce(new Promise(resolve => (resolveOpening = resolve)));
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('Ngrok tunnel open timed out');
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
await jest.advanceTimersByTimeAsync(19_000);
|
||||
await rejected;
|
||||
initial.close.mockRejectedValueOnce(new Error('temporary unlisten failure'));
|
||||
resolveOpening(initial as never);
|
||||
@@ -816,8 +1066,10 @@ it.each(['resolve', 'reject'])(
|
||||
const opening = startNgrokTunnelAsync(options);
|
||||
const rejected = expect(opening).rejects.toThrow('open timed out');
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
await jest.advanceTimersByTimeAsync(15_000);
|
||||
// The first open times out, and startup does not retry it while it is still pending.
|
||||
await jest.advanceTimersByTimeAsync(19_000);
|
||||
await rejected;
|
||||
expect(ngrok.forward).toHaveBeenCalledTimes(1);
|
||||
const targetPort = (jest.mocked(ngrok.forward).mock.calls[0][0] as ngrok.Config).addr as number;
|
||||
if (outcome === 'resolve') {
|
||||
resolveOpening(replacement as never);
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
|
||||
import {
|
||||
readExpoDeviceHubInputLogAsync,
|
||||
readServeSimInputLogAsync,
|
||||
startPreviewActivityPolling,
|
||||
} from '../previewActivity';
|
||||
|
||||
const token = 'test-session-token';
|
||||
let server: http.Server;
|
||||
let port: number;
|
||||
let events: { id: number; at?: string; timestamp?: string }[];
|
||||
let status: number;
|
||||
let requests: { url?: string; authorization?: string }[];
|
||||
let rawBody: string | undefined;
|
||||
let replaying: boolean;
|
||||
let replayStartedAt: string | null;
|
||||
|
||||
function createLoggerMock(): bunyan {
|
||||
return { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
events = [];
|
||||
status = 200;
|
||||
requests = [];
|
||||
rawBody = undefined;
|
||||
replaying = false;
|
||||
replayStartedAt = null;
|
||||
server = http.createServer((req, res) => {
|
||||
requests.push({ url: req.url, authorization: req.headers.authorization });
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(rawBody ?? JSON.stringify({ events: events.slice(-1), replaying, replayStartedAt }));
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
port = (server.address() as { port: number }).port;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
describe(readServeSimInputLogAsync, () => {
|
||||
it('reads the newest event ID with the session token', async () => {
|
||||
events = [{ id: 3 }, { id: 7 }];
|
||||
await expect(readServeSimInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: 7,
|
||||
latestEventAt: undefined,
|
||||
replaying: false,
|
||||
replayStartedAt: undefined,
|
||||
});
|
||||
expect(requests).toEqual([{ url: '/api/event-log?limit=1', authorization: `Bearer ${token}` }]);
|
||||
});
|
||||
|
||||
it('returns undefined when serve-sim has logged no event', async () => {
|
||||
await expect(readServeSimInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: undefined,
|
||||
latestEventAt: undefined,
|
||||
replaying: false,
|
||||
replayStartedAt: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['unparseable JSON', 'not json'],
|
||||
['a body without an events array', '{}'],
|
||||
['an entry without a numeric ID', '{"events":[{"id":"7"}]}'],
|
||||
])('rejects %s', async (_, body) => {
|
||||
rawBody = body;
|
||||
await expect(readServeSimInputLogAsync({ port, token })).rejects.toThrow('serve-sim event log');
|
||||
});
|
||||
|
||||
it('rejects a refused request', async () => {
|
||||
status = 401;
|
||||
await expect(readServeSimInputLogAsync({ port, token })).rejects.toThrow('401');
|
||||
});
|
||||
});
|
||||
|
||||
describe(readExpoDeviceHubInputLogAsync, () => {
|
||||
it('reads the newest entry time from either server', async () => {
|
||||
events = [{ id: 2, timestamp: '2026-11-13T12:00:02.000Z' }];
|
||||
await expect(readServeSimInputLogAsync({ port, token })).resolves.toMatchObject({
|
||||
latestEventId: 2,
|
||||
latestEventAt: '2026-11-13T12:00:02.000Z',
|
||||
});
|
||||
events = [{ id: 3, at: '2026-11-13T12:00:03.000Z' }];
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).resolves.toMatchObject({
|
||||
latestEventId: 3,
|
||||
latestEventAt: '2026-11-13T12:00:03.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the newest recorded Android input through the hub with the session token', async () => {
|
||||
events = [{ id: 3 }, { id: 9 }];
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: 9,
|
||||
latestEventAt: undefined,
|
||||
replaying: false,
|
||||
replayStartedAt: undefined,
|
||||
});
|
||||
expect(requests).toEqual([
|
||||
{ url: '/vendor/serve-emu/api/session?limit=1', authorization: `Bearer ${token}` },
|
||||
]);
|
||||
});
|
||||
|
||||
it('reports a running replay and when it started', async () => {
|
||||
replaying = true;
|
||||
replayStartedAt = '2026-11-13T12:00:00.000Z';
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: undefined,
|
||||
latestEventAt: undefined,
|
||||
replaying: true,
|
||||
replayStartedAt: '2026-11-13T12:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads replay state from the paged response shape', async () => {
|
||||
rawBody = JSON.stringify({
|
||||
events: [{ id: 4, at: '2026-11-13T12:00:01.000Z' }],
|
||||
session: { replaying: true, replayStartedAt: '2026-11-13T12:00:00.000Z' },
|
||||
});
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: 4,
|
||||
latestEventAt: '2026-11-13T12:00:01.000Z',
|
||||
replaying: true,
|
||||
replayStartedAt: '2026-11-13T12:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns no event ID when the hub has recorded no input', async () => {
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).resolves.toEqual({
|
||||
latestEventId: undefined,
|
||||
latestEventAt: undefined,
|
||||
replaying: false,
|
||||
replayStartedAt: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['unparseable JSON', 'not json'],
|
||||
['a body without an events array', '{}'],
|
||||
['an entry without a numeric ID', '{"events":[{"id":"9"}]}'],
|
||||
])('rejects %s', async (_, body) => {
|
||||
rawBody = body;
|
||||
await expect(readExpoDeviceHubInputLogAsync({ port, token })).rejects.toThrow(
|
||||
'expo-device-hub input log'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(startPreviewActivityPolling, () => {
|
||||
async function waitForRequestsAsync(count: number): Promise<void> {
|
||||
while (requests.length < count) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
}
|
||||
|
||||
it('reports activity only when a new event appears', async () => {
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
|
||||
events = [{ id: 1 }];
|
||||
const before = Date.now();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const firstSeen = polling.getLastActivityObservedAt();
|
||||
expect(firstSeen?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(firstSeen);
|
||||
|
||||
events = [{ id: 1 }, { id: 2 }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).not.toBe(firstSeen);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity while the event log fails, and warns once', async () => {
|
||||
status = 500;
|
||||
const logger = createLoggerMock();
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(3);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
status = 200;
|
||||
events = [{ id: 4 }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const observedAt = polling.getLastActivityObservedAt();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(observedAt);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the last observation while serve-sim refuses connections', async () => {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
server = http.createServer();
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity when serve-sim drops the connection mid-response', async () => {
|
||||
server.removeAllListeners('request');
|
||||
server.on('request', (req, res) => {
|
||||
requests.push({ url: req.url });
|
||||
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
|
||||
res.write('{"events":');
|
||||
setImmediate(() => res.socket?.destroy());
|
||||
});
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(3);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity while serve-sim answers without an event log', async () => {
|
||||
status = 404;
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
status = 200;
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports Android preview input from expo-device-hub', async () => {
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
expect(requests[0].url).toBe('/vendor/serve-emu/api/session?limit=1');
|
||||
|
||||
events = [{ id: 1 }];
|
||||
const before = Date.now();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports activity while expo-device-hub replays recorded input', async () => {
|
||||
replaying = true;
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const before = Date.now();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports a replay that started and finished between two reads', async () => {
|
||||
events = [{ id: 1 }];
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const observedAt = polling.getLastActivityObservedAt();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(observedAt);
|
||||
|
||||
replayStartedAt = '2026-11-13T12:00:00.000Z';
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const replayObservedAt = polling.getLastActivityObservedAt();
|
||||
expect(replayObservedAt).not.toBe(observedAt);
|
||||
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(replayObservedAt);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('counts input in a new recording that repeats the last ID between two reads', async () => {
|
||||
events = [{ id: 1, at: '2026-11-13T12:00:00.000Z' }];
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const firstSeen = polling.getLastActivityObservedAt();
|
||||
expect(firstSeen).toBeDefined();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(firstSeen);
|
||||
|
||||
events = [{ id: 1, at: '2026-11-13T12:05:00.000Z' }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).not.toBe(firstSeen);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('counts input in a new recording whose IDs start again', async () => {
|
||||
events = [{ id: 1 }];
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const firstSeen = polling.getLastActivityObservedAt();
|
||||
expect(firstSeen).toBeDefined();
|
||||
|
||||
events = [];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
events = [{ id: 1 }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).not.toBe(firstSeen);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['before its headers', 'headers'],
|
||||
['after its headers', 'body'],
|
||||
] as const)(
|
||||
'reports current activity while an expo-device-hub read times out %s',
|
||||
async (_, stall) => {
|
||||
events = [{ id: 1 }];
|
||||
let stalled = false;
|
||||
server.removeAllListeners('request');
|
||||
server.on('request', (req, res) => {
|
||||
requests.push({ url: req.url });
|
||||
if (stalled && stall === 'headers') {
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
if (stalled) {
|
||||
res.write('{"events":[');
|
||||
return;
|
||||
}
|
||||
res.end(JSON.stringify({ events, replaying: false, replayStartedAt: null }));
|
||||
});
|
||||
const logger = createLoggerMock();
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger,
|
||||
pollIntervalMs: 10,
|
||||
requestTimeoutMs: 100,
|
||||
});
|
||||
try {
|
||||
while (polling.getLastActivityObservedAt() === undefined) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
const observedAt = polling.getLastActivityObservedAt();
|
||||
|
||||
stalled = true;
|
||||
// The next request starts only after the stalled read times out.
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const reportedAt = polling.getLastActivityObservedAt();
|
||||
expect(reportedAt).not.toBe(observedAt);
|
||||
expect(jest.mocked(logger.warn).mock.calls[0][1]).toContain(
|
||||
'idle timeout does not stop this session'
|
||||
);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
server.closeAllConnections();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('warns about an unreadable log after an earlier device outage', async () => {
|
||||
const logger = createLoggerMock();
|
||||
status = 503;
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
|
||||
status = 500;
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(2);
|
||||
expect(jest.mocked(logger.warn).mock.calls[1][1]).toContain(
|
||||
'idle timeout does not stop this session'
|
||||
);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the last observation while expo-device-hub has no device', async () => {
|
||||
events = [{ id: 1 }];
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'expo-device-hub',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const observedAt = polling.getLastActivityObservedAt();
|
||||
expect(observedAt).toBeDefined();
|
||||
|
||||
status = 503;
|
||||
await waitForRequestsAsync(requests.length + 3);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(observedAt);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity when serve-sim answers 503', async () => {
|
||||
status = 503;
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops polling after stopAsync', async () => {
|
||||
const polling = startPreviewActivityPolling({
|
||||
server: 'serve-sim',
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
await waitForRequestsAsync(1);
|
||||
await polling.stopAsync();
|
||||
const count = requests.length;
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
expect(requests.length).toBe(count);
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,7 @@ import { sleepAsync } from '../../../utils/retry';
|
||||
import { uploadDeviceRunSessionScreenRecordingsAsync } from '../deviceRunSessionScreenRecordings';
|
||||
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
|
||||
import {
|
||||
TOOL_TUNNEL_TEARDOWN_OPTIONS,
|
||||
createCorsOriginsInputProvider,
|
||||
createFrameAncestorsInputProvider,
|
||||
createIosSessionStartupInputProviders,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
describeServeSimLaunch,
|
||||
ensureFfmpegInstalledOnceAsync,
|
||||
fetchWebPreviewTurnArgsAsync,
|
||||
finishRemoteSessionAsync,
|
||||
parseCorsOriginsInput,
|
||||
parseFrameAncestorsInput,
|
||||
parseServeSimLaunchInputs,
|
||||
@@ -226,6 +228,89 @@ function createEnvMock(): BuildStepEnv {
|
||||
return { DEVICE_RUN_SESSION_ID: 'drs-id' } as unknown as BuildStepEnv;
|
||||
}
|
||||
|
||||
describe(finishRemoteSessionAsync, () => {
|
||||
const tunnelError = new Error('tunnel stop timed out');
|
||||
const serverError = new Error('server stop failed');
|
||||
|
||||
beforeEach(() => {
|
||||
jest.mocked(Sentry).capture.mockReset();
|
||||
});
|
||||
|
||||
it('does not fail a successful session when only a tunnel cannot stop', async () => {
|
||||
const logger = { warn: jest.fn() } as unknown as bunyan;
|
||||
await expect(
|
||||
finishRemoteSessionAsync({
|
||||
logger,
|
||||
sessionFailed: false,
|
||||
teardown: [
|
||||
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['Appium server', Promise.resolve()],
|
||||
],
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: tunnelError },
|
||||
'Could not stop the Appium tunnel during remote session teardown.'
|
||||
);
|
||||
expect(jest.mocked(Sentry).capture.mock.calls).toEqual([
|
||||
[
|
||||
'Could not stop the Appium tunnel after the remote session ended',
|
||||
tunnelError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails a successful session with the first failure that fails the session', async () => {
|
||||
const logger = { warn: jest.fn() } as unknown as bunyan;
|
||||
await expect(
|
||||
finishRemoteSessionAsync({
|
||||
logger,
|
||||
sessionFailed: false,
|
||||
teardown: [
|
||||
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['Appium server', Promise.reject(serverError)],
|
||||
],
|
||||
})
|
||||
).rejects.toBe(serverError);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(2);
|
||||
expect(jest.mocked(Sentry).capture.mock.calls).toEqual([
|
||||
[
|
||||
'Could not stop the Appium tunnel after the remote session ended',
|
||||
tunnelError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it('reports every teardown failure to Sentry when the session failed', async () => {
|
||||
const logger = { warn: jest.fn() } as unknown as bunyan;
|
||||
await expect(
|
||||
finishRemoteSessionAsync({
|
||||
logger,
|
||||
sessionFailed: true,
|
||||
teardown: [
|
||||
['Appium tunnel', Promise.reject(tunnelError), TOOL_TUNNEL_TEARDOWN_OPTIONS],
|
||||
['Appium server', Promise.reject(serverError)],
|
||||
['session host', undefined],
|
||||
],
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
expect(jest.mocked(Sentry).capture.mock.calls).toEqual([
|
||||
[
|
||||
'Could not stop the Appium tunnel after the remote session failed',
|
||||
tunnelError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
[
|
||||
'Could not stop the Appium server after the remote session failed',
|
||||
serverError,
|
||||
{ level: 'warning' },
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe(createIosSessionStartupInputProviders, () => {
|
||||
it('declares optional inputs so existing workflows do not opt into owned startup', () => {
|
||||
const inputs = createIosSessionStartupInputProviders().map(provider =>
|
||||
|
||||
@@ -16,7 +16,11 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
import { runServeSimActionAsync, stageServeSimAppAsync } from '../serveSimActions';
|
||||
import {
|
||||
runServeSimActionAsync,
|
||||
runServeSimActionWithResultAsync,
|
||||
stageServeSimAppAsync,
|
||||
} from '../serveSimActions';
|
||||
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
@@ -67,6 +71,18 @@ it('authenticates the upgrade, waits for ready, and sends the action once', asyn
|
||||
expect(actions).toEqual([{ id: 1, action: 'app.install', params: request().params }]);
|
||||
});
|
||||
|
||||
it('returns stdout from an authenticated action for catalog inspection', async () => {
|
||||
server.on('connection', socket => {
|
||||
socket.on('message', () =>
|
||||
socket.send(JSON.stringify({ id: 1, stdout: '{"actions":[]}', exitCode: 0 }))
|
||||
);
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
});
|
||||
await expect(
|
||||
runServeSimActionWithResultAsync({ ...request(), action: 'actions.describe', params: {} })
|
||||
).resolves.toBe('{"actions":[]}');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ id: 1, exitCode: 1, stderr: 'install refused' }, 'install refused'],
|
||||
[{ id: 1, error: 'unknown action app.install' }, 'unknown action'],
|
||||
@@ -137,6 +153,55 @@ it('aborts an in-flight action without resending it', async () => {
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
it('cancels before dispatch while waiting for ready in drain mode', async () => {
|
||||
const controller = new AbortController();
|
||||
const actions = jest.fn();
|
||||
server.on('connection', socket => {
|
||||
socket.on('message', actions);
|
||||
controller.abort(new Error('stopped before ready'));
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
});
|
||||
await expect(
|
||||
runServeSimActionAsync({
|
||||
...request(),
|
||||
signal: controller.signal,
|
||||
drainAfterDispatch: true,
|
||||
})
|
||||
).rejects.toThrow('stopped before ready');
|
||||
expect(actions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drains dispatched actions after cancellation in drain mode', async () => {
|
||||
const controller = new AbortController();
|
||||
let reply!: () => void;
|
||||
let dispatched!: () => void;
|
||||
const ready = new Promise<void>(resolve => {
|
||||
dispatched = resolve;
|
||||
});
|
||||
server.on('connection', socket => {
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
socket.on('message', () => {
|
||||
reply = () => socket.send(JSON.stringify({ id: 1, stdout: 'completed', exitCode: 0 }));
|
||||
dispatched();
|
||||
});
|
||||
});
|
||||
let settled = false;
|
||||
const action = runServeSimActionAsync({
|
||||
...request(),
|
||||
signal: controller.signal,
|
||||
drainAfterDispatch: true,
|
||||
});
|
||||
void action.finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
await ready;
|
||||
controller.abort(new Error('stopped after dispatch'));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(settled).toBe(false);
|
||||
reply();
|
||||
await expect(action).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not connect when already aborted', async () => {
|
||||
const connected = jest.fn();
|
||||
server.on('connection', connected);
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
|
||||
import { fetchLatestServeSimEventIdAsync, startServeSimActivityPolling } from '../serveSimActivity';
|
||||
|
||||
const token = 'test-session-token';
|
||||
let server: http.Server;
|
||||
let port: number;
|
||||
let events: { id: number }[];
|
||||
let status: number;
|
||||
let requests: { url?: string; authorization?: string }[];
|
||||
let rawBody: string | undefined;
|
||||
|
||||
function createLoggerMock(): bunyan {
|
||||
return { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
events = [];
|
||||
status = 200;
|
||||
requests = [];
|
||||
rawBody = undefined;
|
||||
server = http.createServer((req, res) => {
|
||||
requests.push({ url: req.url, authorization: req.headers.authorization });
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(rawBody ?? JSON.stringify({ events: events.slice(-1) }));
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
port = (server.address() as { port: number }).port;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
describe(fetchLatestServeSimEventIdAsync, () => {
|
||||
it('reads the newest event ID with the session token', async () => {
|
||||
events = [{ id: 3 }, { id: 7 }];
|
||||
await expect(fetchLatestServeSimEventIdAsync({ port, token })).resolves.toBe(7);
|
||||
expect(requests).toEqual([{ url: '/api/event-log?limit=1', authorization: `Bearer ${token}` }]);
|
||||
});
|
||||
|
||||
it('returns undefined when serve-sim has logged no event', async () => {
|
||||
await expect(fetchLatestServeSimEventIdAsync({ port, token })).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['unparseable JSON', 'not json'],
|
||||
['a body without an events array', '{}'],
|
||||
['an entry without a numeric ID', '{"events":[{"id":"7"}]}'],
|
||||
])('rejects %s', async (_, body) => {
|
||||
rawBody = body;
|
||||
await expect(fetchLatestServeSimEventIdAsync({ port, token })).rejects.toThrow(
|
||||
'serve-sim event log'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a refused request', async () => {
|
||||
status = 401;
|
||||
await expect(fetchLatestServeSimEventIdAsync({ port, token })).rejects.toThrow('401');
|
||||
});
|
||||
});
|
||||
|
||||
describe(startServeSimActivityPolling, () => {
|
||||
async function waitForRequestsAsync(count: number): Promise<void> {
|
||||
while (requests.length < count) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
}
|
||||
|
||||
it('reports activity only when a new event appears', async () => {
|
||||
const polling = startServeSimActivityPolling({
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
|
||||
events = [{ id: 1 }];
|
||||
const before = Date.now();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const firstSeen = polling.getLastActivityObservedAt();
|
||||
expect(firstSeen?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(firstSeen);
|
||||
|
||||
events = [{ id: 1 }, { id: 2 }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).not.toBe(firstSeen);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity while the event log fails, and warns once', async () => {
|
||||
status = 500;
|
||||
const logger = createLoggerMock();
|
||||
const polling = startServeSimActivityPolling({ port, token, logger, pollIntervalMs: 10 });
|
||||
try {
|
||||
await waitForRequestsAsync(3);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
status = 200;
|
||||
events = [{ id: 4 }];
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
const observedAt = polling.getLastActivityObservedAt();
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBe(observedAt);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the last observation while serve-sim refuses connections', async () => {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
server = http.createServer();
|
||||
const polling = startServeSimActivityPolling({
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity when serve-sim drops the connection mid-response', async () => {
|
||||
server.removeAllListeners('request');
|
||||
server.on('request', (req, res) => {
|
||||
requests.push({ url: req.url });
|
||||
res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': '100' });
|
||||
res.write('{"events":');
|
||||
setImmediate(() => res.socket?.destroy());
|
||||
});
|
||||
const polling = startServeSimActivityPolling({
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(3);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports current activity while serve-sim answers without an event log', async () => {
|
||||
status = 404;
|
||||
const polling = startServeSimActivityPolling({
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
try {
|
||||
await waitForRequestsAsync(2);
|
||||
const before = Date.now();
|
||||
expect(polling.getLastActivityObservedAt()?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
|
||||
status = 200;
|
||||
await waitForRequestsAsync(requests.length + 2);
|
||||
expect(polling.getLastActivityObservedAt()).toBeUndefined();
|
||||
} finally {
|
||||
await polling.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops polling after stopAsync', async () => {
|
||||
const polling = startServeSimActivityPolling({
|
||||
port,
|
||||
token,
|
||||
logger: createLoggerMock(),
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
await waitForRequestsAsync(1);
|
||||
await polling.stopAsync();
|
||||
const count = requests.length;
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
expect(requests.length).toBe(count);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { mkdtemp, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('../deviceRunSessionArtifacts');
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
jest.unmock('fs/promises');
|
||||
jest.unmock('node:fs/promises');
|
||||
|
||||
const ctx = {} as CustomBuildContext;
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
let crash: { udid: string; filePath: string; size: number; number: number };
|
||||
|
||||
beforeAll(async () => {
|
||||
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'crash-test-')), 'A-2.ips');
|
||||
await writeFile(filePath, '{"app_name":"Crash"}');
|
||||
crash = { udid: 'ABCDEF123456', filePath, size: 20, number: 2 };
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[undefined, 'Crash report 2 (ABCDEF12)', 'crash-2.ips'],
|
||||
['My/App:Beta\n', 'Crash report 2: My/App:Beta\n (ABCDEF12)', 'My-App-Beta--2.ips'],
|
||||
])('names the report for process %j', async (processName, name, filename) => {
|
||||
await uploadServeSimCrashesFileAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
crash: { ...crash, ...(processName ? { processName } : {}) },
|
||||
logger,
|
||||
});
|
||||
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
artifactId: 'simulator-crash-ABCDEF123456-2',
|
||||
name,
|
||||
filename,
|
||||
kind: 'simulator-crash',
|
||||
metadata: { __eas_type: 'simulator-crash', udid: 'ABCDEF123456', source: 'serve-sim/crashes' },
|
||||
size: 20,
|
||||
openStream: expect.any(Function),
|
||||
signal: expect.any(AbortSignal),
|
||||
attempts: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports a failed upload by report number without rejecting', async () => {
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
|
||||
await expect(
|
||||
uploadServeSimCrashesFileAsync(ctx, { deviceRunSessionId: 'drs-id', crash, logger })
|
||||
).resolves.toBeUndefined();
|
||||
expect(Sentry.capture).toHaveBeenCalledWith(
|
||||
'Could not upload a simulator crash report',
|
||||
expect.objectContaining({ message: 'offline' }),
|
||||
{ level: 'warning' }
|
||||
);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ message: 'offline' }) },
|
||||
'Could not upload crash report 2 for ABCDEF123456; other artifacts will continue.'
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,816 @@
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { type IncomingMessage, type Server, type ServerResponse, createServer } from 'node:http';
|
||||
import { type AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
import { type CustomBuildContext } from '../../../customBuildContext';
|
||||
import { DEVICE_RUN_SESSION_TOKEN_HEADER } from '../deviceRunSessionWorkerApi';
|
||||
import { uploadServeSimCrashesFileAsync } from '../serveSimCrashesArtifacts';
|
||||
import { ServeSimCrashesRecorder } from '../serveSimCrashesRecorder';
|
||||
import * as serveSimServers from '../serveSimMetricsRecorder';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.unmock('fs');
|
||||
jest.unmock('node:fs');
|
||||
jest.unmock('fs/promises');
|
||||
jest.unmock('node:fs/promises');
|
||||
jest.unmock('node-fetch');
|
||||
|
||||
const fs = jest.requireActual<typeof import('node:fs/promises')>('node:fs/promises');
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
let directory: string;
|
||||
let server: Server;
|
||||
let baseUrl: string;
|
||||
const summary = { id: 'crash/a', appName: 'Fixture', occurrenceTimes: [{ key: 1 }, { key: 2 }] };
|
||||
const report = (key: number) =>
|
||||
JSON.stringify({ app_name: 'Fixture 서울 🌲', incident_id: `INC-${key}` }) +
|
||||
'\n' +
|
||||
JSON.stringify({ exception: { type: 'EXC_CRASH', signal: 'SIGABRT' }, incident: `INC-${key}` }) +
|
||||
'\n';
|
||||
const detail = (key: number) => ({
|
||||
record: { id: summary.id, bundleId: 'dev.expo.fixture' },
|
||||
occurrence: { key, incidentId: `INC-${key}`, logTail: ['PRIVATE APP LOG'], pid: 123 },
|
||||
report: report(key),
|
||||
reportError: null,
|
||||
});
|
||||
|
||||
/** Answers the one-shot list that stopping reads; returns false for other requests. */
|
||||
function answerList(
|
||||
request: IncomingMessage,
|
||||
response: ServerResponse,
|
||||
crashes: unknown[] = []
|
||||
): boolean {
|
||||
if (request.headers.accept !== 'application/json') {
|
||||
return false;
|
||||
}
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
response.end(JSON.stringify({ meta: { statusError: null }, crashes }));
|
||||
return true;
|
||||
}
|
||||
|
||||
function stoppedRetrying(): boolean {
|
||||
return jest
|
||||
.mocked(logger.warn)
|
||||
.mock.calls.some(([message]) =>
|
||||
String(message).startsWith('Stopped retrying simulator crash collection')
|
||||
);
|
||||
}
|
||||
|
||||
async function waitFor(read: () => boolean | Promise<boolean>): Promise<void> {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
if (await read()) {
|
||||
return;
|
||||
}
|
||||
await delay(10);
|
||||
}
|
||||
throw new Error('Timed out waiting for crash recording');
|
||||
}
|
||||
|
||||
async function start(maxBytes?: number): Promise<void> {
|
||||
await writeFile(
|
||||
path.join(directory, 'server-device-A.json'),
|
||||
JSON.stringify({
|
||||
device: 'device-A',
|
||||
url: baseUrl,
|
||||
token: 'test-token',
|
||||
})
|
||||
);
|
||||
await ServeSimCrashesRecorder.startAsync({
|
||||
logger,
|
||||
stateDir: directory,
|
||||
pollIntervalMs: 10,
|
||||
maxBytes,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(os.tmpdir(), 'crashes-http-test-'));
|
||||
server = createServer();
|
||||
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
const { outputDirectory } = await ServeSimCrashesRecorder.finishAsync();
|
||||
if (outputDirectory) {
|
||||
await rm(outputDirectory, { recursive: true, force: true });
|
||||
}
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('saves recurrences as separate private IPS files and uploads unchanged reports without app logs', async () => {
|
||||
let connections = 0;
|
||||
let requests = 0;
|
||||
const uploaded: Buffer[] = [];
|
||||
let uploadAttempts = 0;
|
||||
const uploadInputs: { filename: string }[] = [];
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
|
||||
expect(request.method).toBe('POST');
|
||||
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
|
||||
const chunks: Buffer[] = [];
|
||||
request.on('data', chunk => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
uploadInputs.push(JSON.parse(Buffer.concat(chunks).toString()));
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
response.end(
|
||||
JSON.stringify({ data: { uploadSession: { url: baseUrl + '/upload', headers: {} } } })
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (request.method === 'PUT') {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on('data', chunk => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
uploaded.push(Buffer.concat(chunks));
|
||||
uploadAttempts += 1;
|
||||
response.writeHead(uploadAttempts === 1 ? 503 : 200).end();
|
||||
});
|
||||
return;
|
||||
}
|
||||
expect(request.headers.authorization).toBe('Bearer test-token');
|
||||
const url = new URL(request.url!, baseUrl);
|
||||
expect(url.searchParams.get('device')).toBe('device-A');
|
||||
if (answerList(request, response, [summary])) {
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/crashes') {
|
||||
expect(url.searchParams.has('tail')).toBe(false);
|
||||
expect(request.headers.accept).toBe('text/event-stream');
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
const initial = { ...summary, occurrenceTimes: [{ key: 1 }] };
|
||||
const wire = `data: ${JSON.stringify({ type: 'list', crashes: [initial] })}\r\n\r\n`;
|
||||
if (connections === 1) {
|
||||
response.end(wire);
|
||||
} else {
|
||||
response.write(
|
||||
wire + `data: ${JSON.stringify({ type: 'recurred', record: summary })}\r\n\r\n`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
expect(url.pathname).toBe('/crashes/crash%2Fa');
|
||||
requests += 1;
|
||||
response.end(JSON.stringify(detail(Number(url.searchParams.get('key')))));
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => requests === 2);
|
||||
await ServeSimCrashesRecorder.stopAsync();
|
||||
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(files).toHaveLength(2);
|
||||
expect(requests).toBe(2);
|
||||
const expected = [Buffer.from(report(1)), Buffer.from(report(2))];
|
||||
for (const [index, file] of files.entries()) {
|
||||
expect(path.extname(file.filePath)).toBe('.ips');
|
||||
expect(await readFile(file.filePath)).toEqual(expected[index]);
|
||||
expect((await stat(file.filePath)).mode & 0o777).toBe(0o600);
|
||||
expect((await stat(path.dirname(file.filePath))).mode & 0o777).toBe(0o700);
|
||||
}
|
||||
expect(files[0].filePath).not.toBe(files[1].filePath);
|
||||
const context = {
|
||||
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
|
||||
expoApiV2BaseUrl: baseUrl + '/v2/',
|
||||
} as unknown as CustomBuildContext;
|
||||
for (const crash of files) {
|
||||
await uploadServeSimCrashesFileAsync(context, {
|
||||
deviceRunSessionId: 'session-id',
|
||||
crash,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
expect(uploaded).toEqual([expected[0], expected[0], expected[1]]);
|
||||
expect(uploadAttempts).toBe(3);
|
||||
expect(uploadInputs.map(input => input.filename)).toEqual(['Fixture-1.ips', 'Fixture-2.ips']);
|
||||
expect(uploadInputs[0]).toMatchObject({
|
||||
name: 'Crash report 1: Fixture (device-A)',
|
||||
kind: 'simulator-crash',
|
||||
metadata: { __eas_type: 'simulator-crash', udid: 'device-A', source: 'serve-sim/crashes' },
|
||||
});
|
||||
expect(JSON.stringify(uploadInputs)).not.toContain('PRIVATE APP LOG');
|
||||
expect(await ServeSimCrashesRecorder.finishAsync()).toEqual({
|
||||
outputDirectory: null,
|
||||
crashes: [],
|
||||
});
|
||||
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('keeps an in-flight report download alive during stop and waits for its write', async () => {
|
||||
let requested = false;
|
||||
let finishReport: () => void = () => {};
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(`data: ${JSON.stringify({ type: 'crash', record: summary })}\n\n`);
|
||||
} else {
|
||||
requested = true;
|
||||
finishReport = () => response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => requested);
|
||||
const stopped = ServeSimCrashesRecorder.stopAsync();
|
||||
finishReport();
|
||||
await stopped;
|
||||
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
|
||||
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('closes a rejected stream socket and produces no artifact for an empty session', async () => {
|
||||
let closed = false;
|
||||
server.on('request', (request, response) => {
|
||||
request.socket.on('close', () => {
|
||||
closed = true;
|
||||
});
|
||||
response.writeHead(403).write('unfinished response');
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => closed);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toEqual([]);
|
||||
expect(collected.outputDirectory).toEqual(expect.any(String));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
expect(JSON.stringify(jest.mocked(logger.warn).mock.calls)).not.toContain('test-token');
|
||||
});
|
||||
|
||||
it('stops at a complete-record byte limit and keeps earlier reports', async () => {
|
||||
let requested = 0;
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [summary] })}\n\n`);
|
||||
} else {
|
||||
requested += 1;
|
||||
response.end(
|
||||
JSON.stringify(detail(Number(new URL(request.url!, baseUrl).searchParams.get('key'))))
|
||||
);
|
||||
}
|
||||
});
|
||||
await writeFile(
|
||||
path.join(directory, 'server-device-A.json'),
|
||||
JSON.stringify({ device: 'device-A', url: baseUrl })
|
||||
);
|
||||
await ServeSimCrashesRecorder.startAsync({
|
||||
logger,
|
||||
stateDir: directory,
|
||||
pollIntervalMs: 10,
|
||||
maxBytes: Buffer.byteLength(report(1)),
|
||||
});
|
||||
await waitFor(() => requested === 2);
|
||||
await ServeSimCrashesRecorder.stopAsync();
|
||||
const { crashes: files } = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(await readFile(files[0].filePath, 'utf8')).toBe(report(1));
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
|
||||
await rm(path.dirname(files[0].filePath), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'fails on every request',
|
||||
3,
|
||||
'Could not download crash occurrence 1 for device-A; skipping it.',
|
||||
(response: ServerResponse) => response.writeHead(500).end(),
|
||||
],
|
||||
[
|
||||
'is refused with a permanent 4xx',
|
||||
1,
|
||||
'Could not download crash occurrence 1 for device-A; skipping it.',
|
||||
(response: ServerResponse) => response.writeHead(400).end(),
|
||||
],
|
||||
[
|
||||
'is not valid JSON',
|
||||
1,
|
||||
'Could not download crash occurrence 1 for device-A; skipping it.',
|
||||
(response: ServerResponse) => response.end('{broken'),
|
||||
],
|
||||
[
|
||||
'exceeds 8 MiB',
|
||||
1,
|
||||
'Could not download crash occurrence 1 for device-A; skipping it.',
|
||||
(response: ServerResponse) =>
|
||||
response.end(JSON.stringify({ ...detail(1), report: 'x'.repeat(8 * 1024 * 1024) })),
|
||||
],
|
||||
[
|
||||
'does not match the occurrence',
|
||||
1,
|
||||
'Could not download crash occurrence 1 for device-A; skipping it.',
|
||||
(response: ServerResponse) => response.end(JSON.stringify(detail(2))),
|
||||
],
|
||||
[
|
||||
'is no longer kept',
|
||||
1,
|
||||
'Crash occurrence 1 is no longer available for device-A; earlier reports will be retained.',
|
||||
(response: ServerResponse) => response.writeHead(404).end(),
|
||||
],
|
||||
])(
|
||||
'skips an occurrence whose detail %s after %i attempts and keeps collecting the device',
|
||||
async (_name, attempts, warning, respond) => {
|
||||
let connections = 0;
|
||||
let badRequests = 0;
|
||||
server.on('request', (request, response) => {
|
||||
const url = new URL(request.url!, baseUrl);
|
||||
if (answerList(request, response)) {
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/crashes') {
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
// Every stream ends, so each reconnect replays the bad occurrence.
|
||||
response.end(
|
||||
`data: ${JSON.stringify({
|
||||
type: 'list',
|
||||
crashes: [
|
||||
{ id: 'crash/b', occurrenceTimes: [{ key: 1 }] },
|
||||
{ ...summary, occurrenceTimes: [{ key: 1 }] },
|
||||
],
|
||||
})}\n\n`
|
||||
);
|
||||
} else if (url.pathname === '/crashes/crash%2Fb') {
|
||||
badRequests += 1;
|
||||
respond(response);
|
||||
} else {
|
||||
response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => connections >= 12);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(badRequests).toBe(attempts);
|
||||
expect(stoppedRetrying()).toBe(false);
|
||||
expect(jest.mocked(logger.warn).mock.calls.filter(call => call.includes(warning))).toHaveLength(
|
||||
1
|
||||
);
|
||||
expect(collected.crashes).toHaveLength(1);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
}
|
||||
);
|
||||
|
||||
it('saves an occurrence whose detail fails once, without reconnecting', async () => {
|
||||
let connections = 0;
|
||||
let requests = 0;
|
||||
server.on('request', (request, response) => {
|
||||
if (answerList(request, response)) {
|
||||
return;
|
||||
}
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
|
||||
);
|
||||
} else {
|
||||
requests += 1;
|
||||
if (requests === 1) {
|
||||
response.writeHead(503).end();
|
||||
} else {
|
||||
response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => requests === 2);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(connections).toBe(1);
|
||||
expect(collected.crashes).toHaveLength(1);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
|
||||
expect(logger.warn).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.stringContaining('Could not download')
|
||||
);
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('collects an occurrence listed after the stream last delivered, when stopping', async () => {
|
||||
let streaming = false;
|
||||
server.on('request', (request, response) => {
|
||||
const url = new URL(request.url!, baseUrl);
|
||||
const listed = { ...summary, appName: '', procName: 'FixtureProcess' };
|
||||
if (answerList(request, response, [{ ...listed, occurrenceTimes: [{ key: 1 }] }])) {
|
||||
return;
|
||||
}
|
||||
if (url.pathname === '/crashes') {
|
||||
streaming = true;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
|
||||
} else {
|
||||
response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => streaming);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toEqual([
|
||||
{
|
||||
udid: 'device-A',
|
||||
filePath: path.join(collected.outputDirectory!, 'device-A-1.ips'),
|
||||
size: Buffer.byteLength(report(1)),
|
||||
number: 1,
|
||||
processName: 'FixtureProcess',
|
||||
},
|
||||
]);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('stops the final pass at its deadline and warns', async () => {
|
||||
let streaming = false;
|
||||
server.on('request', (request, response) => {
|
||||
if (answerList(request, response, [{ ...summary, occurrenceTimes: [{ key: 1 }] }])) {
|
||||
return;
|
||||
}
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
streaming = true;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`);
|
||||
}
|
||||
// The detail never answers.
|
||||
});
|
||||
await writeFile(
|
||||
path.join(directory, 'server-device-A.json'),
|
||||
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'test-token' })
|
||||
);
|
||||
await ServeSimCrashesRecorder.startAsync({
|
||||
logger,
|
||||
stateDir: directory,
|
||||
pollIntervalMs: 10,
|
||||
finalPassTimeoutMs: 100,
|
||||
});
|
||||
await waitFor(() => streaming);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toEqual([]);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Stopped checking device-A for crashes at the end-of-session deadline; collected reports will be retained.'
|
||||
);
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('warns once per device when serve-sim cannot watch crash reports', async () => {
|
||||
let connections = 0;
|
||||
server.on('request', (_request, response) => {
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.end(
|
||||
`data: ${JSON.stringify({ type: 'meta', meta: { statusError: 'EACCES' } })}\n\n` +
|
||||
`data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`
|
||||
);
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => connections >= 3);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(
|
||||
jest
|
||||
.mocked(logger.warn)
|
||||
.mock.calls.filter(([message]) => String(message).startsWith('serve-sim cannot watch'))
|
||||
).toHaveLength(1);
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['empty', ''],
|
||||
['heartbeat-only', ': heartbeat\n\n'],
|
||||
['meta-only', `data: ${JSON.stringify({ type: 'meta', meta: { statusError: null } })}\n\n`],
|
||||
['invalid JSON', 'data: {invalid}\n\n'],
|
||||
['invalid frame', 'data: {"type":"list","crashes":false}\n\n'],
|
||||
])('stops retrying after ten %s streams', async (_name, payload) => {
|
||||
let connections = 0;
|
||||
server.on('request', (_request, response) => {
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.end(payload);
|
||||
});
|
||||
await start();
|
||||
await waitFor(stoppedRetrying);
|
||||
await delay(30);
|
||||
expect(connections).toBe(10);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toEqual([]);
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('keeps retrying streams that process a healthy empty crash list', async () => {
|
||||
let connections = 0;
|
||||
server.on('request', (_request, response) => {
|
||||
connections += 1;
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [] })}\n\n`;
|
||||
if (connections < 12) {
|
||||
response.end(frame);
|
||||
} else {
|
||||
response.write(frame);
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => connections === 12);
|
||||
expect(stoppedRetrying()).toBe(false);
|
||||
});
|
||||
|
||||
it('recovers the same server after registry absence without resetting dedupe or the byte budget', async () => {
|
||||
let connections = 0;
|
||||
let healthy = false;
|
||||
let expectAbsence = false;
|
||||
let observedAbsence = false;
|
||||
const keys: number[] = [];
|
||||
const readServers = serveSimServers.readServeSimServersAsync;
|
||||
const registry = jest
|
||||
.spyOn(serveSimServers, 'readServeSimServersAsync')
|
||||
.mockImplementation(async stateDir => {
|
||||
const servers = await readServers(stateDir);
|
||||
if (expectAbsence && servers.length === 0) {
|
||||
observedAbsence = true;
|
||||
}
|
||||
return servers;
|
||||
});
|
||||
server.on('request', (request, response) => {
|
||||
const url = new URL(request.url!, baseUrl);
|
||||
if (url.pathname === '/crashes') {
|
||||
connections += 1;
|
||||
if (connections > 1 && !healthy) {
|
||||
response.writeHead(503).end();
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
const record = {
|
||||
...summary,
|
||||
occurrenceTimes: healthy ? [{ key: 1 }, { key: 2 }, { key: 3 }] : [{ key: 1 }],
|
||||
};
|
||||
const frame = `data: ${JSON.stringify({ type: 'list', crashes: [record] })}\n\n`;
|
||||
if (healthy) {
|
||||
response.write(frame);
|
||||
} else {
|
||||
response.end(frame);
|
||||
}
|
||||
} else {
|
||||
const key = Number(url.searchParams.get('key'));
|
||||
keys.push(key);
|
||||
response.end(JSON.stringify(detail(key)));
|
||||
}
|
||||
});
|
||||
try {
|
||||
const expected = report(1) + report(2);
|
||||
await start(Buffer.byteLength(expected));
|
||||
await waitFor(stoppedRetrying);
|
||||
expect(connections).toBe(11);
|
||||
expectAbsence = true;
|
||||
await rm(path.join(directory, 'server-device-A.json'));
|
||||
await waitFor(() => observedAbsence);
|
||||
healthy = true;
|
||||
await writeFile(
|
||||
path.join(directory, 'server-device-A.json'),
|
||||
JSON.stringify({
|
||||
device: 'device-A',
|
||||
url: baseUrl,
|
||||
token: 'test-token',
|
||||
})
|
||||
);
|
||||
await waitFor(() => keys.includes(3));
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(connections).toBe(12);
|
||||
expect(keys).toEqual([1, 2, 3]);
|
||||
expect(collected.crashes).toHaveLength(2);
|
||||
expect(
|
||||
(await Promise.all(collected.crashes.map(file => readFile(file.filePath, 'utf8')))).join('')
|
||||
).toBe(expected);
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
} finally {
|
||||
registry.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes a stalled upload within its budget and lets another device upload', async () => {
|
||||
const firstFile = path.join(directory, 'A.ips');
|
||||
const secondFile = path.join(directory, 'B.ips');
|
||||
await writeFile(firstFile, report(1));
|
||||
const expected = Buffer.from(report(2));
|
||||
await writeFile(secondFile, expected);
|
||||
let firstClosed = false;
|
||||
let firstRequests = 0;
|
||||
let uploaded: Buffer | undefined;
|
||||
let sessions = 0;
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url === '/v2/device-run-session-worker/artifact-upload-sessions') {
|
||||
expect(request.method).toBe('POST');
|
||||
expect(request.headers[DEVICE_RUN_SESSION_TOKEN_HEADER]).toBe('worker-token');
|
||||
request.resume();
|
||||
request.on('end', () => {
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
uploadSession: {
|
||||
url: baseUrl + (sessions++ === 0 ? '/stalled' : '/upload'),
|
||||
headers: {},
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (request.url === '/stalled') {
|
||||
firstRequests += 1;
|
||||
response.on('close', () => {
|
||||
firstClosed = true;
|
||||
});
|
||||
request.resume();
|
||||
} else {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on('data', chunk => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
uploaded = Buffer.concat(chunks);
|
||||
response.end();
|
||||
});
|
||||
}
|
||||
});
|
||||
const context = {
|
||||
env: { EAS_DEVICE_RUN_SESSION_TOKEN: 'worker-token' },
|
||||
expoApiV2BaseUrl: baseUrl + '/v2/',
|
||||
} as unknown as CustomBuildContext;
|
||||
await uploadServeSimCrashesFileAsync(context, {
|
||||
deviceRunSessionId: 'session-id',
|
||||
crash: { udid: 'A', filePath: firstFile, size: Buffer.byteLength(report(1)), number: 1 },
|
||||
logger,
|
||||
signal: AbortSignal.timeout(50),
|
||||
});
|
||||
await waitFor(() => firstClosed);
|
||||
expect(firstRequests).toBe(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
'Could not upload crash report 1 for A; other artifacts will continue.'
|
||||
);
|
||||
await uploadServeSimCrashesFileAsync(context, {
|
||||
deviceRunSessionId: 'session-id',
|
||||
crash: { udid: 'B', filePath: secondFile, size: expected.length, number: 1 },
|
||||
logger,
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
});
|
||||
expect(sessions).toBe(2);
|
||||
expect(uploaded).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([null, ''])(
|
||||
'does not create an artifact when the native report is %s',
|
||||
async nativeReport => {
|
||||
let requested = false;
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
|
||||
);
|
||||
} else {
|
||||
requested = true;
|
||||
response.end(
|
||||
JSON.stringify({ ...detail(1), report: nativeReport, reportError: 'Report unavailable' })
|
||||
);
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => requested);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toEqual([]);
|
||||
expect(await readdir(collected.outputDirectory!)).toEqual([]);
|
||||
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('has no native report'));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
}
|
||||
);
|
||||
|
||||
it('does not duplicate a saved incident when a restarted serve-sim reuses occurrence keys', async () => {
|
||||
let requested = 0;
|
||||
server.on('request', (request, response) => {
|
||||
if (answerList(request, response)) {
|
||||
return;
|
||||
}
|
||||
// A restarted serve-sim numbers occurrences from 1 again; the capture time tells them apart.
|
||||
const restarted = request.headers.authorization === 'Bearer new-token';
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
const occurrence = restarted
|
||||
? { key: 1, capturedAtMs: 2_000, rawPath: '/DiagnosticReports/Fixture-2.ips' }
|
||||
: { key: 1, capturedAtMs: 1_000, rawPath: '/DiagnosticReports/Fixture-1.ips' };
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [occurrence] }] })}\n\n`
|
||||
);
|
||||
} else {
|
||||
requested += 1;
|
||||
response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await waitFor(() => requested === 1);
|
||||
await writeFile(
|
||||
path.join(directory, 'server-device-A.json'),
|
||||
JSON.stringify({ device: 'device-A', url: baseUrl, token: 'new-token' })
|
||||
);
|
||||
server.closeAllConnections();
|
||||
await waitFor(() => requested === 2);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toHaveLength(1);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('removes a partial file before retrying a failed write', async () => {
|
||||
const write = fs.writeFile;
|
||||
let attempted = 0;
|
||||
const writing = jest.spyOn(fs, 'writeFile').mockImplementation(async (file, data, options) => {
|
||||
if (String(file).endsWith('.ips') && attempted++ === 0) {
|
||||
await write(file, 'partial report', options);
|
||||
throw new Error('disk write failed');
|
||||
}
|
||||
await write(file, data, options);
|
||||
});
|
||||
server.on('request', (request, response) => {
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'list', crashes: [{ ...summary, occurrenceTimes: [{ key: 1 }] }] })}\n\n`
|
||||
);
|
||||
} else {
|
||||
response.end(JSON.stringify(detail(1)));
|
||||
}
|
||||
});
|
||||
try {
|
||||
await start();
|
||||
await waitFor(() => attempted >= 2);
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
expect(collected.crashes).toHaveLength(1);
|
||||
expect(await readdir(collected.outputDirectory!)).toEqual([
|
||||
path.basename(collected.crashes[0].filePath),
|
||||
]);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(1));
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
} finally {
|
||||
writing.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the report allowance and deduplicates reconnects after more missing reports than the allowance', async () => {
|
||||
const missingCount = 1_001;
|
||||
const requested: number[] = [];
|
||||
let connections = 0;
|
||||
let completed: (() => void) | undefined;
|
||||
const processed = new Promise<void>(resolve => {
|
||||
completed = resolve;
|
||||
});
|
||||
const occurrence = (key: number) => ({ ...summary, occurrenceTimes: [{ key }] });
|
||||
server.on('request', (request, response) => {
|
||||
if (answerList(request, response)) {
|
||||
return;
|
||||
}
|
||||
if (request.url!.startsWith('/crashes?')) {
|
||||
response.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
connections += 1;
|
||||
if (connections === 1) {
|
||||
for (let key = 1; key <= missingCount; key++) {
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(key) })}\n\n`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const retained = {
|
||||
...summary,
|
||||
occurrenceTimes: Array.from({ length: 5 }, (_, index) => ({
|
||||
key: missingCount - 4 + index,
|
||||
})),
|
||||
};
|
||||
response.write(`data: ${JSON.stringify({ type: 'list', crashes: [retained] })}\n\n`);
|
||||
}
|
||||
if (connections < 3) {
|
||||
response.end();
|
||||
} else {
|
||||
response.write(
|
||||
`data: ${JSON.stringify({ type: 'recurred', record: occurrence(missingCount + 1) })}\n\n`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const key = Number(new URL(request.url!, baseUrl).searchParams.get('key'));
|
||||
requested.push(key);
|
||||
response.end(
|
||||
JSON.stringify({ ...detail(key), report: key <= missingCount ? null : report(key) })
|
||||
);
|
||||
if (key === missingCount + 1) {
|
||||
completed?.();
|
||||
}
|
||||
}
|
||||
});
|
||||
await start();
|
||||
await processed;
|
||||
const collected = await ServeSimCrashesRecorder.finishAsync();
|
||||
try {
|
||||
expect(connections).toBe(3);
|
||||
expect(requested).toEqual(Array.from({ length: missingCount + 1 }, (_, index) => index + 1));
|
||||
expect(collected.crashes).toHaveLength(1);
|
||||
expect(await readFile(collected.crashes[0].filePath, 'utf8')).toBe(report(missingCount + 1));
|
||||
expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('reached its limit'));
|
||||
} finally {
|
||||
await rm(collected.outputDirectory!, { recursive: true, force: true });
|
||||
}
|
||||
}, 15_000);
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { mkdtemp, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { CustomBuildContext } from '../../../customBuildContext';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
import { uploadServeSimNetworkCaptureFileAsync } from '../serveSimNetworkCaptureArtifacts';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('../deviceRunSessionArtifacts');
|
||||
|
||||
const ctx = {} as CustomBuildContext;
|
||||
const logger = { info: jest.fn(), warn: jest.fn() } as unknown as bunyan;
|
||||
|
||||
async function harAsync(name: string): Promise<string> {
|
||||
const filePath = path.join(await mkdtemp(path.join(os.tmpdir(), 'network-capture-test-')), name);
|
||||
await writeFile(filePath, '{"log":{"entries":[{}]}}');
|
||||
return filePath;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockImplementation(async (_ctx, options) => {
|
||||
options.openStream().destroy();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[1, 'Network capture (ABCDEF12)'],
|
||||
[2, 'Network capture (ABCDEF12, part 2)'],
|
||||
])('uploads part %i as a network-capture artifact', async (part, name) => {
|
||||
const filePath = await harAsync('A.har');
|
||||
await uploadServeSimNetworkCaptureFileAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
udid: 'ABCDEF123456',
|
||||
filePath,
|
||||
size: 24,
|
||||
part,
|
||||
logger,
|
||||
});
|
||||
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledWith(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
artifactId: `network-capture-ABCDEF123456-${part}`,
|
||||
name,
|
||||
filename: 'network-capture.har',
|
||||
kind: 'network-capture',
|
||||
metadata: { __eas_type: 'network-capture', format: 'har', udid: 'ABCDEF123456', part },
|
||||
size: 24,
|
||||
openStream: expect.any(Function),
|
||||
signal: expect.any(AbortSignal),
|
||||
attempts: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('logs a failed upload without rejecting', async () => {
|
||||
jest.mocked(uploadDeviceRunSessionArtifactAsync).mockRejectedValueOnce(new Error('offline'));
|
||||
await expect(
|
||||
uploadServeSimNetworkCaptureFileAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
udid: 'A',
|
||||
filePath: await harAsync('A.har'),
|
||||
size: 24,
|
||||
part: 1,
|
||||
logger,
|
||||
})
|
||||
).resolves.toBeUndefined();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ message: 'offline' }) },
|
||||
'Could not upload the network capture for A.'
|
||||
);
|
||||
expect(Sentry.capture).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts 500 MiB and skips larger HARs', async () => {
|
||||
const limit = 500 * 1024 * 1024;
|
||||
const filePath = await harAsync('A.har');
|
||||
for (const size of [limit, limit + 1]) {
|
||||
await uploadServeSimNetworkCaptureFileAsync(ctx, {
|
||||
deviceRunSessionId: 'drs-id',
|
||||
udid: 'A',
|
||||
filePath,
|
||||
size,
|
||||
part: 1,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
expect(uploadDeviceRunSessionArtifactAsync).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Skipping network capture for A: exceeds the 500 MB upload limit.'
|
||||
);
|
||||
expect(Sentry.capture).not.toHaveBeenCalled();
|
||||
});
|
||||
+606
@@ -0,0 +1,606 @@
|
||||
import { bunyan } from '@expo/logger';
|
||||
import { type BuildStepEnv } from '@expo/steps';
|
||||
import { appendFileSync, existsSync, writeFileSync } from 'node:fs';
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
|
||||
import { spawnDetached } from '../remoteDeviceRunSession';
|
||||
import { ServeSimNetworkCaptureRecorder } from '../serveSimNetworkCaptureRecorder';
|
||||
|
||||
jest.mock('../../../sentry');
|
||||
jest.mock('../remoteDeviceRunSession', () => ({
|
||||
...jest.requireActual('../remoteDeviceRunSession'),
|
||||
spawnDetached: jest.fn(),
|
||||
}));
|
||||
|
||||
const logger = {
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
} as unknown as bunyan;
|
||||
const env = {} as BuildStepEnv;
|
||||
const stopFollower = jest.fn();
|
||||
let stateDir: string;
|
||||
|
||||
async function writeServerAsync(udid: string, state: Record<string, unknown>): Promise<void> {
|
||||
await writeFile(
|
||||
path.join(stateDir, `server-${udid}.json`),
|
||||
JSON.stringify({ device: udid, ...state })
|
||||
);
|
||||
}
|
||||
|
||||
/** Writes what `capture har` leaves: a HAR, and its entry log with one line per request. */
|
||||
function record(harPath: string, entries: number): void {
|
||||
writeFileSync(harPath, `${JSON.stringify({ log: { entries: Array(entries).fill({}) } })}\n`);
|
||||
writeFileSync(harPath.replace(/\.har$/, '.entries.ndjson'), '{}\n'.repeat(entries));
|
||||
}
|
||||
|
||||
type Request = { id: string; startedAt: number };
|
||||
|
||||
function entryFor({ id, startedAt }: Request) {
|
||||
return {
|
||||
startedDateTime: new Date(startedAt).toISOString(),
|
||||
request: { url: `https://example.com/${id}` },
|
||||
_captureId: id,
|
||||
_captureStartedAt: startedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** Writes a recording as serve-sim does: entries by completion time, the HAR in start order. */
|
||||
function recordRequests(harPath: string, requests: Request[]): void {
|
||||
const entries = requests.map(entryFor);
|
||||
const sorted = [...entries].sort((a, b) => a._captureStartedAt - b._captureStartedAt);
|
||||
writeFileSync(
|
||||
harPath,
|
||||
`${JSON.stringify({
|
||||
log: {
|
||||
version: '1.2',
|
||||
creator: { name: '@expo/serve-sim', version: '0.10.2' },
|
||||
entries: sorted,
|
||||
},
|
||||
})}\n`
|
||||
);
|
||||
writeFileSync(
|
||||
harPath.replace(/\.har$/, '.entries.ndjson'),
|
||||
entries.map(entry => `${JSON.stringify(entry)}\n`).join('')
|
||||
);
|
||||
}
|
||||
|
||||
async function readHarAsync(harPath: string): Promise<any> {
|
||||
return JSON.parse(await readFile(harPath, 'utf8'));
|
||||
}
|
||||
|
||||
function followerArgs(): string[][] {
|
||||
return jest.mocked(spawnDetached).mock.calls.map(([options]) => options.args);
|
||||
}
|
||||
|
||||
async function waitForFollowersAsync(count: number): Promise<void> {
|
||||
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < count; i++) {
|
||||
await delay(10);
|
||||
}
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(count);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
stopFollower.mockResolvedValue(undefined);
|
||||
jest.mocked(spawnDetached).mockImplementation(() => ({
|
||||
pid: 1234,
|
||||
getOutput: () => 'Stopped before recording began.',
|
||||
getExitError: () => undefined,
|
||||
stopAsync: stopFollower,
|
||||
}));
|
||||
stateDir = await mkdtemp(path.join(os.tmpdir(), 'serve-sim-network-capture-test-'));
|
||||
await mkdir(stateDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
await rm(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('starts one capture har follower per serve-sim that can serve capture routes', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
packageVersion: '0.5.0',
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
await delay(50);
|
||||
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(1);
|
||||
const [options] = jest.mocked(spawnDetached).mock.calls[0];
|
||||
expect(options.command).toBe('npx');
|
||||
expect(options.args).toEqual([
|
||||
'--yes',
|
||||
'@expo/[email protected]',
|
||||
'capture',
|
||||
'har',
|
||||
'-o',
|
||||
expect.stringMatching(/SIM-A-1\.har$/),
|
||||
'-d',
|
||||
'SIM-A',
|
||||
]);
|
||||
expect(options.stopGracePeriodMs).toBe(60_000);
|
||||
});
|
||||
|
||||
it('does not pass the ngrok token to the follower', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env: { NGROK_AUTHTOKEN: 'ngrok-secret', PATH: '/usr/bin' } as BuildStepEnv,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
|
||||
expect(jest.mocked(spawnDetached).mock.calls[0][0].env).toEqual({ PATH: '/usr/bin' });
|
||||
});
|
||||
|
||||
it('starts a new follower only when serve-sim restarts for the device', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
packageVersion: '0.5.0',
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(1);
|
||||
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
|
||||
await waitForFollowersAsync(2);
|
||||
expect(jest.mocked(spawnDetached).mock.calls[1][0].command).toBe('npx');
|
||||
expect(followerArgs()[1]).toEqual([
|
||||
'--yes',
|
||||
'@expo/[email protected]',
|
||||
'capture',
|
||||
'har',
|
||||
'-o',
|
||||
expect.stringMatching(/SIM-A-2\.har$/),
|
||||
'-d',
|
||||
'SIM-A',
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops every follower and returns only the HARs that hold requests', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
|
||||
await waitForFollowersAsync(2);
|
||||
const recorded = followerArgs().find(args => args.includes('SIM-A'))!;
|
||||
record(recorded[recorded.indexOf('-o') + 1], 1);
|
||||
// serve-sim writes an empty HAR when recording begins, before any request.
|
||||
const empty = followerArgs().find(args => args.includes('SIM-B'))!;
|
||||
record(empty[empty.indexOf('-o') + 1], 0);
|
||||
|
||||
const { outputDirectory, captures } = await ServeSimNetworkCaptureRecorder.finishAsync({
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(stopFollower).toHaveBeenCalledTimes(2);
|
||||
expect(captures).toEqual([
|
||||
{ udid: 'SIM-A', filePath: recorded[recorded.indexOf('-o') + 1], size: 25 },
|
||||
]);
|
||||
expect(outputDirectory).toBe(path.dirname(captures[0].filePath));
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
{ output: 'Stopped before recording began.' },
|
||||
'No network capture was recorded for SIM-B.'
|
||||
);
|
||||
});
|
||||
|
||||
it('stops followers in parallel', async () => {
|
||||
let stopping = 0;
|
||||
let mostAtOnce = 0;
|
||||
stopFollower.mockImplementation(async () => {
|
||||
stopping += 1;
|
||||
mostAtOnce = Math.max(mostAtOnce, stopping);
|
||||
await delay(20);
|
||||
stopping -= 1;
|
||||
});
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await writeServerAsync('SIM-B', { url: 'http://127.0.0.1:4200', token: 'token-b' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
|
||||
await waitForFollowersAsync(2);
|
||||
await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(mostAtOnce).toBe(2);
|
||||
});
|
||||
|
||||
it('keeps collecting when a follower cannot be stopped', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
|
||||
await waitForFollowersAsync(1);
|
||||
stopFollower.mockRejectedValueOnce(new Error('EPERM'));
|
||||
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
|
||||
outputDirectory: expect.any(String),
|
||||
captures: [],
|
||||
});
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ message: 'EPERM' }) },
|
||||
'Could not stop the network capture follower for SIM-A.'
|
||||
);
|
||||
});
|
||||
|
||||
it('returns nothing when the recorder never started', async () => {
|
||||
await expect(ServeSimNetworkCaptureRecorder.finishAsync({ logger })).resolves.toEqual({
|
||||
outputDirectory: null,
|
||||
captures: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe('restarting followers', () => {
|
||||
const exits: (Error | undefined)[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
exits.length = 0;
|
||||
jest.mocked(spawnDetached).mockImplementation(() => {
|
||||
const index = exits.push(undefined) - 1;
|
||||
return {
|
||||
pid: 1234,
|
||||
getOutput: () => 'Network capture is not enabled on this device.',
|
||||
getExitError: () => exits[index],
|
||||
stopAsync: stopFollower,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
function outPath(call: number): string {
|
||||
const args = followerArgs()[call];
|
||||
return args[args.indexOf('-o') + 1];
|
||||
}
|
||||
|
||||
it('starts another follower when one exits before capture was on, and drops the empty one', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
idleRestartIntervalMs: 30,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
expect(outPath(1)).toMatch(/SIM-A-2\.har$/);
|
||||
record(outPath(1), 1);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures).toEqual([{ udid: 'SIM-A', filePath: outPath(1), size: 25 }]);
|
||||
expect(stopFollower).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps a recording when its stream drops and records the rest in a new part', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
restartIntervalMs: 30,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
record(outPath(0), 2);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
record(outPath(1), 1);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures).toEqual([
|
||||
{ udid: 'SIM-A', filePath: outPath(0), size: 28 },
|
||||
{ udid: 'SIM-A', filePath: outPath(1), size: 25 },
|
||||
]);
|
||||
});
|
||||
|
||||
describe('when a new follower replays the requests serve-sim holds', () => {
|
||||
const r1 = { id: 'r1', startedAt: 1_000 };
|
||||
const r2 = { id: 'r2', startedAt: 2_000 };
|
||||
|
||||
async function startAsync(): Promise<void> {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
restartIntervalMs: 30,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
}
|
||||
|
||||
it('drops a part that holds only replayed requests', async () => {
|
||||
await startAsync();
|
||||
recordRequests(outPath(0), [r2, r1]);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
recordRequests(outPath(1), [r2, r1]);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
|
||||
});
|
||||
|
||||
it('keeps only the new requests in a later part, in start order', async () => {
|
||||
await startAsync();
|
||||
recordRequests(outPath(0), [r1]);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
// A request from a later capture session reuses the id r1 with another start time.
|
||||
const r1Again = { id: 'r1', startedAt: 4_000 };
|
||||
recordRequests(outPath(1), [r1Again, r1, r2]);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
|
||||
const har = await readHarAsync(outPath(1));
|
||||
expect(har.log.creator).toEqual({ name: '@expo/serve-sim', version: '0.10.2' });
|
||||
expect(har.log.entries.map((entry: any) => entry._captureStartedAt)).toEqual([2_000, 4_000]);
|
||||
expect(captures[1].size).toBe((await readFile(outPath(1))).length);
|
||||
});
|
||||
|
||||
it('keeps the requests a killed follower logged before its HAR caught up', async () => {
|
||||
const r3 = { id: 'r3', startedAt: 3_000 };
|
||||
await startAsync();
|
||||
// serve-sim writes the entry log before it rebuilds the HAR, so a killed follower's HAR can
|
||||
// lack r2 although its entry log has it.
|
||||
recordRequests(outPath(0), [r1]);
|
||||
appendFileSync(
|
||||
outPath(0).replace(/\.har$/, '.entries.ndjson'),
|
||||
`${JSON.stringify(entryFor(r2))}\n`
|
||||
);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
recordRequests(outPath(1), [r1, r2, r3]);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0), outPath(1)]);
|
||||
const ids = async (harPath: string): Promise<string[]> =>
|
||||
(await readHarAsync(harPath)).log.entries.map((entry: any) => entry._captureId);
|
||||
expect(await ids(outPath(0))).toEqual(['r1', 'r2']);
|
||||
expect(await ids(outPath(1))).toEqual(['r3']);
|
||||
});
|
||||
|
||||
it('leaves out a line a killed follower cut off', async () => {
|
||||
await startAsync();
|
||||
recordRequests(outPath(0), [r1]);
|
||||
appendFileSync(outPath(0).replace(/\.har$/, '.entries.ndjson'), '{"startedDateTime":"20');
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
|
||||
const har = await readHarAsync(outPath(0));
|
||||
expect(har.log.entries.map((entry: any) => entry._captureId)).toEqual(['r1']);
|
||||
});
|
||||
|
||||
it('removes the files of a part that holds only replayed requests', async () => {
|
||||
await startAsync();
|
||||
recordRequests(outPath(0), [r1]);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(2);
|
||||
recordRequests(outPath(1), [r1]);
|
||||
const replayedFiles = [
|
||||
outPath(1),
|
||||
outPath(1).replace(/\.har$/, '.entries.ndjson'),
|
||||
outPath(1).replace(/\.har$/, '.network-capture.json'),
|
||||
`${outPath(1)}.0f7c2a4e-9d1b-4c3a-8e5f-6a7b8c9d0e1f.seed.tmp`,
|
||||
];
|
||||
for (const file of replayedFiles.slice(2)) {
|
||||
writeFileSync(file, '{}');
|
||||
}
|
||||
exits[1] = new Error('Process exited with code 1.');
|
||||
await waitForFollowersAsync(3);
|
||||
|
||||
expect(replayedFiles.filter(file => existsSync(file))).toEqual([]);
|
||||
expect(existsSync(outPath(0))).toBe(true);
|
||||
});
|
||||
|
||||
it('does not use a recording slot for followers that recorded no new request', async () => {
|
||||
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
|
||||
recordRequests(args[args.indexOf('-o') + 1], [r1]);
|
||||
return {
|
||||
pid: 1234,
|
||||
getOutput: () => '',
|
||||
getExitError: () => new Error('Process exited with code 1.'),
|
||||
stopAsync: stopFollower,
|
||||
};
|
||||
});
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 1,
|
||||
restartIntervalMs: 0,
|
||||
});
|
||||
for (let i = 0; i < 300 && jest.mocked(spawnDetached).mock.calls.length < 25; i++) {
|
||||
await delay(10);
|
||||
}
|
||||
expect(jest.mocked(spawnDetached).mock.calls.length).toBeGreaterThanOrEqual(25);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures.map(capture => capture.filePath)).toEqual([outPath(0)]);
|
||||
expect(logger.warn).not.toHaveBeenCalledWith(
|
||||
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('waits longer to replace a follower that recorded nothing than one that recorded requests', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
restartIntervalMs: 30,
|
||||
idleRestartIntervalMs: 60_000,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await delay(100);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(1);
|
||||
|
||||
record(outPath(0), 1);
|
||||
await waitForFollowersAsync(2);
|
||||
});
|
||||
|
||||
it('drops an empty follower from an earlier serve-sim when serve-sim restarts', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({ logger, env, stateDir, pollIntervalMs: 10 });
|
||||
await waitForFollowersAsync(1);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-restarted' });
|
||||
await waitForFollowersAsync(2);
|
||||
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures).toEqual([]);
|
||||
// Only the new follower is left to stop, and the device is reported once.
|
||||
expect(stopFollower).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
jest
|
||||
.mocked(logger.info)
|
||||
.mock.calls.filter(
|
||||
([, message]) => message === 'No network capture was recorded for SIM-A.'
|
||||
)
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('waits 30 s by default before replacing a follower that recorded nothing', async () => {
|
||||
const startedAt = Date.now();
|
||||
const now = jest.spyOn(Date, 'now');
|
||||
try {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
restartIntervalMs: 0,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
exits[0] = new Error('Process exited with code 1.');
|
||||
now.mockReturnValue(startedAt + 29_000);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(1);
|
||||
now.mockReturnValue(startedAt + 31_000);
|
||||
await waitForFollowersAsync(2);
|
||||
} finally {
|
||||
now.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('stops starting followers once 20 HARs hold requests', async () => {
|
||||
jest.mocked(spawnDetached).mockImplementation(({ args }) => {
|
||||
record(args[args.indexOf('-o') + 1], 1);
|
||||
return {
|
||||
pid: 1234,
|
||||
getOutput: () => '',
|
||||
getExitError: () => new Error('Process exited with code 1.'),
|
||||
stopAsync: stopFollower,
|
||||
};
|
||||
});
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 1,
|
||||
restartIntervalMs: 0,
|
||||
});
|
||||
await waitForFollowersAsync(20);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(20);
|
||||
const { captures } = await ServeSimNetworkCaptureRecorder.finishAsync({ logger });
|
||||
expect(captures).toHaveLength(20);
|
||||
expect(logger.warn).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Network capture reached its limit of 20 recordings; recorded captures will be retained.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps polling after a follower fails to start, and retries on the next poll', async () => {
|
||||
jest.mocked(spawnDetached).mockImplementationOnce(() => {
|
||||
throw new Error('spawn EAGAIN');
|
||||
});
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 10,
|
||||
restartIntervalMs: 60_000,
|
||||
idleRestartIntervalMs: 60_000,
|
||||
});
|
||||
await waitForFollowersAsync(2);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
{ err: expect.objectContaining({ message: 'spawn EAGAIN' }) },
|
||||
'Could not start the network capture follower for SIM-A; retrying.'
|
||||
);
|
||||
expect(followerArgs()[1]).toContainEqual(expect.stringMatching(/SIM-A-2\.har$/));
|
||||
});
|
||||
|
||||
it('bounds followers that record nothing, warns once, and retries a new server identity', async () => {
|
||||
jest.mocked(spawnDetached).mockImplementation(() => ({
|
||||
pid: 1234,
|
||||
getOutput: () => 'npm error: the requested serve-sim package was not found',
|
||||
getExitError: () => new Error('Process exited with code 1.'),
|
||||
stopAsync: stopFollower,
|
||||
}));
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 1,
|
||||
idleRestartIntervalMs: 0,
|
||||
});
|
||||
// Runs that recorded nothing do not use up the 20 HARs that may hold requests.
|
||||
await waitForFollowersAsync(120);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(120);
|
||||
const warnings = jest
|
||||
.mocked(logger.warn)
|
||||
.mock.calls.filter(([, message]) =>
|
||||
String(message).startsWith('Stopped retrying network capture')
|
||||
);
|
||||
expect(warnings).toEqual([
|
||||
[
|
||||
{ output: 'npm error: the requested serve-sim package was not found' },
|
||||
'Stopped retrying network capture for SIM-A after 120 attempts; recorded captures will be retained.',
|
||||
],
|
||||
]);
|
||||
|
||||
jest.mocked(spawnDetached).mockImplementation(() => ({
|
||||
pid: 1234,
|
||||
getOutput: () => '',
|
||||
getExitError: () => undefined,
|
||||
stopAsync: stopFollower,
|
||||
}));
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'new-token' });
|
||||
await waitForFollowersAsync(121);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(121);
|
||||
expect(followerArgs()[120]).toContainEqual(expect.stringMatching(/SIM-A-121\.har$/));
|
||||
});
|
||||
|
||||
it('keeps a running empty follower waiting without spending more attempts', async () => {
|
||||
await writeServerAsync('SIM-A', { url: 'http://127.0.0.1:4100', token: 'token-a' });
|
||||
await ServeSimNetworkCaptureRecorder.startAsync({
|
||||
logger,
|
||||
env,
|
||||
stateDir,
|
||||
pollIntervalMs: 1,
|
||||
restartIntervalMs: 0,
|
||||
idleRestartIntervalMs: 0,
|
||||
});
|
||||
await waitForFollowersAsync(1);
|
||||
await delay(50);
|
||||
expect(spawnDetached).toHaveBeenCalledTimes(1);
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { runServeSimActionAsync, runServeSimActionWithResultAsync } from '../serveSimActions';
|
||||
import { createServeSimPreviewCapture } from '../serveSimPreviewCapture';
|
||||
|
||||
jest.mock('../serveSimActions');
|
||||
|
||||
const signal = new AbortController().signal;
|
||||
const tmpdir = path.join(os.tmpdir(), 'host-tmp');
|
||||
const staging = path.join(tmpdir, 'serve-sim-screenshots');
|
||||
const destination = path.join(os.tmpdir(), 'screen.png');
|
||||
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0xff, 0x00]);
|
||||
const options = { port: 1234, token: 'host-token', device: 'selected-udid', tmpdir };
|
||||
|
||||
beforeEach(async () => {
|
||||
await mkdir(staging, { recursive: true });
|
||||
jest.mocked(runServeSimActionAsync).mockReset();
|
||||
});
|
||||
|
||||
it('captures the selected active display and removes only its own staging', async () => {
|
||||
await writeFile(path.join(staging, 'unrelated.png'), 'keep');
|
||||
jest.mocked(runServeSimActionAsync).mockImplementation(async request => {
|
||||
expect(request).toEqual({
|
||||
port: 1234,
|
||||
token: 'host-token',
|
||||
action: 'screenshot.capture',
|
||||
params: {
|
||||
udid: 'selected-udid',
|
||||
fileName: expect.stringMatching(/^serve-sim-screenshot-preview-.*\.png$/),
|
||||
automation: true,
|
||||
},
|
||||
timeoutMs: 30_000,
|
||||
signal,
|
||||
drainAfterDispatch: true,
|
||||
});
|
||||
await writeFile(path.join(staging, request.params.fileName as string), png);
|
||||
return;
|
||||
});
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
await capture.captureAsync(destination, signal);
|
||||
expect(await readFile(destination)).toEqual(png);
|
||||
expect(await readdir(staging)).toEqual(['unrelated.png']);
|
||||
});
|
||||
|
||||
it('drains an already sent action before honoring abort and deleting its output', async () => {
|
||||
const controller = new AbortController();
|
||||
let complete!: () => void;
|
||||
const pending = new Promise<void>(resolve => {
|
||||
complete = resolve;
|
||||
});
|
||||
let staged!: string;
|
||||
jest.mocked(runServeSimActionAsync).mockImplementation(async request => {
|
||||
staged = path.join(staging, request.params.fileName as string);
|
||||
await pending;
|
||||
await writeFile(staged, png);
|
||||
return;
|
||||
});
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
let settled = false;
|
||||
const capturing = capture.captureAsync(destination, controller.signal);
|
||||
void capturing.then(
|
||||
() => {
|
||||
settled = true;
|
||||
},
|
||||
() => {
|
||||
settled = true;
|
||||
}
|
||||
);
|
||||
controller.abort(new Error('session stopped'));
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
complete();
|
||||
await expect(capturing).rejects.toThrow('session stopped');
|
||||
expect(await readdir(staging)).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(['timed out', 'connection closed'])(
|
||||
'keeps a possibly writable file after %s until the host stops',
|
||||
async message => {
|
||||
let staged!: string;
|
||||
jest.mocked(runServeSimActionAsync).mockImplementation(async request => {
|
||||
staged = path.join(staging, request.params.fileName as string);
|
||||
await writeFile(staged, 'reservation');
|
||||
throw new Error(message);
|
||||
});
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
await expect(capture.captureAsync(destination, signal)).rejects.toThrow(message);
|
||||
expect(await readFile(staged, 'utf8')).toBe('reservation');
|
||||
// The server may still write after the client's deadline or disconnect.
|
||||
await writeFile(staged, png);
|
||||
await capture.cleanupAfterHostStoppedAsync();
|
||||
expect(await readdir(staging)).toEqual([]);
|
||||
}
|
||||
);
|
||||
|
||||
it('attempts every owned cleanup when one file cannot be removed', async () => {
|
||||
let blocked!: string;
|
||||
let count = 0;
|
||||
jest.mocked(runServeSimActionAsync).mockImplementation(async request => {
|
||||
const staged = path.join(staging, request.params.fileName as string);
|
||||
if (count++ === 0) {
|
||||
blocked = staged;
|
||||
await mkdir(staged);
|
||||
} else {
|
||||
await writeFile(staged, png);
|
||||
}
|
||||
throw new Error('capture disconnected');
|
||||
});
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
await expect(capture.captureAsync(destination, signal)).rejects.toThrow('disconnected');
|
||||
await expect(capture.captureAsync(destination, signal)).rejects.toThrow('disconnected');
|
||||
await expect(capture.cleanupAfterHostStoppedAsync()).rejects.toThrow(
|
||||
'Could not remove preview captures'
|
||||
);
|
||||
expect(await readdir(staging)).toEqual([path.basename(blocked)]);
|
||||
});
|
||||
|
||||
it('does not send a capture when already aborted', async () => {
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
await expect(
|
||||
capture.captureAsync(destination, AbortSignal.abort(new Error('stopped')))
|
||||
).rejects.toThrow('stopped');
|
||||
expect(runServeSimActionAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
{ 'screenshot.capture': { properties: { automation: { type: 'boolean', default: false } } } },
|
||||
true,
|
||||
],
|
||||
[{ 'screenshot.capture': { properties: {} } }, false],
|
||||
[{ 'screenshot.capture': { properties: { automation: { type: 'string' } } } }, false],
|
||||
[{}, false],
|
||||
[null, false],
|
||||
])(
|
||||
'checks the catalog automation field before enabling captures (%j)',
|
||||
async (catalog, supported) => {
|
||||
jest.mocked(runServeSimActionWithResultAsync).mockResolvedValueOnce(JSON.stringify(catalog));
|
||||
const capture = createServeSimPreviewCapture(options);
|
||||
await expect(capture.isSupportedAsync(signal)).resolves.toBe(supported);
|
||||
expect(runServeSimActionWithResultAsync).toHaveBeenCalledWith({
|
||||
port: options.port,
|
||||
token: options.token,
|
||||
action: 'actions.describe',
|
||||
params: {},
|
||||
timeoutMs: 30_000,
|
||||
signal,
|
||||
});
|
||||
expect(runServeSimActionAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { SystemError, formatBytes } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { mkdtemp, rm, stat } from 'node:fs/promises';
|
||||
@@ -11,8 +11,8 @@ import { z } from 'zod';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from './deviceRunSessionScreenshotMetadata';
|
||||
|
||||
const AGENT_DEVICE_ARTIFACT_UPLOAD_POLL_INTERVAL_MS = 5_000;
|
||||
const AGENT_DEVICE_ARTIFACT_CLEANUP_TIMEOUT_MS = 30_000;
|
||||
@@ -216,6 +216,17 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
signal,
|
||||
});
|
||||
const { size } = await stat(temporaryArtifactPath);
|
||||
const display = artifact.displayRotation
|
||||
? { displayRotation: artifact.displayRotation }
|
||||
: undefined;
|
||||
const metadata =
|
||||
artifact.artifactType === 'screenshot'
|
||||
? await createScreenshotMetadataAsync(temporaryArtifactPath, {
|
||||
source: 'agent-device',
|
||||
...display,
|
||||
logger,
|
||||
})
|
||||
: display;
|
||||
logger.info(`Uploading artifact ${artifact.filename} (${formatBytes(size)}).`);
|
||||
await uploadDeviceRunSessionArtifactAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
@@ -223,9 +234,7 @@ export async function uploadAgentDeviceArtifactAsync(
|
||||
name: `${artifact.filename} (${artifact.id})`,
|
||||
filename: artifact.filename,
|
||||
kind: artifact.artifactType ?? undefined,
|
||||
...(artifact.displayRotation
|
||||
? { metadata: { displayRotation: artifact.displayRotation } }
|
||||
: {}),
|
||||
...(metadata ? { metadata } : {}),
|
||||
size,
|
||||
openStream: () => createReadStream(temporaryArtifactPath),
|
||||
...(signal ? { signal } : {}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { formatBytes } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { type BuildStepGlobalContext } from '@expo/steps';
|
||||
import path from 'node:path';
|
||||
@@ -10,7 +11,6 @@ import {
|
||||
} from '../../utils/androidEmulatorLogCapture';
|
||||
import { AndroidEmulatorLogFiles } from '../../utils/androidEmulatorLogFiles';
|
||||
import { type AndroidEmulatorLogSource } from '../../utils/androidEmulatorLogSources';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { uploadDeviceRunSessionFileAsync } from './uploadDeviceRunSessionFile';
|
||||
|
||||
const UPLOAD_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { SystemError, formatBytes } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import { mkdtemp, rm, stat } from 'node:fs/promises';
|
||||
@@ -11,8 +11,8 @@ import { z } from 'zod';
|
||||
|
||||
import { CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from './deviceRunSessionScreenshotMetadata';
|
||||
|
||||
const ARGENT_ARTIFACT_UPLOAD_POLL_INTERVAL_MS = 5_000;
|
||||
const ARGENT_ARTIFACT_UPLOAD_CLEANUP_TIMEOUT_MS = 30_000;
|
||||
@@ -208,13 +208,19 @@ export async function uploadArgentArtifactAsync(
|
||||
destinationPath: temporaryArtifactPath,
|
||||
});
|
||||
const { size } = await stat(temporaryArtifactPath);
|
||||
const kind = getArgentArtifactKind(artifact);
|
||||
const metadata =
|
||||
(kind === 'screenshot' || kind === 'screenshot-diff') && !artifact.isDirectory
|
||||
? await createScreenshotMetadataAsync(temporaryArtifactPath, { source: 'argent', logger })
|
||||
: undefined;
|
||||
logger.info(`Uploading artifact ${filename} (${formatBytes(size)}).`);
|
||||
await uploadDeviceRunSessionArtifactAsync(ctx, {
|
||||
deviceRunSessionId,
|
||||
artifactId: artifact.id,
|
||||
name: `${filename} (${artifact.id})`,
|
||||
filename,
|
||||
kind: getArgentArtifactKind(artifact),
|
||||
kind,
|
||||
...(metadata ? { metadata } : {}),
|
||||
size,
|
||||
openStream: () => createReadStream(temporaryArtifactPath),
|
||||
});
|
||||
|
||||
@@ -11,6 +11,11 @@ import path from 'node:path';
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { uploadContentWithSignedUrl } from '../../storage/uploadWithSignedUrl';
|
||||
import { killProcessGroup } from '../../utils/processes';
|
||||
import {
|
||||
type ImageSize,
|
||||
type ScreenshotMetadata,
|
||||
readImageSize,
|
||||
} from './deviceRunSessionScreenshotMetadata';
|
||||
import { requireDeviceRunSessionWorkerApi } from './deviceRunSessionWorkerApi';
|
||||
|
||||
const PREVIEW_INTERVAL_MS = 60_000;
|
||||
@@ -20,7 +25,6 @@ const MAX_PREVIEW_SIZE_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export function startDeviceRunSessionPreview({
|
||||
ctx,
|
||||
deviceRunSessionId,
|
||||
captureAsync,
|
||||
logger,
|
||||
}: {
|
||||
@@ -32,6 +36,7 @@ export function startDeviceRunSessionPreview({
|
||||
const controller = new AbortController();
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
let uploadSession: { url: string; headers: Record<string, string> } | undefined;
|
||||
let storedSize: ImageSize | undefined;
|
||||
let pending: Promise<void>;
|
||||
|
||||
const uploadAsync = async (): Promise<void> => {
|
||||
@@ -44,8 +49,10 @@ export function startDeviceRunSessionPreview({
|
||||
if (image.length === 0 || image.length > MAX_PREVIEW_SIZE_BYTES) {
|
||||
throw new Error('Session preview is empty or exceeds the 5 MiB upload limit.');
|
||||
}
|
||||
const size = readImageSize(image);
|
||||
if (!uploadSession) {
|
||||
uploadSession = await createPreviewUploadSessionAsync(ctx, deviceRunSessionId, signal);
|
||||
uploadSession = await createPreviewUploadSessionAsync(ctx, size, signal);
|
||||
storedSize = size;
|
||||
}
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
@@ -54,6 +61,16 @@ export function startDeviceRunSessionPreview({
|
||||
{ signedUrl: uploadSession, content: image },
|
||||
{ signal, retries: 0, stallTimeoutMs: 30_000 }
|
||||
);
|
||||
if (
|
||||
controller.signal.aborted ||
|
||||
!size ||
|
||||
(size.width === storedSize?.width && size.height === storedSize.height)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
storedSize = undefined;
|
||||
uploadSession = await createPreviewUploadSessionAsync(ctx, size, signal);
|
||||
storedSize = size;
|
||||
} catch (err) {
|
||||
if (!controller.signal.aborted) {
|
||||
logger.warn({ err }, 'Could not refresh the session preview; retrying in 60 seconds.');
|
||||
@@ -80,10 +97,16 @@ export function startDeviceRunSessionPreview({
|
||||
|
||||
async function createPreviewUploadSessionAsync(
|
||||
ctx: CustomBuildContext,
|
||||
deviceRunSessionId: string,
|
||||
size: ImageSize | undefined,
|
||||
signal: AbortSignal
|
||||
): Promise<{ url: string; headers: Record<string, string> }> {
|
||||
return await requireDeviceRunSessionWorkerApi(ctx).createPreviewUploadSessionAsync({ signal });
|
||||
const metadata: ScreenshotMetadata | undefined = size
|
||||
? { source: 'preview', ...size }
|
||||
: undefined;
|
||||
return await requireDeviceRunSessionWorkerApi(ctx).createPreviewUploadSessionAsync(
|
||||
{ metadata },
|
||||
{ signal }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,18 +164,25 @@ export async function captureDeviceRunSessionPreviewAsync({
|
||||
device,
|
||||
env,
|
||||
signal,
|
||||
captureIosScreenshotAsync,
|
||||
}: {
|
||||
runtimePlatform: BuildRuntimePlatform;
|
||||
device: string;
|
||||
env: BuildStepEnv;
|
||||
signal: AbortSignal;
|
||||
captureIosScreenshotAsync?: (file: string, signal: AbortSignal) => Promise<void>;
|
||||
}): Promise<Buffer> {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), 'session-preview-'));
|
||||
try {
|
||||
const options = { env, signal, timeout: 30_000, stdio: 'pipe' as const };
|
||||
const preview = path.join(directory, 'preview.webp');
|
||||
if (runtimePlatform === BuildRuntimePlatform.DARWIN) {
|
||||
await captureIosPreviewAsync({ device, directory, preview, options });
|
||||
if (!captureIosScreenshotAsync) {
|
||||
throw new Error(
|
||||
'Cannot capture the iOS session preview: serve-sim screenshot capture is not configured.'
|
||||
);
|
||||
}
|
||||
await captureIosPreviewAsync({ captureIosScreenshotAsync, directory, preview, options });
|
||||
} else {
|
||||
await captureAndroidPreviewAsync({ device, directory, preview, options });
|
||||
}
|
||||
@@ -170,19 +200,20 @@ type CaptureOptions = {
|
||||
};
|
||||
|
||||
async function captureIosPreviewAsync({
|
||||
device,
|
||||
captureIosScreenshotAsync,
|
||||
directory,
|
||||
preview,
|
||||
options,
|
||||
}: {
|
||||
device: string;
|
||||
captureIosScreenshotAsync: (file: string, signal: AbortSignal) => Promise<void>;
|
||||
directory: string;
|
||||
preview: string;
|
||||
options: CaptureOptions;
|
||||
}): Promise<void> {
|
||||
const screenshot = path.join(directory, 'screen.png');
|
||||
const resized = path.join(directory, 'resized.png');
|
||||
await spawn('xcrun', ['simctl', 'io', device, 'screenshot', screenshot], options);
|
||||
await captureIosScreenshotAsync(screenshot, options.signal);
|
||||
options.signal.throwIfAborted();
|
||||
await spawn('sips', ['-Z', String(PREVIEW_MAX_DIMENSION), screenshot, '--out', resized], options);
|
||||
await spawn('cwebp', ['-quiet', '-q', String(PREVIEW_QUALITY), resized, '-o', preview], options);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SystemError } from '@expo/eas-build-job';
|
||||
import { SystemError, formatBytes } from '@expo/eas-build-job';
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import type { BuildStepEnv } from '@expo/steps';
|
||||
import spawn from '@expo/turtle-spawn';
|
||||
@@ -11,7 +11,6 @@ import { z } from 'zod';
|
||||
|
||||
import { type CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
|
||||
const RecordingsSchema = z.array(
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
const IMAGE_HEADER_MAX_BYTES = 64 * 1024;
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
export type ScreenshotSource = 'manual' | 'agent-device' | 'argent' | 'preview';
|
||||
|
||||
export type ScreenshotMetadata = {
|
||||
source: ScreenshotSource;
|
||||
width?: number;
|
||||
height?: number;
|
||||
displayRotation?: string;
|
||||
};
|
||||
|
||||
export type ImageSize = { width: number; height: number };
|
||||
|
||||
export async function createScreenshotMetadataAsync(
|
||||
file: string,
|
||||
{ logger, ...metadata }: Omit<ScreenshotMetadata, 'width' | 'height'> & { logger: bunyan }
|
||||
): Promise<ScreenshotMetadata> {
|
||||
try {
|
||||
const size = await readImageFileSizeAsync(file);
|
||||
if (size) {
|
||||
return { ...metadata, ...size };
|
||||
}
|
||||
logger.warn(
|
||||
{ file },
|
||||
'Uploading the screenshot without its width and height because it does not start with a complete PNG, WebP or JPEG header.'
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, file },
|
||||
'Uploading the screenshot without its width and height because its header could not be read.'
|
||||
);
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
async function readImageFileSizeAsync(file: string): Promise<ImageSize | undefined> {
|
||||
const handle = await open(file, 'r');
|
||||
try {
|
||||
const { buffer, bytesRead } = await handle.read(
|
||||
Buffer.alloc(IMAGE_HEADER_MAX_BYTES),
|
||||
0,
|
||||
IMAGE_HEADER_MAX_BYTES,
|
||||
0
|
||||
);
|
||||
return readImageSize(buffer.subarray(0, bytesRead));
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function readImageSize(header: Buffer): ImageSize | undefined {
|
||||
const size = readPngSize(header) ?? readWebpSize(header) ?? readJpegSize(header);
|
||||
return size && size.width > 0 && size.height > 0 ? size : undefined;
|
||||
}
|
||||
|
||||
function readPngSize(header: Buffer): ImageSize | undefined {
|
||||
if (
|
||||
header.length < 24 ||
|
||||
!header.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
||||
header.toString('latin1', 12, 16) !== 'IHDR'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) };
|
||||
}
|
||||
|
||||
function readWebpSize(header: Buffer): ImageSize | undefined {
|
||||
if (
|
||||
header.length < 16 ||
|
||||
header.toString('latin1', 0, 4) !== 'RIFF' ||
|
||||
header.toString('latin1', 8, 12) !== 'WEBP'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
switch (header.toString('latin1', 12, 16)) {
|
||||
case 'VP8 ':
|
||||
if (header.length < 30 || header.readUIntBE(23, 3) !== 0x9d012a) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
width: header.readUInt16LE(26) & 0x3fff,
|
||||
height: header.readUInt16LE(28) & 0x3fff,
|
||||
};
|
||||
case 'VP8L': {
|
||||
if (header.length < 25 || header[20] !== 0x2f) {
|
||||
return undefined;
|
||||
}
|
||||
const bits = header.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
case 'VP8X':
|
||||
if (header.length < 30) {
|
||||
return undefined;
|
||||
}
|
||||
return { width: header.readUIntLE(24, 3) + 1, height: header.readUIntLE(27, 3) + 1 };
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function readJpegSize(header: Buffer): ImageSize | undefined {
|
||||
if (header.length < 4 || header[0] !== 0xff || header[1] !== 0xd8) {
|
||||
return undefined;
|
||||
}
|
||||
let offset = 2;
|
||||
while (offset + 4 <= header.length) {
|
||||
if (header[offset] !== 0xff) {
|
||||
return undefined;
|
||||
}
|
||||
const marker = header[offset + 1];
|
||||
if (marker === 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
if (marker === 0xd9 || marker === 0xda) {
|
||||
return undefined;
|
||||
}
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
|
||||
offset += 2;
|
||||
continue;
|
||||
}
|
||||
const segmentEnd = offset + 2 + header.readUInt16BE(offset + 2);
|
||||
if (segmentEnd < offset + 4) {
|
||||
return undefined;
|
||||
}
|
||||
if (isJpegStartOfFrame(marker)) {
|
||||
return segmentEnd <= header.length
|
||||
? readJpegFrameSize(header.subarray(offset + 4, segmentEnd))
|
||||
: undefined;
|
||||
}
|
||||
offset = segmentEnd;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readJpegFrameSize(frame: Buffer): ImageSize | undefined {
|
||||
if (frame.length < 6 || frame[5] === 0 || frame.length !== 6 + 3 * frame[5]) {
|
||||
return undefined;
|
||||
}
|
||||
return { width: frame.readUInt16BE(3), height: frame.readUInt16BE(1) };
|
||||
}
|
||||
|
||||
function isJpegStartOfFrame(marker: number): boolean {
|
||||
return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { formatBytes } from '@expo/eas-build-job';
|
||||
import type { bunyan } from '@expo/logger';
|
||||
import { type FSWatcher, createReadStream, watch } from 'node:fs';
|
||||
import { mkdtemp, readFile, readdir, rm, rmdir, stat } from 'node:fs/promises';
|
||||
@@ -7,8 +8,8 @@ import { z } from 'zod';
|
||||
|
||||
import type { CustomBuildContext } from '../../customBuildContext';
|
||||
import { Sentry } from '../../sentry';
|
||||
import { formatBytes } from '../../utils/artifacts';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from './deviceRunSessionArtifacts';
|
||||
import { createScreenshotMetadataAsync } from './deviceRunSessionScreenshotMetadata';
|
||||
import {
|
||||
type ScreenshotSession,
|
||||
loadScreenshotSessionAsync,
|
||||
@@ -93,7 +94,10 @@ async function uploadScreenshotAsync(
|
||||
artifactId: name.slice(0, -4),
|
||||
name: artifactDetails.name,
|
||||
filename: artifactDetails.filename,
|
||||
metadata: artifactDetails.metadata,
|
||||
metadata: {
|
||||
...artifactDetails.metadata,
|
||||
...(await createScreenshotMetadataAsync(file, { source: 'manual', logger })),
|
||||
},
|
||||
kind: 'screenshot',
|
||||
size,
|
||||
openStream: () => createReadStream(file),
|
||||
|
||||
@@ -126,13 +126,14 @@ export class DeviceRunSessionWorkerApi {
|
||||
}
|
||||
|
||||
public async createPreviewUploadSessionAsync(
|
||||
input: { metadata?: Record<string, unknown> } = {},
|
||||
options: WorkerApiRequestOptions = {}
|
||||
): Promise<DeviceRunSessionUploadSession> {
|
||||
const { uploadSession } = await this.client.requestAsync(
|
||||
'POST',
|
||||
'preview-upload-session',
|
||||
UploadSessionSchema,
|
||||
options
|
||||
input.metadata ? { ...options, json: { metadata: input.metadata } } : options
|
||||
);
|
||||
return uploadSession;
|
||||
}
|
||||
|
||||
@@ -42,10 +42,12 @@ import {
|
||||
} from './remoteDeviceRunSession';
|
||||
import { LOCAL_EGRESS_PROXY_HOST, readLocalEgressHandoffAsync } from './localEgress';
|
||||
import { withDeviceRunSessionTimeoutAsync } from './deviceRunSessionTimeout';
|
||||
import { EMULATOR_CAPTURE_REQUESTED_ENV } from './emulatorCapture';
|
||||
import {
|
||||
IosSimulatorRecordingUtils,
|
||||
SERVE_SIM_STOP_GRACE_PERIOD_MS,
|
||||
} from './IosSimulatorRecordingUtils';
|
||||
import { ServeSimCrashesRecorder } from './serveSimCrashesRecorder';
|
||||
import { SERVE_SIM_STATE_DIR, readServeSimServersAsync } from './serveSimMetricsRecorder';
|
||||
import { startLogPhase } from '../../utils/logPhase';
|
||||
import { runServeSimActionAsync, stageServeSimAppAsync } from './serveSimActions';
|
||||
@@ -54,7 +56,8 @@ import {
|
||||
isPreinstalledExpoGoAsync,
|
||||
readIosApplicationIdentifierAsync,
|
||||
} from './iosAppArtifact';
|
||||
import { type ServeSimActivityPolling, startServeSimActivityPolling } from './serveSimActivity';
|
||||
import { createServeSimPreviewCapture } from './serveSimPreviewCapture';
|
||||
import { type PreviewActivityPolling, startPreviewActivityPolling } from './previewActivity';
|
||||
import { verifyLocalEgressGuardAsync } from './localEgressGuard';
|
||||
import { type IosSimulatorUuid } from '../../utils/IosSimulatorUtils';
|
||||
import { createColdIosSessionAsync } from './coldIosSession';
|
||||
@@ -72,6 +75,10 @@ const EXPO_DEVICE_HUB_PACKAGE_NAME = 'expo-device-hub';
|
||||
const EXPO_DEVICE_HUB_MAX_DIMENSION = '960';
|
||||
const EXPO_DEVICE_HUB_VIDEO_BITRATE = '6000000';
|
||||
const EXPO_DEVICE_HUB_VIDEO_FPS = '60';
|
||||
// expo-device-hub downloads the scrcpy server on first start. This copy keeps Android sessions
|
||||
// working when the GitHub release download fails; expo-device-hub falls back to GitHub when the
|
||||
// copy is missing.
|
||||
const SCRCPY_SERVER_MIRROR_BASE_URL = 'https://storage.googleapis.com/turtle-v2/scrcpy';
|
||||
// expo-device-hub's record of each running Hub, like serve-sim's: `server-<port>.json`.
|
||||
export const EXPO_DEVICE_HUB_STATE_DIR = path.join(os.tmpdir(), 'expo-device-hub');
|
||||
// On SIGTERM the Hub finalizes the recording itself, with this deadline before it force-exits,
|
||||
@@ -122,7 +129,7 @@ export function corsOriginArgs(corsOrigins: readonly string[]): string[] {
|
||||
return corsOrigins.flatMap(origin => ['--cors-origin', origin]);
|
||||
}
|
||||
|
||||
function createServeSimPackageSpec(packageVersion: string | undefined): string {
|
||||
export function createServeSimPackageSpec(packageVersion: string | undefined): string {
|
||||
return `${SERVE_SIM_PACKAGE_NAME}@${packageVersion ?? 'latest'}`;
|
||||
}
|
||||
|
||||
@@ -370,7 +377,7 @@ export type DeviceWebPreview = {
|
||||
export type DeviceSessionHost = {
|
||||
/** The preview tunnel opened during startup, or a new one after closeAsync. */
|
||||
openPreviewAsync(): Promise<DeviceWebPreview>;
|
||||
/** Last observed preview input. Always `undefined` on Android, which keeps no event log. */
|
||||
/** Last observed preview input from the serve-sim (iOS) or expo-device-hub (Android) input log. */
|
||||
getLastPreviewActivityAt(): Date | undefined;
|
||||
/**
|
||||
* Terminal and idempotent. Finalization, host-stop and upload failures are logged and reported.
|
||||
@@ -412,6 +419,11 @@ export type DeviceSessionHostOptions = {
|
||||
onStartupError?: (error: unknown) => void;
|
||||
networkCapture?: boolean;
|
||||
networkCaptureFields?: string[];
|
||||
/**
|
||||
* This session type runs an expo-device-hub that can use the experimental emulator capture.
|
||||
* Only web preview sets it; the host rejects a capture request from any other session type.
|
||||
*/
|
||||
emulatorCapture?: boolean;
|
||||
} & ServeSimLaunchOptions;
|
||||
|
||||
export type DeviceSessionServerLaunch = {
|
||||
@@ -525,6 +537,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
networkCaptureFields = [],
|
||||
bootEnv = {},
|
||||
preview,
|
||||
emulatorCapture = false,
|
||||
}: DeviceSessionHostOptions,
|
||||
onFinished: (successful: boolean) => void,
|
||||
artifactLogger: bunyan,
|
||||
@@ -532,6 +545,15 @@ async function startDeviceSessionHostInternalAsync(
|
||||
): Promise<DeviceSessionHost> {
|
||||
signal?.throwIfAborted();
|
||||
const isAndroid = runtimePlatform === BuildRuntimePlatform.LINUX;
|
||||
const requestedEmulatorCapture = env[EMULATOR_CAPTURE_REQUESTED_ENV];
|
||||
if (isAndroid && requestedEmulatorCapture && !emulatorCapture) {
|
||||
// Other session types run the latest expo-device-hub, which ignores the capture, so the
|
||||
// session would start without the capture that it asked for.
|
||||
throw new UserError(
|
||||
'EAS_EMULATOR_CAPTURE_UNSUPPORTED_SESSION',
|
||||
`The experimental emulator capture (expo-emulator-capture@${requestedEmulatorCapture}) works only in web preview sessions for now. Remove experimental_emulator_capture_version from eas/start_android_emulator, or start a web preview session.`
|
||||
);
|
||||
}
|
||||
if (
|
||||
Object.keys(bootEnv).length > 0 &&
|
||||
(runtimePlatform !== BuildRuntimePlatform.DARWIN || !iosSimulatorUdid)
|
||||
@@ -603,13 +625,17 @@ async function startDeviceSessionHostInternalAsync(
|
||||
let previewToken: string | undefined;
|
||||
let previewTask: Promise<DeviceWebPreview> | null = null;
|
||||
const previewRetirementErrors: unknown[] = [];
|
||||
// Stops new attempts to open the preview tunnel when the host finishes. An attempt in progress
|
||||
// continues, so preview retirement still waits for it and closes its listener.
|
||||
const previewRetryController = new AbortController();
|
||||
let finishTask: Promise<void> | null = null;
|
||||
let hostReady = false;
|
||||
let iosPreviewCapture: ReturnType<typeof createServeSimPreviewCapture> | undefined;
|
||||
let sessionPreview: ReturnType<typeof startDeviceRunSessionPreview> | null = null;
|
||||
const previewSetupController = new AbortController();
|
||||
let previewSetupTask: Promise<void> | undefined;
|
||||
let previewFailed = false;
|
||||
let previewActivity: ServeSimActivityPolling | null = null;
|
||||
let previewActivity: PreviewActivityPolling | null = null;
|
||||
|
||||
function openPreviewAsync(): Promise<DeviceWebPreview> {
|
||||
if (finishTask) {
|
||||
@@ -629,6 +655,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
authtoken: preview.authtoken,
|
||||
healthCheck: { path: isAndroid ? '/readyz' : '/healthz' },
|
||||
logger,
|
||||
retrySignal: previewRetryController.signal,
|
||||
});
|
||||
if (finishTask) {
|
||||
await withDeviceRunSessionTimeoutAsync(
|
||||
@@ -766,11 +793,23 @@ async function startDeviceSessionHostInternalAsync(
|
||||
env: {
|
||||
...env,
|
||||
...bootEnv,
|
||||
// The emulator start turns the experimental emulator capture on in the job env. Otherwise
|
||||
// keep it off, so a Hub build with the capture on by default does not try to attach the
|
||||
// agent with a debugger.
|
||||
...(isAndroid && env.EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE === undefined
|
||||
? { EXPO_DEVICE_HUB_EXPERIMENTAL_EMULATOR_CAPTURE: '0' }
|
||||
: {}),
|
||||
...(isAndroid ? {} : { TMPDIR: serveSimTmpdir, SERVE_SIM_STATE_DIR: serveSimStateDir }),
|
||||
EXPO_DEVICE_HUB_SCREENSHOT_DIRECTORY: screenshots.directory,
|
||||
...(recording ? { EXPO_DEVICE_HUB_RECORDING_CONTROL_TOKEN: recording.controlToken } : {}),
|
||||
// The Hub must write its token in the directory read by this host.
|
||||
...(isAndroid ? { EXPO_DEVICE_HUB_STATE_DIR } : {}),
|
||||
...(isAndroid
|
||||
? {
|
||||
SERVE_EMU_SCRCPY_BASE_URL:
|
||||
env.SERVE_EMU_SCRCPY_BASE_URL || SCRCPY_SERVER_MIRROR_BASE_URL,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
logger,
|
||||
};
|
||||
@@ -787,6 +826,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
startup.abort(error);
|
||||
// Mark the opening tunnel as retired; its late-open path closes it.
|
||||
finishTask = Promise.resolve();
|
||||
previewRetryController.abort();
|
||||
await Promise.allSettled([simulatorSetup, retirePreviewAsync()]);
|
||||
let hostStopped = true;
|
||||
try {
|
||||
@@ -814,6 +854,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
finishAsync() {
|
||||
readinessController.abort(new Error('Simulator preview ended.'));
|
||||
return (finishTask ??= (async () => {
|
||||
previewRetryController.abort();
|
||||
const previewRetirement = retirePreviewAsync();
|
||||
if (server.requiresPreviewRetirement) {
|
||||
// Confirm the tunnel is closed before stop, so the next session cannot reach this one.
|
||||
@@ -827,6 +868,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
await sessionPreview?.stopAsync();
|
||||
await previewActivity?.stopAsync();
|
||||
},
|
||||
cleanupPreviewCaptureAsync: async () => iosPreviewCapture?.cleanupAfterHostStoppedAsync(),
|
||||
previewServer,
|
||||
screenshots,
|
||||
serverName,
|
||||
@@ -984,14 +1026,31 @@ async function startDeviceSessionHostInternalAsync(
|
||||
secrets.push(previewToken);
|
||||
if (!isAndroid) {
|
||||
IosSimulatorRecordingUtils.useServeSimPackage(packageSpec);
|
||||
if (!finishTask) {
|
||||
previewActivity = startServeSimActivityPolling({ port, token: previewToken, logger });
|
||||
}
|
||||
}
|
||||
if (!finishTask) {
|
||||
previewActivity = startPreviewActivityPolling({
|
||||
server: isAndroid ? 'expo-device-hub' : 'serve-sim',
|
||||
port,
|
||||
token: previewToken,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
// Android installed FFmpeg before launching the host. The optional thumbnail must not delay
|
||||
// readiness on macOS, so it starts after its encoder is installed there.
|
||||
previewSetupTask = (async () => {
|
||||
if (!isAndroid) {
|
||||
iosPreviewCapture = createServeSimPreviewCapture({
|
||||
port,
|
||||
token: previewToken!,
|
||||
device,
|
||||
tmpdir: serveSimTmpdir,
|
||||
});
|
||||
if (!(await iosPreviewCapture.isSupportedAsync(previewSetupController.signal))) {
|
||||
logger.warn(
|
||||
'This serve-sim version does not support automated screenshots; skipping session previews.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ensureMacosPreviewEncoderInstalledAsync({
|
||||
env,
|
||||
logger,
|
||||
@@ -1005,6 +1064,7 @@ async function startDeviceSessionHostInternalAsync(
|
||||
logger,
|
||||
captureAsync: signal =>
|
||||
captureDeviceRunSessionPreviewAsync({
|
||||
captureIosScreenshotAsync: iosPreviewCapture?.captureAsync,
|
||||
runtimePlatform,
|
||||
device: previewDevice ?? device,
|
||||
env,
|
||||
@@ -1080,6 +1140,7 @@ async function finishDeviceSessionHostAsync(
|
||||
{
|
||||
previewRetirement,
|
||||
stopSessionPreviewAsync,
|
||||
cleanupPreviewCaptureAsync,
|
||||
previewServer,
|
||||
screenshots,
|
||||
serverName,
|
||||
@@ -1091,6 +1152,7 @@ async function finishDeviceSessionHostAsync(
|
||||
}: {
|
||||
previewRetirement: Promise<boolean>;
|
||||
stopSessionPreviewAsync: () => Promise<void>;
|
||||
cleanupPreviewCaptureAsync: () => Promise<void>;
|
||||
previewServer: DetachedProcessHandle;
|
||||
screenshots: { finishAsync(hostStopped: boolean): Promise<void> };
|
||||
serverName: string;
|
||||
@@ -1114,6 +1176,8 @@ async function finishDeviceSessionHostAsync(
|
||||
logger,
|
||||
});
|
||||
}
|
||||
// Crash reports are read from serve-sim, so collection finishes before it stops.
|
||||
await ServeSimCrashesRecorder.stopAsync();
|
||||
let hostStopped = false;
|
||||
try {
|
||||
await previewServer.stopAsync();
|
||||
@@ -1124,6 +1188,13 @@ async function finishDeviceSessionHostAsync(
|
||||
} catch (err) {
|
||||
logger.warn({ err }, `Could not stop the ${serverName} session host.`);
|
||||
}
|
||||
if (hostStopped) {
|
||||
try {
|
||||
await cleanupPreviewCaptureAsync();
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'Could not remove session preview capture files.');
|
||||
}
|
||||
}
|
||||
const previewRetired = await previewRetirement;
|
||||
onStopped(hostStopped && !hostExited && previewRetired);
|
||||
await screenshots.finishAsync(hostStopped);
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { UserError } from '@expo/eas-build-job';
|
||||
import { type bunyan } from '@expo/logger';
|
||||
import { type BuildStepEnv } from '@expo/steps';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { installIsolatedNpmPackageAsync } from '../../utils/installIsolatedNpmPackageAsync';
|
||||
|
||||
// Experimental emulator capture. The Android Emulator preloads the expo-emulator-capture agent,
|
||||
// which serves the emulator screen as H.264 on a Unix socket, and expo-device-hub streams the
|
||||
// screen from that socket. The step input names the agent version, so a new agent release needs
|
||||
// no change in build-tools or in the backend, while the package keeps its library at this path.
|
||||
|
||||
const PACKAGE_NAME = 'expo-emulator-capture';
|
||||
/**
|
||||
* `eas/start_android_emulator` sets this job env variable to the requested agent version. The
|
||||
* session host rejects it in every session type except web preview, the only one that runs an
|
||||
* expo-device-hub version that can use the capture for now.
|
||||
*/
|
||||
export const EMULATOR_CAPTURE_REQUESTED_ENV = 'EAS_EXPERIMENTAL_EMULATOR_CAPTURE_VERSION';
|
||||
const LINUX_AGENT_LIBRARY = path.join(
|
||||
'node_modules',
|
||||
PACKAGE_NAME,
|
||||
'dist',
|
||||
'linux-x64',
|
||||
'libexpo_emulator_capture.so'
|
||||
);
|
||||
/**
|
||||
* An npm version, a simple range such as `0.1.x`, or a dist-tag: letters, digits, `.`, `_` and `-`.
|
||||
* It keeps out specs that install another package, such as `npm:`, `file:` or git URLs. eas-cli
|
||||
* and www check the same pattern.
|
||||
*/
|
||||
const VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z._-]{0,127}$/;
|
||||
/** The registry normally answers in seconds; a stalled install must not hold the emulator. */
|
||||
const INSTALL_TIMEOUT_MS = 5 * 60_000;
|
||||
|
||||
/** The expo-emulator-capture version to preload, or undefined when the capture is off. */
|
||||
export function parseExperimentalEmulatorCaptureVersionInput(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value !== 'string' || !VERSION_PATTERN.test(value)) {
|
||||
throw new UserError(
|
||||
'EAS_EMULATOR_CAPTURE_INVALID_VERSION',
|
||||
`experimental_emulator_capture_version must be an npm version or dist-tag of ${PACKAGE_NAME}, made of letters, digits, ".", "_" and "-".`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the agent package and returns the path of its library. Returns undefined after a
|
||||
* warning when the agent cannot run on this host or the install fails. The emulator then starts
|
||||
* as it does without the capture.
|
||||
*/
|
||||
export async function installEmulatorCaptureAsync({
|
||||
version,
|
||||
env,
|
||||
logger,
|
||||
}: {
|
||||
version: string;
|
||||
env: BuildStepEnv;
|
||||
logger: bunyan;
|
||||
}): Promise<string | undefined> {
|
||||
if (process.platform !== 'linux' || process.arch !== 'x64') {
|
||||
logger.warn(
|
||||
`The experimental emulator capture runs only on Linux x86-64 hosts. The emulator starts without ${PACKAGE_NAME}.`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
let directory: string;
|
||||
try {
|
||||
directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'eas-emulator-capture-package-'));
|
||||
logger.info(`Installing ${PACKAGE_NAME}@${version} for the experimental emulator capture.`);
|
||||
await installIsolatedNpmPackageAsync({
|
||||
packageSpec: `${PACKAGE_NAME}@${version}`,
|
||||
directory,
|
||||
npmCacheUrl: env.EAS_BUILD_NPM_CACHE_URL,
|
||||
pathEnv: env.PATH,
|
||||
logger,
|
||||
signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err },
|
||||
`Could not install ${PACKAGE_NAME}@${version}. The emulator starts without it.`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
const library = path.join(directory, LINUX_AGENT_LIBRARY);
|
||||
if (!fs.existsSync(library)) {
|
||||
logger.warn(
|
||||
`${PACKAGE_NAME}@${version} has no Linux x86-64 agent at ${library}. The emulator starts without it.`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
return library;
|
||||
}
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user