forked from invertase/react-native-firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase.test.js
More file actions
1225 lines (1097 loc) · 38.3 KB
/
Copy pathfirebase.test.js
File metadata and controls
1225 lines (1097 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-console */
/*
* Copyright (c) 2016-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
const { execSync, spawn } = require('child_process');
const net = require('net');
const path = require('path');
const { pullIosCoverage, pullAndroidCoverageWithRetry } = require('../scripts/pull-native-coverage');
const { recordE2eCloudMetricFromHost } = require('../../packages/app/e2e/cloud-metrics');
const E2E_TEST_PROJECT = 'react-native-firebase-testing';
const E2E_CLOUD_PRESSURE_LOG_FILTER = 'jsonPayload.message="[rnfb-e2e-metrics]"';
const E2E_CLOUD_PRESSURE_LOG_CONSOLE_URL = `https://console.cloud.google.com/logs/query;query=${encodeURIComponent(
E2E_CLOUD_PRESSURE_LOG_FILTER,
)};storageScope=project;project=${E2E_TEST_PROJECT}`;
const E2E_CLOUD_PRESSURE_SUMMARY_CALLABLE = `https://us-central1-${E2E_TEST_PROJECT}.cloudfunctions.net/e2eCloudMetricsSummaryV2`;
function logCloudPressureAnalysisPointer(context) {
console.warn(
`[rnfb-e2e] cloud-pressure-analysis (${context}): retrospective pressure data is in Cloud Logging ` +
`(project=${E2E_TEST_PROJECT}, filter ${E2E_CLOUD_PRESSURE_LOG_FILTER}) or via POST ` +
`${E2E_CLOUD_PRESSURE_SUMMARY_CALLABLE} with {"data":{"lookbackHours":24}} — ` +
`console: ${E2E_CLOUD_PRESSURE_LOG_CONSOLE_URL}`,
);
}
const JET_REMOTE_PORT = parseInt(process.env.JET_REMOTE_PORT || '8090', 10);
const JET_CONTROL_PORT = parseInt(
process.env.RNFB_JET_CONTROL_PORT || String(JET_REMOTE_PORT + 1),
10,
);
const METRO_PORT = parseInt(process.env.JET_METRO_PORT || process.env.RCT_METRO_PORT || '8081', 10);
const LAUNCH_APP_TIMEOUT_MS = parseInt(process.env.RNFB_LAUNCH_APP_TIMEOUT_MS || '180000', 10);
const LAUNCH_APP_RELEASE_TIMEOUT_MS = parseInt(
process.env.RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS || '120000',
10,
);
const LAUNCH_APP_MAX_ATTEMPTS = parseInt(process.env.RNFB_LAUNCH_APP_MAX_ATTEMPTS || '2', 10);
const SLOW_TERMINATE_MS = parseInt(process.env.RNFB_SLOW_TERMINATE_MS || '10000', 10);
const REBOOT_IOS_SIMULATOR_TIMEOUT_MS = parseInt(
process.env.RNFB_REBOOT_IOS_SIMULATOR_TIMEOUT_MS || String(12 * 60 * 1000),
10,
);
const REBOOT_ANDROID_EMULATOR_TIMEOUT_MS = parseInt(
process.env.RNFB_REBOOT_ANDROID_EMULATOR_TIMEOUT_MS || '300000',
10,
);
const ANDROID_READY_MAX_LOAD = parseFloat(process.env.RNFB_ANDROID_READY_MAX_LOAD || '5');
const ANDROID_READY_LOAD_POLLS = parseInt(process.env.RNFB_ANDROID_READY_LOAD_POLLS || '3', 10);
const ANDROID_READY_POLL_MS = parseInt(process.env.RNFB_ANDROID_READY_POLL_MS || '2000', 10);
const ANDROID_PACKAGE_HANDLER_TIMEOUT_MS = parseInt(
process.env.RNFB_ANDROID_PACKAGE_HANDLER_TIMEOUT_MS || '30000',
10,
);
const ANDROID_BOOT_SETTLE_MS = parseInt(process.env.RNFB_ANDROID_BOOT_SETTLE_MS || '30000', 10);
const ANDROID_AVD_NAME = process.env.RNFB_ANDROID_AVD_NAME || 'TestingAVD';
const ANDROID_EMULATOR_COLD_BOOT_ARGS = (
process.env.RNFB_ANDROID_EMULATOR_BOOT_ARGS || '-no-snapshot-load -no-snapshot-save'
).trim();
const DRAIN_ORCHESTRATE_TIMEOUT_MS = parseInt(
process.env.RNFB_DRAIN_ORCHESTRATE_TIMEOUT_MS || '30000',
10,
);
const KILL_JET_FOR_LAUNCH_RETRY_TIMEOUT_MS = parseInt(
process.env.RNFB_KILL_JET_LAUNCH_RETRY_TIMEOUT_MS || '30000',
10,
);
const JET_RETRYABLE_WS_RE = /\[jet-ws\] RETRYABLE_DISCONNECT code=(1006|1001)\b/;
const JET_RECONNECT_RECOVERED_RE = /\[jet-ws\] reconnect_recovered code=(1006|1001)\b/;
const JET_SERVER_NOT_RUNNING_RE = /server wasn't running/i;
const JET_COVERAGE_LOST_RE = /Coverage summary:[\s\S]*?Unknown% \( 0\/0 \)/;
const JET_COVERAGE_TEARDOWN_RE =
/Failed to send 'coverage-ready' message: WebSocket is closed|coverage upload timed out waiting for coverage-ack/i;
const JET_PROTOCOL_ERROR_RE = /\[🟥\] Unexpected end of JSON input/i;
const JET_NO_CLIENT_CONNECTED_RE = /Error: No client connected/i;
const RETRYABLE_CLOUD_QUOTA_RE =
/installations\/token-error|Too many server requests|firebaseinstallations\.googleapis\.com|remoteConfig\/failure.*fetch\(\)|Failed to get installations token|\[remoteConfig\/unknown\].*installations/i;
const CLOUD_QUOTA_RETRY_COOLDOWN_MS = parseInt(
process.env.RNFB_CLOUD_QUOTA_RETRY_COOLDOWN_MS || '90000',
10,
);
const RETRYABLE_LAUNCH_RE =
/launchApp timed out|RCTJavaScriptDidFailToLoad|packager-probe|Metro not responding|Unknown application display identifier|Simulator device failed to launch|unknown to FrontBoard|FBSOpenApplicationServiceErrorDomain/i;
const PORT_CLOSED_ERROR_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'EPIPE']);
let cachedUsesLiveMetro;
let lastJetAttemptContext;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function isCI() {
return process.env.CI === 'true' || process.env.CI === true;
}
function resolveDetoxConfigurationName() {
if (process.env.DETOX_CONFIGURATION) {
return process.env.DETOX_CONFIGURATION;
}
if (typeof detox !== 'undefined' && detox?.config?.configurationName) {
return detox.config.configurationName;
}
return '';
}
function resolveAppBinaryPath() {
if (typeof detox !== 'undefined' && detox?.config?.apps) {
const apps = detox.config.apps;
const appConfig = apps.default || apps[Object.keys(apps)[0]];
if (appConfig?.binaryPath) {
return appConfig.binaryPath;
}
}
const fs = require('node:fs');
const debugIosApp = path.resolve(__dirname, '../ios/build/Build/Products/Debug-iphonesimulator/testing.app');
if (fs.existsSync(debugIosApp)) {
return debugIosApp;
}
const releaseIosApp = path.resolve(
__dirname,
'../ios/build/Build/Products/Release-iphonesimulator/testing.app',
);
if (fs.existsSync(releaseIosApp)) {
return releaseIosApp;
}
return '';
}
function usesLiveMetro() {
if (cachedUsesLiveMetro !== undefined) {
return cachedUsesLiveMetro;
}
const configName = resolveDetoxConfigurationName();
if (/debug/i.test(configName)) {
return true;
}
if (/release/i.test(configName)) {
return false;
}
const binaryPath = resolveAppBinaryPath();
if (/Debug-|app-debug/i.test(binaryPath)) {
return true;
}
if (/Release-|app-release/i.test(binaryPath)) {
return false;
}
return false;
}
function cacheUsesLiveMetro() {
cachedUsesLiveMetro = usesLiveMetro();
console.log(`[rnfb-e2e] cached usesLiveMetro=${cachedUsesLiveMetro}`);
}
function resolveIosSimulatorUdid() {
try {
if (typeof device !== 'undefined' && device?.id) {
return device.id;
}
} catch (_) {
// Detox device may not be ready yet.
}
return '';
}
function logLaunchInstallState(label) {
let platform = 'unknown';
try {
if (typeof detox !== 'undefined' && detox?.device?.getPlatform) {
platform = detox.device.getPlatform();
}
} catch (_) {
// Detox device may not be ready yet.
}
if (platform === 'ios' && process.platform === 'darwin') {
const udid = resolveIosSimulatorUdid();
if (!udid) {
console.log(`[rnfb-e2e] install-state label=${label} udid=unknown skipped=no-ios-udid`);
return;
}
try {
const container = execSync(
`/usr/bin/xcrun simctl get_app_container ${udid} com.invertase.testing 2>&1`,
{ encoding: 'utf8', timeout: 15000 },
).trim();
console.log(`[rnfb-e2e] install-state label=${label} udid=${udid} container=${container}`);
} catch (err) {
const detail = err?.stdout?.toString?.() || err?.message || String(err);
console.warn(
`[rnfb-e2e] install-state label=${label} udid=${udid} container=missing detail=${detail}`,
);
}
try {
const apps = execSync(`/usr/bin/xcrun simctl listapps ${udid} 2>/dev/null`, {
encoding: 'utf8',
timeout: 30000,
});
const invertaseLine =
apps
.split('\n')
.find(line => line.includes('com.invertase.testing')) || '(not listed)';
console.log(`[rnfb-e2e] install-state label=${label} listapps=${invertaseLine.trim()}`);
} catch (err) {
console.warn(
`[rnfb-e2e] install-state label=${label} listapps=error detail=${err?.message || err}`,
);
}
return;
}
if (platform === 'android') {
const serial = resolveAndroidSerial();
try {
const apk = adbShell(serial, 'pm path com.invertase.testing');
console.log(`[rnfb-e2e] install-state label=${label} serial=${serial} apk=${apk}`);
} catch (err) {
console.warn(
`[rnfb-e2e] install-state label=${label} serial=${serial} apk=missing detail=${err?.message || err}`,
);
}
return;
}
console.log(`[rnfb-e2e] install-state label=${label} skipped=platform-${platform}`);
}
function rebootIosSimulator(testsDir) {
return new Promise((resolve, reject) => {
const repoRoot = path.resolve(testsDir, '..');
const bootScript = path.join(repoRoot, '.github/workflows/scripts/boot-simulator.sh');
console.warn(`[rnfb-e2e] Rebooting iOS simulator via ${bootScript}`);
const child = spawn('bash', [bootScript], {
cwd: repoRoot,
stdio: 'inherit',
});
const timer = setTimeout(() => {
child.kill('SIGTERM');
reject(new Error(`boot-simulator.sh timed out after ${REBOOT_IOS_SIMULATOR_TIMEOUT_MS}ms`));
}, REBOOT_IOS_SIMULATOR_TIMEOUT_MS);
child.on('close', code => {
clearTimeout(timer);
if (code === 0) {
resolve();
return;
}
reject(new Error(`boot-simulator.sh failed with code ${code}`));
});
child.on('error', err => {
clearTimeout(timer);
reject(err);
});
});
}
function resolveAdbPath() {
const sdkRoot = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;
return sdkRoot ? path.join(sdkRoot, 'platform-tools', 'adb') : 'adb';
}
function resolveEmulatorPath() {
const sdkRoot = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;
if (!sdkRoot) {
throw new Error('ANDROID_HOME or ANDROID_SDK_ROOT is required to cold boot the Android emulator');
}
return path.join(sdkRoot, 'emulator', 'emulator');
}
function resolveAndroidEmulatorPort(serial) {
const portMatch = serial.match(/^emulator-(\d+)$/);
return portMatch ? portMatch[1] : '5554';
}
function adbDeviceState(serial) {
const adb = resolveAdbPath();
try {
return execSync(`${adb} -s ${serial} get-state`, {
encoding: 'utf8',
timeout: 5000,
}).trim();
} catch (_) {
return 'unknown';
}
}
function resolveAndroidSerial() {
try {
if (typeof device !== 'undefined' && device?.id) {
return device.id;
}
} catch (_) {
// Detox device may not be ready yet.
}
return process.env.ANDROID_SERIAL || 'emulator-5554';
}
function adbShell(serial, command, timeoutMs = 15000) {
const adb = resolveAdbPath();
return execSync(`${adb} -s ${serial} shell ${command}`, {
encoding: 'utf8',
timeout: timeoutMs,
}).trim();
}
function parseGuestLoad1Min(loadavgLine) {
const first = loadavgLine.trim().split(/\s+/)[0];
const load = parseFloat(first);
return Number.isFinite(load) ? load : NaN;
}
function killTcpPortListener(port, label) {
let pidList = '';
try {
pidList = execSync(`lsof -nP -iTCP:${port} -sTCP:LISTEN -t 2>/dev/null || true`, {
encoding: 'utf8',
timeout: 5000,
}).trim();
} catch (err) {
console.warn(`[rnfb-e2e] ${label}: unable to inspect :${port} listener: ${err?.message || err}`);
return;
}
const pids = pidList
.split(/\s+/)
.filter(Boolean)
.filter(pid => /^\d+$/.test(pid));
if (pids.length === 0) {
console.log(`[rnfb-e2e] ${label}: no listener on :${port}`);
return;
}
console.warn(`[rnfb-e2e] ${label}: killing stray listener on :${port} pid=${pids.join(',')}`);
try {
execSync(`kill ${pids.join(' ')}`, { stdio: 'inherit', timeout: 5000 });
} catch (err) {
console.warn(`[rnfb-e2e] ${label}: failed to kill :${port} listener: ${err?.message || err}`);
}
}
async function ensureTcpPortClosed(port, label, timeoutMs = KILL_JET_FOR_LAUNCH_RETRY_TIMEOUT_MS) {
killTcpPortListener(port, label);
await waitForTcpPortClosed(port, '127.0.0.1', timeoutMs);
}
function forceStopAndroidTestingApps(label) {
const adb = resolveAdbPath();
const serial = resolveAndroidSerial();
const packages = ['com.invertase.testing', 'com.invertase.testing.test'];
for (const appId of packages) {
try {
console.log(`[rnfb-e2e] ${label}: force-stopping ${appId} serial=${serial}`);
execSync(`${adb} -s ${serial} shell am force-stop ${appId}`, {
stdio: 'inherit',
timeout: 15000,
});
} catch (err) {
console.warn(`[rnfb-e2e] ${label}: force-stop ${appId} failed: ${err?.message || err}`);
}
}
}
async function waitForAndroidInstrumentationStopped(label, timeoutMs = 30000) {
const serial = resolveAndroidSerial();
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const pid = adbShell(serial, 'pidof com.invertase.testing.test', 5000);
if (!pid) {
console.log(`[rnfb-e2e] ${label}: instrumentation pid clear`);
return;
}
console.log(`[rnfb-e2e] ${label}: waiting for instrumentation pid=${pid}`);
} catch (_) {
console.log(`[rnfb-e2e] ${label}: instrumentation pid clear`);
return;
}
await sleep(1000);
}
throw new Error(`[rnfb-e2e] ${label}: instrumentation pid still present after ${timeoutMs}ms`);
}
function clearStaleMacOsTestingForSharedJetPort(label) {
if (process.platform !== 'darwin') {
return;
}
console.log(
`[rnfb-e2e] ${label}: killing stale macOS io.invertase.testing for shared :${JET_REMOTE_PORT}`,
);
try {
execSync('killall "io.invertase.testing"', { stdio: 'inherit', timeout: 5000 });
} catch (_) {
// not running — expected
}
try {
execSync("pkill -f 'tests:macos:test-cover|jet --target=macos' 2>/dev/null || true", {
stdio: 'inherit',
timeout: 5000,
});
} catch (_) {
// no stray macOS jet — expected
}
}
async function ensureAndroidJetHostClear(label = 'android-jet-host-clear') {
console.log(`[rnfb-e2e] ${label}: clearing Android apps and Jet port before spawn`);
clearStaleMacOsTestingForSharedJetPort(label);
forceStopAndroidTestingApps(label);
await waitForAndroidInstrumentationStopped(label);
await ensureTcpPortClosed(JET_REMOTE_PORT, label);
console.log(`[rnfb-e2e] ${label}: host clear`);
}
function coldBootAndroidEmulator() {
const adb = resolveAdbPath();
const serial = resolveAndroidSerial();
const port = resolveAndroidEmulatorPort(serial);
const coldBootSerial = `emulator-${port}`;
const emulatorPath = resolveEmulatorPath();
const extraBootArgs = ANDROID_EMULATOR_COLD_BOOT_ARGS.split(/\s+/).filter(Boolean);
console.warn(
`[rnfb-e2e] Cold booting Android emulator serial=${serial} avd=${ANDROID_AVD_NAME} ` +
`(kill + relaunch with ${extraBootArgs.join(' ')})`,
);
try {
execSync(`${adb} -s ${serial} emu kill`, { stdio: 'inherit', timeout: 60000 });
} catch (err) {
console.warn(`[rnfb-e2e] emu kill failed (continuing): ${err?.message || err}`);
}
try {
execSync(`pkill -f "qemu-system.*@${ANDROID_AVD_NAME}"`, { stdio: 'ignore', timeout: 5000 });
} catch (_) {
// No matching emulator process.
}
const emulatorArgs = [
'-verbose',
'-no-audio',
'-no-boot-anim',
'-read-only',
'-port',
port,
...extraBootArgs,
`@${ANDROID_AVD_NAME}`,
];
const child = spawn(emulatorPath, emulatorArgs, {
detached: true,
stdio: 'ignore',
});
child.unref();
execSync(`${adb} -s ${coldBootSerial} wait-for-device`, {
stdio: 'inherit',
timeout: REBOOT_ANDROID_EMULATOR_TIMEOUT_MS,
});
}
async function waitForAndroidEmulatorReady() {
const serial = resolveAndroidSerial();
const deadline = Date.now() + REBOOT_ANDROID_EMULATOR_TIMEOUT_MS;
let stableLoadPolls = 0;
let packageHandlerDone = false;
let bootSettleDone = false;
while (Date.now() < deadline) {
try {
const deviceState = adbDeviceState(serial);
if (deviceState === 'offline') {
stableLoadPolls = 0;
console.warn(
`[rnfb-e2e] android-ready probe serial=${serial} state=offline (Quick Boot gray screen?) — ` +
'kill emulator and rerun; Detox should cold boot with -no-snapshot-load',
);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
const bootCompleted = adbShell(serial, 'getprop sys.boot_completed');
const bootDev = adbShell(serial, 'getprop dev.bootcomplete');
const provisioned = adbShell(serial, 'settings get global device_provisioned');
adbShell(serial, 'echo ok', 5000);
if (bootCompleted !== '1') {
stableLoadPolls = 0;
console.log(`[rnfb-e2e] android-ready probe boot_completed=${bootCompleted} (waiting)`);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
if (bootDev !== '1') {
stableLoadPolls = 0;
console.log(`[rnfb-e2e] android-ready probe dev.bootcomplete=${bootDev} (waiting)`);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
if (provisioned !== '1') {
stableLoadPolls = 0;
console.log(`[rnfb-e2e] android-ready probe provisioned=${provisioned} (waiting)`);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
if (!packageHandlerDone) {
console.log('[rnfb-e2e] android-ready probe waiting for package handler queue...');
try {
adbShell(
serial,
`cmd package wait-for-handler --timeout ${ANDROID_PACKAGE_HANDLER_TIMEOUT_MS}`,
ANDROID_PACKAGE_HANDLER_TIMEOUT_MS + 5000,
);
packageHandlerDone = true;
console.log('[rnfb-e2e] android-ready probe package handler ready');
} catch (err) {
console.warn(`[rnfb-e2e] android-ready package handler wait: ${err?.message || err}`);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
}
if (!isCI()) {
console.log('[rnfb-e2e] android-ready: skipping settle/load (not CI)');
console.log(`[rnfb-e2e] Android emulator ready serial=${serial}`);
return;
}
if (!bootSettleDone) {
console.log(
`[rnfb-e2e] android-ready boot complete; settling ${ANDROID_BOOT_SETTLE_MS}ms before load polling`,
);
await sleep(ANDROID_BOOT_SETTLE_MS);
bootSettleDone = true;
stableLoadPolls = 0;
}
const loadLine = adbShell(serial, 'cat /proc/loadavg');
const load1 = parseGuestLoad1Min(loadLine);
if (!Number.isFinite(load1) || load1 >= ANDROID_READY_MAX_LOAD) {
stableLoadPolls = 0;
console.log(
`[rnfb-e2e] android-ready probe load1=${load1} max=${ANDROID_READY_MAX_LOAD} loadavg="${loadLine.trim()}" (waiting)`,
);
await sleep(ANDROID_READY_POLL_MS);
continue;
}
stableLoadPolls += 1;
console.log(
`[rnfb-e2e] android-ready probe load1=${load1} stable=${stableLoadPolls}/${ANDROID_READY_LOAD_POLLS} boot=1 provisioned=1`,
);
if (stableLoadPolls >= ANDROID_READY_LOAD_POLLS) {
console.log(`[rnfb-e2e] Android emulator ready serial=${serial}`);
return;
}
await sleep(ANDROID_READY_POLL_MS);
} catch (err) {
stableLoadPolls = 0;
console.warn(`[rnfb-e2e] android-ready probe: ${err?.message || err}`);
await sleep(ANDROID_READY_POLL_MS);
}
}
throw new Error(
`Android emulator did not become ready within ${REBOOT_ANDROID_EMULATOR_TIMEOUT_MS}ms (serial=${serial})`,
);
}
async function drainJetAttempt(platform) {
const ctx = lastJetAttemptContext;
console.warn('[rnfb-e2e] Draining Jet attempt before outer retry...');
if (platform === 'android') {
try {
await device.terminateApp();
} catch (_) {
// Detox may already be disconnected.
}
forceStopAndroidTestingApps('drain');
} else {
try {
await device.terminateApp();
} catch (_) {
// No-op
}
}
if (ctx?.orchestratePromise) {
await Promise.race([
ctx.orchestratePromise.catch(() => {}),
sleep(DRAIN_ORCHESTRATE_TIMEOUT_MS).then(() => {
console.warn(
`[rnfb-e2e] drain orchestrate timed out after ${DRAIN_ORCHESTRATE_TIMEOUT_MS}ms`,
);
}),
]);
}
if (ctx?.jetProcess && !ctx.jetProcess.killed) {
ctx.jetProcess.kill('SIGTERM');
await sleep(500);
if (!ctx.jetProcess.killed) {
ctx.jetProcess.kill('SIGKILL');
}
}
if (platform === 'android') {
await ensureAndroidJetHostClear('drain');
} else {
await waitForTcpPortClosed(JET_REMOTE_PORT);
}
console.log('[rnfb-e2e] Jet attempt drain complete');
}
function waitForTcpPort(port, host = '127.0.0.1', timeoutMs = 120000) {
const start = Date.now();
return new Promise((resolve, reject) => {
const tryConnect = () => {
if (Date.now() - start > timeoutMs) {
reject(new Error(`Timed out waiting for ${host}:${port} after ${timeoutMs}ms`));
return;
}
const socket = net.connect(port, host);
socket.once('connect', () => {
socket.end();
resolve();
});
socket.once('error', () => {
socket.destroy();
setTimeout(tryConnect, 250);
});
};
tryConnect();
});
}
function waitForTcpPortClosed(port, host = '127.0.0.1', timeoutMs = 120000) {
const start = Date.now();
let probes = 0;
return new Promise((resolve, reject) => {
const probe = () => {
if (Date.now() - start > timeoutMs) {
reject(
new Error(
`Timed out waiting for ${host}:${port} to close after ${timeoutMs}ms (probes=${probes})`,
),
);
return;
}
probes += 1;
const socket = net.connect(port, host);
socket.once('connect', () => {
socket.end();
setTimeout(probe, 250);
});
socket.once('error', err => {
socket.destroy();
const elapsedMs = Date.now() - start;
const code = err?.code || 'UNKNOWN';
if (PORT_CLOSED_ERROR_CODES.has(code)) {
console.log(
`[rnfb-e2e] port ${host}:${port} closed (code=${code}, elapsed=${elapsedMs}ms, probes=${probes})`,
);
resolve();
return;
}
console.warn(
`[rnfb-e2e] port-probe non-close error code=${code} host=${host} port=${port} probe=${probes}`,
);
setTimeout(probe, 250);
});
};
probe();
});
}
function isRetryableJetDisconnect(output) {
return JET_RETRYABLE_WS_RE.test(output);
}
function isRetryableJetSessionFailure(output) {
if (JET_SERVER_NOT_RUNNING_RE.test(output)) {
return true;
}
if (JET_COVERAGE_TEARDOWN_RE.test(output)) {
return true;
}
if (JET_PROTOCOL_ERROR_RE.test(output)) {
return true;
}
if (JET_NO_CLIENT_CONNECTED_RE.test(output)) {
return true;
}
if (!JET_RECONNECT_RECOVERED_RE.test(output)) {
return false;
}
return JET_COVERAGE_LOST_RE.test(output) || /\[🟥\] Stopped the server/i.test(output);
}
function isRetryableCloudQuotaFailure(jetOutput) {
return RETRYABLE_CLOUD_QUOTA_RE.test(jetOutput);
}
function isRetryableLaunchFailure(err) {
const message = err?.message || '';
if (err?.retryableAtJetLevel) {
return true;
}
if (!usesLiveMetro()) {
return (
/launchApp timed out/i.test(message) ||
RETRYABLE_LAUNCH_RE.test(message) ||
/FrontBoard|unknown to FrontBoard|FBSOpenApplication/i.test(message)
);
}
return RETRYABLE_LAUNCH_RE.test(message);
}
function isRetryableE2eFailure(err) {
const jetOutput = err?.jetOutput || '';
return (
isRetryableJetDisconnect(jetOutput) ||
isRetryableJetSessionFailure(jetOutput) ||
isRetryableCloudQuotaFailure(jetOutput) ||
isRetryableLaunchFailure(err)
);
}
function logRetryEligibility(err, attempt) {
const jetOutput = err?.jetOutput || '';
const checks = {
jetDisconnect: isRetryableJetDisconnect(jetOutput),
jetSession: isRetryableJetSessionFailure(jetOutput),
jetProtocol: JET_PROTOCOL_ERROR_RE.test(jetOutput),
jetNoClient: JET_NO_CLIENT_CONNECTED_RE.test(jetOutput),
coverageTeardown: JET_COVERAGE_TEARDOWN_RE.test(jetOutput),
cloudQuota: isRetryableCloudQuotaFailure(jetOutput),
launchFailure: isRetryableLaunchFailure(err),
launchJetLevel: Boolean(err?.retryableAtJetLevel),
};
console.warn(
`[rnfb-e2e] retry-eligibility attempt=${attempt} retryable=${attempt === 1 && isRetryableE2eFailure(err)} checks=${JSON.stringify(checks)}`,
);
}
async function waitForMetro(port = METRO_PORT, timeoutMs = 120000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
const response = await fetch(`http://127.0.0.1:${port}/status`);
const body = await response.text();
if (body.includes('packager-status:running')) {
console.log(`[rnfb-e2e] Metro OK on 127.0.0.1:${port}`);
return;
}
console.warn(
`[rnfb-e2e] Metro 127.0.0.1:${port}/status returned unexpected body: ${body.slice(0, 120)}`,
);
} catch (_) {
// Metro not ready yet; keep polling.
}
await new Promise(resolve => setTimeout(resolve, 500));
}
throw new Error(
`Metro not responding with packager-status:running on 127.0.0.1:${port} after ${timeoutMs}ms`,
);
}
async function terminateAppWithTiming(label) {
const start = Date.now();
try {
await device.terminateApp();
const elapsedMs = Date.now() - start;
console.log(`[rnfb-e2e] terminateApp label=${label} elapsed=${elapsedMs}ms`);
return elapsedMs;
} catch (err) {
const elapsedMs = Date.now() - start;
console.warn(
`[rnfb-e2e] terminateApp label=${label} elapsed=${elapsedMs}ms error=${err?.message || err}`,
);
return elapsedMs;
}
}
async function launchAppWithTimeout(launchArgs, { deleteApp = true, timeoutMs } = {}) {
const effectiveTimeout = timeoutMs ?? (usesLiveMetro() ? LAUNCH_APP_TIMEOUT_MS : LAUNCH_APP_RELEASE_TIMEOUT_MS);
console.log(
`[rnfb-e2e] launchApp starting timeout=${effectiveTimeout}ms delete=${deleteApp} liveMetro=${usesLiveMetro()}`,
);
logLaunchInstallState(`before-launch delete=${deleteApp}`);
let timer;
try {
await Promise.race([
device.launchApp({
newInstance: true,
delete: deleteApp,
launchArgs,
}),
new Promise((_, reject) => {
timer = setTimeout(() => {
const err = new Error(
`[rnfb-e2e] launchApp timed out after ${effectiveTimeout}ms — check sim-app.log for ` +
`[rnfb-lifecycle] packager-probe / RCTJavaScriptDidFailToLoad and Detox waitForActive`,
);
err.retryableLaunchFailure = true;
reject(err);
}, effectiveTimeout);
}),
]);
console.log('[rnfb-e2e] launchApp complete');
logLaunchInstallState('after-launch-success');
} finally {
clearTimeout(timer);
}
}
async function postJetControl(path, body) {
const url = `http://127.0.0.1:${JET_CONTROL_PORT}${path}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
console.warn(`[rnfb-e2e] jet-control POST ${path} status=${response.status}`);
}
} catch (err) {
console.warn(`[rnfb-e2e] jet-control POST ${path} failed: ${err?.message || err}`);
}
}
function logOrchestrateState(state) {
console.log(`[rnfb-e2e] orchestrate-state=${state} ts=${new Date().toISOString()}`);
postJetControl('/orchestrate-state', { phase: state });
}
async function signalJetLaunchReady() {
console.log('[rnfb-e2e] signaling Jet launch-ready (permit test run)');
await postJetControl('/launch-ready', {});
}
async function killJetForLaunchRetry(jetProcess) {
if (!jetProcess || jetProcess.killed) {
return;
}
logOrchestrateState('launch-retry-kill-jet');
console.warn('[rnfb-e2e] launch-retry: killing Jet before terminateApp/reboot');
jetProcess.kill('SIGTERM');
await sleep(500);
if (!jetProcess.killed) {
jetProcess.kill('SIGKILL');
}
try {
await waitForTcpPortClosed(JET_REMOTE_PORT, '127.0.0.1', KILL_JET_FOR_LAUNCH_RETRY_TIMEOUT_MS);
} catch (err) {
console.warn(`[rnfb-e2e] launch-retry: Jet port still open after kill: ${err?.message || err}`);
}
}
async function launchAppWithRetry(launchArgs, { testsDir, onBeforeRelaunch } = {}) {
const liveMetro = usesLiveMetro();
for (let launchAttempt = 1; launchAttempt <= LAUNCH_APP_MAX_ATTEMPTS; launchAttempt++) {
try {
if (launchAttempt > 1) {
console.warn(
`[rnfb-e2e] Retrying launchApp after launch failure (attempt ${launchAttempt}/${LAUNCH_APP_MAX_ATTEMPTS}) liveMetro=${liveMetro}`,
);
if (onBeforeRelaunch) {
await onBeforeRelaunch();
}
const terminateMs = await terminateAppWithTiming(`retry-${launchAttempt}`);
if (terminateMs >= SLOW_TERMINATE_MS && testsDir && process.platform === 'darwin') {
console.warn(
`[rnfb-e2e] slow terminate (${terminateMs}ms >= ${SLOW_TERMINATE_MS}ms) — rebooting simulator before relaunch`,
);
await rebootIosSimulator(testsDir);
}
if (liveMetro) {
await waitForMetro(METRO_PORT);
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
await launchAppWithTimeout(launchArgs, {
deleteApp: launchAttempt === 1,
});
return;
} catch (err) {
console.warn(`[rnfb-e2e] launchApp failure reason=${err?.message || err}`);
logLaunchInstallState(`after-launch-failure attempt=${launchAttempt}`);
const innerRetryable =
launchAttempt < LAUNCH_APP_MAX_ATTEMPTS && isRetryableLaunchFailure(err);
if (!innerRetryable) {
err.retryableAtJetLevel = isRetryableLaunchFailure(err);
throw err;
}
}
}
}
function createJetSession(jetArgs, testsDir) {
let output = '';
let jetProcess;
let ignoreExit = false;
let resolveExit;
let rejectExit;
const exitPromise = new Promise((resolve, reject) => {
resolveExit = resolve;
rejectExit = reject;
});
const bindProcess = proc => {
jetProcess = proc;
proc.stdout.on('data', chunk => {
const text = chunk.toString();
output += text;
process.stdout.write(text);
});
proc.stderr.on('data', chunk => {
const text = chunk.toString();
output += text;
process.stderr.write(text);
});
proc.on('error', err => {
if (ignoreExit) {
console.warn(`[rnfb-e2e] ignoring Jet error during launch-retry: ${err?.message || err}`);
return;
}
err.jetOutput = output;
rejectExit(err);
});
proc.on('close', code => {
if (ignoreExit) {
console.warn(`[rnfb-e2e] ignoring Jet exit code=${code} during launch-retry`);
return;
}
if (code !== 0) {
const err = new Error('Jet tests failed!');
err.jetOutput = output;
err.jetExitCode = code;
rejectExit(err);
return;
}
resolveExit({ output });
});
};
const spawnJet = () => {
const proc = spawn('yarn', jetArgs, {
stdio: ['ignore', 'pipe', 'pipe'],