@devicecloud.dev/dcd 5.11.0-beta.5 → 5.11.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/cloud.js +6 -1
- package/dist/commands/device.js +24 -2
- package/dist/gateways/device-gateway.d.ts +1 -1
- package/dist/gateways/device-gateway.js +2 -2
- package/dist/mcp/tools/run-cloud-test.js +1 -1
- package/dist/methods.d.ts +24 -0
- package/dist/methods.js +144 -166
- package/dist/services/execution-plan.service.d.ts +6 -0
- package/dist/services/execution-plan.service.js +8 -0
- package/dist/services/metadata-extractor.service.d.ts +13 -0
- package/dist/services/metadata-extractor.service.js +35 -1
- package/dist/types/domain/device-session.types.d.ts +14 -0
- package/dist/types.d.ts +11 -0
- package/dist/utils/b2-retry.d.ts +49 -0
- package/dist/utils/b2-retry.js +77 -0
- package/dist/utils/device-run.js +8 -0
- package/package.json +1 -1
package/dist/commands/cloud.js
CHANGED
|
@@ -6,7 +6,7 @@ import { flags as allFlags } from '../constants.js';
|
|
|
6
6
|
import { ApiGateway } from '../gateways/api-gateway.js';
|
|
7
7
|
import { uploadBinary, uploadFlowZip, verifyAppZip, writeJSONFile, } from '../methods.js';
|
|
8
8
|
import { DeviceValidationService } from '../services/device-validation.service.js';
|
|
9
|
-
import { plan } from '../services/execution-plan.service.js';
|
|
9
|
+
import { countExtendedRuntimeFlows, plan } from '../services/execution-plan.service.js';
|
|
10
10
|
import { isSubmitEndpointMissing, submitWithRetry, } from '../services/flow-submit.service.js';
|
|
11
11
|
import { buildTestMetadataMap, computeCommonRoot, } from '../services/flow-paths.js';
|
|
12
12
|
import { MoropoService } from '../services/moropo.service.js';
|
|
@@ -523,6 +523,11 @@ export const cloudCommand = defineCommand({
|
|
|
523
523
|
submitRows.push(colors.dim(`${flowPath.replace(process.cwd(), '.')}:`));
|
|
524
524
|
submitRows.push(...ui.fields(Object.entries(overrides).map(([key, value]) => [key, colors.highlight(String(value))])));
|
|
525
525
|
}
|
|
526
|
+
// The 2x is charged per flow, so say it before the run, not on the bill.
|
|
527
|
+
const extendedFlows = countExtendedRuntimeFlows(flowOverrides);
|
|
528
|
+
if (extendedFlows > 0) {
|
|
529
|
+
submitRows.push('', ui.note(`${extendedFlows} flow${extendedFlows === 1 ? '' : 's'} with extended runtime: up to 20 min each, billed at 2×`));
|
|
530
|
+
}
|
|
526
531
|
}
|
|
527
532
|
out(ui.section('Submitting new job'));
|
|
528
533
|
out(ui.branch(submitRows));
|
package/dist/commands/device.js
CHANGED
|
@@ -583,13 +583,21 @@ const modelsSub = defineCommand({
|
|
|
583
583
|
});
|
|
584
584
|
const inspectSub = defineCommand({
|
|
585
585
|
meta: { name: 'inspect', description: 'The screen as compact JSON: each element with text, an id or a label' },
|
|
586
|
-
args: {
|
|
586
|
+
args: {
|
|
587
|
+
...commonArgs,
|
|
588
|
+
id: idArg,
|
|
589
|
+
all: {
|
|
590
|
+
type: 'boolean',
|
|
591
|
+
default: false,
|
|
592
|
+
description: 'Also list the keyboard keys and the System UI (status and navigation bars)',
|
|
593
|
+
},
|
|
594
|
+
},
|
|
587
595
|
async run({ args }) {
|
|
588
596
|
const json = Boolean(args.json);
|
|
589
597
|
await runDeviceCommand(json, async () => {
|
|
590
598
|
const ctx = await context(args);
|
|
591
599
|
const id = await resolveSessionId(ctx.apiUrl, ctx.auth, args.id);
|
|
592
|
-
const { screen, session } = await DeviceGateway.inspect(ctx.apiUrl, ctx.auth, id);
|
|
600
|
+
const { screen, session } = await DeviceGateway.inspect(ctx.apiUrl, ctx.auth, id, Boolean(args.all));
|
|
593
601
|
return {
|
|
594
602
|
session,
|
|
595
603
|
data: { screen },
|
|
@@ -597,6 +605,14 @@ const inspectSub = defineCommand({
|
|
|
597
605
|
logger.log(ui.section(`Screen ${screen.width}x${screen.height}, ${screen.elements.length} elements` +
|
|
598
606
|
(screen.fresh ? '' : colors.dim(' (no new frame; this is the latest)'))));
|
|
599
607
|
logger.log(ui.branch(screen.elements.map((el) => formatElement(el))));
|
|
608
|
+
const notes = [];
|
|
609
|
+
if (screen.keyboard_open)
|
|
610
|
+
notes.push('A keyboard is open.');
|
|
611
|
+
if (screen.hidden && (screen.hidden.keyboard > 0 || screen.hidden.system > 0)) {
|
|
612
|
+
notes.push(`Left out ${screen.hidden.keyboard} keyboard and ${screen.hidden.system} System UI elements (--all shows them).`);
|
|
613
|
+
}
|
|
614
|
+
if (notes.length > 0)
|
|
615
|
+
logger.log(ui.note(notes.join(' ')));
|
|
600
616
|
},
|
|
601
617
|
};
|
|
602
618
|
});
|
|
@@ -613,6 +629,12 @@ export function formatElement(el) {
|
|
|
613
629
|
parts.push(`id:${el.rid}`);
|
|
614
630
|
if (el.hint)
|
|
615
631
|
parts.push(`hint:"${el.hint}"`);
|
|
632
|
+
for (const state of ['checked', 'selected', 'focused']) {
|
|
633
|
+
if (el[state])
|
|
634
|
+
parts.push(state);
|
|
635
|
+
}
|
|
636
|
+
if (el.enabled === false)
|
|
637
|
+
parts.push('disabled');
|
|
616
638
|
return `${parts.join(' ')} ${colors.dim(el.b)}`;
|
|
617
639
|
}
|
|
618
640
|
/** `data:image/jpeg;base64,...` to bytes and a file extension. */
|
|
@@ -22,7 +22,7 @@ export declare const DeviceGateway: {
|
|
|
22
22
|
human: DeviceHumanStatus;
|
|
23
23
|
session: DeviceSession;
|
|
24
24
|
}>;
|
|
25
|
-
inspect(baseUrl: string, auth: AuthContext, id: string): Promise<{
|
|
25
|
+
inspect(baseUrl: string, auth: AuthContext, id: string, all?: boolean): Promise<{
|
|
26
26
|
screen: DeviceScreen;
|
|
27
27
|
session: DeviceSession;
|
|
28
28
|
}>;
|
|
@@ -97,8 +97,8 @@ export const DeviceGateway = {
|
|
|
97
97
|
human(baseUrl, auth, id) {
|
|
98
98
|
return request(baseUrl, auth, 'GET', `${sessionPath(id)}/human`);
|
|
99
99
|
},
|
|
100
|
-
inspect(baseUrl, auth, id) {
|
|
101
|
-
return request(baseUrl, auth, 'GET', `${sessionPath(id)}/inspect`);
|
|
100
|
+
inspect(baseUrl, auth, id, all = false) {
|
|
101
|
+
return request(baseUrl, auth, 'GET', `${sessionPath(id)}/inspect${all ? '?all=true' : ''}`);
|
|
102
102
|
},
|
|
103
103
|
install(baseUrl, auth, id, app) {
|
|
104
104
|
return request(baseUrl, auth, 'POST', `${sessionPath(id)}/install`, app);
|
|
@@ -95,7 +95,7 @@ export function registerRunCloudTest(server) {
|
|
|
95
95
|
.min(30)
|
|
96
96
|
.max(3600)
|
|
97
97
|
.optional()
|
|
98
|
-
.describe('Max seconds to wait when wait is true (default 600)'),
|
|
98
|
+
.describe('Max seconds to wait when wait is true (default 600). A flow with DEVICECLOUD_OVERRIDE_EXTENDED_RUNTIME: true in its env can run for up to 20 minutes, so raise this when the run includes one.'),
|
|
99
99
|
},
|
|
100
100
|
annotations: {
|
|
101
101
|
title: 'Run a cloud test',
|
package/dist/methods.d.ts
CHANGED
|
@@ -16,6 +16,21 @@ interface UploadBinaryConfig {
|
|
|
16
16
|
log?: boolean;
|
|
17
17
|
}
|
|
18
18
|
export declare const uploadBinary: (config: UploadBinaryConfig) => Promise<string>;
|
|
19
|
+
type UploadResult = {
|
|
20
|
+
error: Error | null;
|
|
21
|
+
success: boolean;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Validates upload results and throws if all uploads failed. The message names
|
|
25
|
+
* both failures: the Supabase error alone hid every Backblaze failure behind
|
|
26
|
+
* it, which is what made a dropped B2 request look like a Supabase outage.
|
|
27
|
+
* @param supabase - Result of the Supabase upload
|
|
28
|
+
* @param backblaze - Result of the Backblaze upload
|
|
29
|
+
* @param b2 - Backblaze configuration
|
|
30
|
+
* @param debug - Enable debug logging
|
|
31
|
+
* @returns void - throws error if all uploads failed
|
|
32
|
+
*/
|
|
33
|
+
export declare function validateUploadResults(supabase: UploadResult, backblaze: UploadResult, b2: unknown, debug: boolean): void;
|
|
19
34
|
/**
|
|
20
35
|
* Storage reference for an already-uploaded flow zip, threaded into the
|
|
21
36
|
* `submitFlowTest` JSON body so the API can locate the staged file.
|
|
@@ -47,6 +62,15 @@ export declare const uploadFlowZip: (config: {
|
|
|
47
62
|
buffer: Buffer;
|
|
48
63
|
debug?: boolean;
|
|
49
64
|
}) => Promise<FlowZipUploadResult>;
|
|
65
|
+
/**
|
|
66
|
+
* Picks the upload URL for one attempt at one part. The API mints one URL per
|
|
67
|
+
* part, but each is bound to the large file rather than to a part number (the
|
|
68
|
+
* part number travels in `X-Bz-Part-Number`), so any of them can carry any
|
|
69
|
+
* part. A retry moves on to the next one, which is what B2 asks for after a
|
|
70
|
+
* 503 or a dropped connection. Parts upload one at a time, so no URL is ever
|
|
71
|
+
* in use twice at once.
|
|
72
|
+
*/
|
|
73
|
+
export declare function partUploadUrlFor<T>(urls: T[], partNumber: number, attempt: number): T;
|
|
50
74
|
/**
|
|
51
75
|
* Writes JSON data to a file with error handling
|
|
52
76
|
* @param filePath - Path to the output JSON file
|
package/dist/methods.js
CHANGED
|
@@ -11,6 +11,7 @@ import { inferEnvFromApiUrl } from './config/environments.js';
|
|
|
11
11
|
import { ApiError, ApiGateway } from './gateways/api-gateway.js';
|
|
12
12
|
import { SupabaseGateway } from './gateways/supabase-gateway.js';
|
|
13
13
|
import { detectFlutterEngine, MetadataExtractorService, } from './services/metadata-extractor.service.js';
|
|
14
|
+
import { assertB2Ok, B2HttpError, withB2Retry } from './utils/b2-retry.js';
|
|
14
15
|
import { encryptFileToPath, generateDek, resolveKekPublicKey, wrapDek, } from './utils/envelope.js';
|
|
15
16
|
import { colors, formatId } from './utils/styling.js';
|
|
16
17
|
const mimeTypeLookupByExtension = {
|
|
@@ -472,7 +473,10 @@ async function handleBackblazeUpload(config) {
|
|
|
472
473
|
? `[DEBUG] Backblaze upload completed successfully in ${durationSeconds.toFixed(2)}s (${duration}ms)`
|
|
473
474
|
: `[DEBUG] Backblaze upload failed after ${durationSeconds.toFixed(2)}s (${duration}ms)`);
|
|
474
475
|
}
|
|
475
|
-
return {
|
|
476
|
+
return {
|
|
477
|
+
error: backblazeSuccess ? null : new Error(`Backblaze upload strategy '${b2.strategy}' is not usable`),
|
|
478
|
+
success: backblazeSuccess,
|
|
479
|
+
};
|
|
476
480
|
}
|
|
477
481
|
catch (error) {
|
|
478
482
|
const b2Error = error instanceof Error ? error : new Error(String(error));
|
|
@@ -557,22 +561,24 @@ async function extractBinaryMetadata(filePath, debug) {
|
|
|
557
561
|
return metadata;
|
|
558
562
|
}
|
|
559
563
|
/**
|
|
560
|
-
* Validates upload results and throws if all uploads failed
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
* @param
|
|
564
|
+
* Validates upload results and throws if all uploads failed. The message names
|
|
565
|
+
* both failures: the Supabase error alone hid every Backblaze failure behind
|
|
566
|
+
* it, which is what made a dropped B2 request look like a Supabase outage.
|
|
567
|
+
* @param supabase - Result of the Supabase upload
|
|
568
|
+
* @param backblaze - Result of the Backblaze upload
|
|
564
569
|
* @param b2 - Backblaze configuration
|
|
565
570
|
* @param debug - Enable debug logging
|
|
566
571
|
* @returns void - throws error if all uploads failed
|
|
567
572
|
*/
|
|
568
|
-
function validateUploadResults(
|
|
569
|
-
if (
|
|
573
|
+
export function validateUploadResults(supabase, backblaze, b2, debug) {
|
|
574
|
+
if (supabase.success || backblaze.success) {
|
|
570
575
|
return;
|
|
571
576
|
}
|
|
577
|
+
const lastError = supabase.error ?? backblaze.error;
|
|
572
578
|
if (debug) {
|
|
573
579
|
console.error(`[DEBUG] === ALL UPLOADS FAILED ===`);
|
|
574
|
-
console.error(`[DEBUG] Supabase upload: FAILED`);
|
|
575
|
-
console.error(`[DEBUG] Backblaze upload: ${b2 ?
|
|
580
|
+
console.error(`[DEBUG] Supabase upload: FAILED${supabase.error ? ` (${supabase.error.message})` : ''}`);
|
|
581
|
+
console.error(`[DEBUG] Backblaze upload: ${b2 ? `FAILED${backblaze.error ? ` (${backblaze.error.message})` : ''}` : 'NOT CONFIGURED'}`);
|
|
576
582
|
if (lastError) {
|
|
577
583
|
console.error(`[DEBUG] Final error details:`);
|
|
578
584
|
console.error(`[DEBUG] - Message: ${lastError.message}`);
|
|
@@ -580,7 +586,8 @@ function validateUploadResults(supabaseSuccess, backblazeSuccess, lastError, b2,
|
|
|
580
586
|
console.error(`[DEBUG] - Stack: ${lastError.stack}`);
|
|
581
587
|
}
|
|
582
588
|
}
|
|
583
|
-
|
|
589
|
+
const backblazePart = b2 && backblaze.error ? `Backblaze error: ${backblaze.error.message}. ` : '';
|
|
590
|
+
throw new Error(`All uploads failed. ${backblazePart}${lastError ? `Last error: ${JSON.stringify({ message: lastError.message, name: lastError.name, stack: lastError.stack })}` : 'No upload targets available.'}`);
|
|
584
591
|
}
|
|
585
592
|
/**
|
|
586
593
|
* Performs the actual file upload
|
|
@@ -618,17 +625,13 @@ async function performUpload(config) {
|
|
|
618
625
|
finalPath,
|
|
619
626
|
source,
|
|
620
627
|
});
|
|
621
|
-
let lastError = backblazeResult.error;
|
|
622
628
|
// Always upload to Supabase (re-enabled as always-on alongside Backblaze)
|
|
623
629
|
if (debug) {
|
|
624
630
|
console.log('[DEBUG] Uploading to Supabase...');
|
|
625
631
|
}
|
|
626
632
|
const supabaseResult = await uploadToSupabase(env, tempPath, source, debug);
|
|
627
|
-
if (!supabaseResult.success && supabaseResult.error) {
|
|
628
|
-
lastError = supabaseResult.error;
|
|
629
|
-
}
|
|
630
633
|
// Validate results
|
|
631
|
-
validateUploadResults(supabaseResult
|
|
634
|
+
validateUploadResults(supabaseResult, backblazeResult, b2, debug);
|
|
632
635
|
// Log upload summary
|
|
633
636
|
if (debug) {
|
|
634
637
|
console.log(`[DEBUG] Upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`);
|
|
@@ -703,13 +706,9 @@ export const uploadFlowZip = async (config) => {
|
|
|
703
706
|
finalPath,
|
|
704
707
|
source,
|
|
705
708
|
});
|
|
706
|
-
let lastError = backblazeResult.error;
|
|
707
709
|
// Always upload to Supabase (always-on alongside Backblaze)
|
|
708
710
|
const supabaseResult = await uploadToSupabase(env, tempPath, source, debug);
|
|
709
|
-
|
|
710
|
-
lastError = supabaseResult.error;
|
|
711
|
-
}
|
|
712
|
-
validateUploadResults(supabaseResult.success, backblazeResult.success, lastError, b2, debug);
|
|
711
|
+
validateUploadResults(supabaseResult, backblazeResult, b2, debug);
|
|
713
712
|
if (debug) {
|
|
714
713
|
console.log(`[DEBUG] Flow zip upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`);
|
|
715
714
|
}
|
|
@@ -733,79 +732,67 @@ export const uploadFlowZip = async (config) => {
|
|
|
733
732
|
* @param fileName - Name/path of the file
|
|
734
733
|
* @param source - Upload source descriptor (streamed from disk)
|
|
735
734
|
* @param debug - Whether debug logging is enabled
|
|
736
|
-
* @returns Promise
|
|
735
|
+
* @returns Promise resolving to true once the upload succeeds; throws the last
|
|
736
|
+
* error once transient failures have used up their retries
|
|
737
737
|
*/
|
|
738
738
|
async function uploadToBackblaze(uploadUrl, authorizationToken, fileName, source, debug) {
|
|
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
|
-
console.error(`[DEBUG] Backblaze upload failed with status ${response.status}: ${errorText}`);
|
|
778
|
-
}
|
|
779
|
-
// Don't throw and don't warn — Backblaze is the primary attempt and the
|
|
780
|
-
// Supabase fallback usually recovers. A user-facing error is raised only
|
|
781
|
-
// if every strategy fails (see validateUploadResults).
|
|
782
|
-
return false;
|
|
783
|
-
}
|
|
784
|
-
if (debug) {
|
|
785
|
-
console.log('[DEBUG] Backblaze upload successful');
|
|
786
|
-
}
|
|
787
|
-
return true;
|
|
788
|
-
}
|
|
789
|
-
catch (error) {
|
|
790
|
-
if (debug) {
|
|
791
|
-
console.error('[DEBUG] === BACKBLAZE UPLOAD EXCEPTION ===');
|
|
792
|
-
console.error('[DEBUG] Backblaze upload exception:', error);
|
|
793
|
-
console.error(`[DEBUG] Error type: ${error instanceof Error ? error.name : typeof error}`);
|
|
794
|
-
console.error(`[DEBUG] Error message: ${error instanceof Error ? error.message : String(error)}`);
|
|
795
|
-
if (error instanceof Error && error.stack) {
|
|
796
|
-
console.error(`[DEBUG] Stack trace:\n${error.stack}`);
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
// Provide more specific error messages for common network errors
|
|
800
|
-
if (error instanceof TypeError && error.message === 'fetch failed') {
|
|
739
|
+
// The API only picks the simple strategy for small binaries (large files
|
|
740
|
+
// get the multi-part path), so one transient buffer here is bounded.
|
|
741
|
+
// S3 pre-signed PUTs reject chunked transfer encoding, which rules out a
|
|
742
|
+
// plain stream body.
|
|
743
|
+
const body = await readFile(source.diskPath);
|
|
744
|
+
// Calculate SHA1 hash for Backblaze (B2 requires SHA1, not SHA256)
|
|
745
|
+
const sha1 = createHash('sha1');
|
|
746
|
+
sha1.update(body);
|
|
747
|
+
const sha1Hex = sha1.digest('hex');
|
|
748
|
+
// Detect if this is an S3 pre-signed URL (authorization token is empty)
|
|
749
|
+
const isS3PreSignedUrl = !authorizationToken || authorizationToken === '';
|
|
750
|
+
if (debug) {
|
|
751
|
+
console.log(`[DEBUG] Uploading to Backblaze URL: ${uploadUrl}`);
|
|
752
|
+
console.log(`[DEBUG] Upload method: ${isS3PreSignedUrl ? 'S3 pre-signed URL (PUT)' : 'B2 native API (POST)'}`);
|
|
753
|
+
console.log(`[DEBUG] File name: ${fileName}`);
|
|
754
|
+
console.log(`[DEBUG] File SHA1: ${sha1Hex}`);
|
|
755
|
+
}
|
|
756
|
+
// Build headers based on upload method
|
|
757
|
+
const headers = {
|
|
758
|
+
'Content-Length': body.length.toString(),
|
|
759
|
+
'Content-Type': source.contentType || 'application/octet-stream',
|
|
760
|
+
'X-Bz-Content-Sha1': sha1Hex,
|
|
761
|
+
};
|
|
762
|
+
// S3 pre-signed URLs have auth embedded in URL, native B2 uses Authorization header
|
|
763
|
+
if (!isS3PreSignedUrl) {
|
|
764
|
+
headers.Authorization = authorizationToken;
|
|
765
|
+
headers['X-Bz-File-Name'] = encodeURIComponent(fileName);
|
|
766
|
+
}
|
|
767
|
+
// No user-facing warning on a failure: validateUploadResults raises the
|
|
768
|
+
// only user-facing error, and only when every strategy fails. The thrown
|
|
769
|
+
// error reaches it through handleBackblazeUpload.
|
|
770
|
+
await withB2Retry(async () => assertB2Ok(await fetch(uploadUrl, {
|
|
771
|
+
// Zero-copy view over the buffer (new Uint8Array(buffer) would clone it).
|
|
772
|
+
body: new Uint8Array(body.buffer, body.byteOffset, body.byteLength),
|
|
773
|
+
headers,
|
|
774
|
+
method: isS3PreSignedUrl ? 'PUT' : 'POST',
|
|
775
|
+
}), 'Backblaze upload'), {
|
|
776
|
+
onRetry(attempt, error, delayMs) {
|
|
801
777
|
if (debug) {
|
|
802
|
-
console.error(
|
|
778
|
+
console.error(`[DEBUG] Backblaze upload attempt ${attempt} failed (${describeB2Error(error)}); retrying in ${delayMs}ms`);
|
|
803
779
|
}
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
780
|
+
},
|
|
781
|
+
});
|
|
782
|
+
if (debug) {
|
|
783
|
+
console.log('[DEBUG] Backblaze upload successful');
|
|
808
784
|
}
|
|
785
|
+
return true;
|
|
786
|
+
}
|
|
787
|
+
/** One line for a failed B2 attempt, including the response body when there is one. */
|
|
788
|
+
function describeB2Error(error) {
|
|
789
|
+
if (error instanceof B2HttpError)
|
|
790
|
+
return `${error.message}${error.body ? `: ${error.body.slice(0, 300)}` : ''}`;
|
|
791
|
+
if (error instanceof Error) {
|
|
792
|
+
const cause = error.cause instanceof Error ? ` (${error.cause.message})` : '';
|
|
793
|
+
return `${error.message}${cause}`;
|
|
794
|
+
}
|
|
795
|
+
return String(error);
|
|
809
796
|
}
|
|
810
797
|
/**
|
|
811
798
|
* Helper function to read a chunk from a file stream
|
|
@@ -840,33 +827,48 @@ function calculateSha1(buffer) {
|
|
|
840
827
|
return sha1.digest('hex');
|
|
841
828
|
}
|
|
842
829
|
/**
|
|
843
|
-
*
|
|
830
|
+
* Picks the upload URL for one attempt at one part. The API mints one URL per
|
|
831
|
+
* part, but each is bound to the large file rather than to a part number (the
|
|
832
|
+
* part number travels in `X-Bz-Part-Number`), so any of them can carry any
|
|
833
|
+
* part. A retry moves on to the next one, which is what B2 asks for after a
|
|
834
|
+
* 503 or a dropped connection. Parts upload one at a time, so no URL is ever
|
|
835
|
+
* in use twice at once.
|
|
836
|
+
*/
|
|
837
|
+
export function partUploadUrlFor(urls, partNumber, attempt) {
|
|
838
|
+
return urls[(partNumber - 1 + attempt - 1) % urls.length];
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Uploads a single part to Backblaze, retrying transient failures on a
|
|
842
|
+
* different upload URL each time
|
|
844
843
|
* @param config - Configuration for the part upload
|
|
845
844
|
* @returns Promise that resolves when upload completes
|
|
846
845
|
*/
|
|
847
846
|
async function uploadPartToBackblaze(config) {
|
|
848
|
-
const {
|
|
847
|
+
const { uploadPartUrls, partBuffer, partLength, sha1Hex, partNumber, totalParts, debug } = config;
|
|
849
848
|
if (debug) {
|
|
850
849
|
console.log(`[DEBUG] Uploading part ${partNumber}/${totalParts} (${(partLength / 1024 / 1024).toFixed(2)} MB, SHA1: ${sha1Hex})`);
|
|
851
850
|
}
|
|
852
851
|
try {
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
852
|
+
await withB2Retry(async (attempt) => {
|
|
853
|
+
const { authorizationToken, uploadUrl } = partUploadUrlFor(uploadPartUrls, partNumber, attempt);
|
|
854
|
+
return assertB2Ok(await fetch(uploadUrl, {
|
|
855
|
+
body: new Uint8Array(partBuffer),
|
|
856
|
+
headers: {
|
|
857
|
+
Authorization: authorizationToken,
|
|
858
|
+
'Content-Length': partLength.toString(),
|
|
859
|
+
'X-Bz-Content-Sha1': sha1Hex,
|
|
860
|
+
'X-Bz-Part-Number': partNumber.toString(),
|
|
861
|
+
},
|
|
862
|
+
method: 'POST',
|
|
863
|
+
}), `Part ${partNumber} upload`);
|
|
864
|
+
}, {
|
|
865
|
+
onRetry(attempt, error, delayMs) {
|
|
866
|
+
if (debug) {
|
|
867
|
+
console.error(`[DEBUG] Part ${partNumber} attempt ${attempt} failed (${describeB2Error(error)}); retrying on another upload URL in ${delayMs}ms`);
|
|
868
|
+
}
|
|
860
869
|
},
|
|
861
|
-
|
|
870
|
+
rotatesUrl: true,
|
|
862
871
|
});
|
|
863
|
-
if (!response.ok) {
|
|
864
|
-
const errorText = await response.text();
|
|
865
|
-
if (debug) {
|
|
866
|
-
console.error(`[DEBUG] Part ${partNumber} upload failed with status ${response.status}: ${errorText}`);
|
|
867
|
-
}
|
|
868
|
-
throw new Error(`Part ${partNumber} upload failed with status ${response.status}`);
|
|
869
|
-
}
|
|
870
872
|
}
|
|
871
873
|
catch (error) {
|
|
872
874
|
if (error instanceof TypeError && error.message === 'fetch failed') {
|
|
@@ -883,78 +885,54 @@ async function uploadPartToBackblaze(config) {
|
|
|
883
885
|
console.log(`[DEBUG] Part ${partNumber}/${totalParts} uploaded successfully`);
|
|
884
886
|
}
|
|
885
887
|
}
|
|
886
|
-
/**
|
|
887
|
-
* Logs detailed error information for Backblaze upload failures
|
|
888
|
-
* @param error - The error that occurred
|
|
889
|
-
* @param debug - Whether debug logging is enabled
|
|
890
|
-
* @returns void
|
|
891
|
-
*/
|
|
892
|
-
function logBackblazeUploadError(error, debug) {
|
|
893
|
-
if (debug) {
|
|
894
|
-
console.error('[DEBUG] === BACKBLAZE LARGE FILE UPLOAD EXCEPTION ===');
|
|
895
|
-
console.error('[DEBUG] Large file upload exception:', error);
|
|
896
|
-
console.error(`[DEBUG] Error type: ${error instanceof Error ? error.name : typeof error}`);
|
|
897
|
-
console.error(`[DEBUG] Error message: ${error instanceof Error ? error.message : String(error)}`);
|
|
898
|
-
if (error instanceof Error && error.stack) {
|
|
899
|
-
console.error(`[DEBUG] Stack trace:\n${error.stack}`);
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
// No user-facing warning: Backblaze is the primary attempt and the Supabase
|
|
903
|
-
// fallback usually recovers; validateUploadResults raises the only
|
|
904
|
-
// user-facing error, and only when every strategy fails.
|
|
905
|
-
}
|
|
906
888
|
/**
|
|
907
889
|
* Upload large file to Backblaze using multi-part upload with streaming (for files >= 5MB)
|
|
908
890
|
* Uses file streaming to avoid loading entire file into memory, preventing OOM errors on large files
|
|
909
891
|
* @param config - Configuration object for the large file upload
|
|
910
|
-
* @returns Promise
|
|
892
|
+
* @returns Promise resolving to true once the upload succeeds; throws the
|
|
893
|
+
* error of the part (or finish call) that failed. No user-facing warning:
|
|
894
|
+
* validateUploadResults raises the only user-facing error, and only when
|
|
895
|
+
* every strategy fails.
|
|
911
896
|
*/
|
|
912
897
|
async function uploadLargeFileToBackblaze(config) {
|
|
913
898
|
const { apiUrl, auth, fileId, uploadPartUrls, filePath, fileSize, debug } = config;
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
const partLength = end - start;
|
|
928
|
-
if (debug) {
|
|
929
|
-
console.log(`[DEBUG] Reading part ${partNumber}/${uploadPartUrls.length} bytes ${start}-${end}`);
|
|
930
|
-
}
|
|
931
|
-
const partBuffer = await readFileChunk(filePath, start, end);
|
|
932
|
-
const sha1Hex = calculateSha1(partBuffer);
|
|
933
|
-
partSha1Array.push(sha1Hex);
|
|
934
|
-
await uploadPartToBackblaze({
|
|
935
|
-
authorizationToken: uploadPartUrls[i].authorizationToken,
|
|
936
|
-
debug,
|
|
937
|
-
partBuffer,
|
|
938
|
-
partLength,
|
|
939
|
-
partNumber,
|
|
940
|
-
sha1Hex,
|
|
941
|
-
totalParts: uploadPartUrls.length,
|
|
942
|
-
uploadUrl: uploadPartUrls[i].uploadUrl,
|
|
943
|
-
});
|
|
944
|
-
}
|
|
899
|
+
const partSha1Array = [];
|
|
900
|
+
const partSize = Math.ceil(fileSize / uploadPartUrls.length);
|
|
901
|
+
if (debug) {
|
|
902
|
+
console.log(`[DEBUG] Uploading large file in ${uploadPartUrls.length} parts (streaming mode)`);
|
|
903
|
+
console.log(`[DEBUG] Part size: ${(partSize / 1024 / 1024).toFixed(2)} MB`);
|
|
904
|
+
console.log(`[DEBUG] Reading from: ${filePath}`);
|
|
905
|
+
}
|
|
906
|
+
// Upload each part using streaming to avoid loading entire file into memory
|
|
907
|
+
for (let i = 0; i < uploadPartUrls.length; i++) {
|
|
908
|
+
const partNumber = i + 1;
|
|
909
|
+
const start = i * partSize;
|
|
910
|
+
const end = Math.min(start + partSize, fileSize);
|
|
911
|
+
const partLength = end - start;
|
|
945
912
|
if (debug) {
|
|
946
|
-
console.log(
|
|
947
|
-
console.log(`[DEBUG] Finalizing ${partSha1Array.length} parts with fileId: ${fileId}`);
|
|
913
|
+
console.log(`[DEBUG] Reading part ${partNumber}/${uploadPartUrls.length} bytes ${start}-${end}`);
|
|
948
914
|
}
|
|
949
|
-
await
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
915
|
+
const partBuffer = await readFileChunk(filePath, start, end);
|
|
916
|
+
const sha1Hex = calculateSha1(partBuffer);
|
|
917
|
+
partSha1Array.push(sha1Hex);
|
|
918
|
+
await uploadPartToBackblaze({
|
|
919
|
+
debug,
|
|
920
|
+
partBuffer,
|
|
921
|
+
partLength,
|
|
922
|
+
partNumber,
|
|
923
|
+
sha1Hex,
|
|
924
|
+
totalParts: uploadPartUrls.length,
|
|
925
|
+
uploadPartUrls,
|
|
926
|
+
});
|
|
953
927
|
}
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
928
|
+
if (debug) {
|
|
929
|
+
console.log('[DEBUG] Finishing large file upload...');
|
|
930
|
+
console.log(`[DEBUG] Finalizing ${partSha1Array.length} parts with fileId: ${fileId}`);
|
|
957
931
|
}
|
|
932
|
+
await ApiGateway.finishLargeFile(apiUrl, auth, fileId, partSha1Array);
|
|
933
|
+
if (debug)
|
|
934
|
+
console.log('[DEBUG] Large file upload completed successfully');
|
|
935
|
+
return true;
|
|
958
936
|
}
|
|
959
937
|
async function getFileHashFromPath(filePath) {
|
|
960
938
|
const hash = createHash('sha256');
|
|
@@ -37,6 +37,12 @@ interface IFlowSequence {
|
|
|
37
37
|
continueOnFailure?: boolean;
|
|
38
38
|
flows: string[];
|
|
39
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* How many flows opt into the extended test runtime (up to 20 minutes, billed
|
|
42
|
+
* accepts: YAML `true` or the string `'true'`.
|
|
43
|
+
* accepts: YAML `true` or the string `'true'`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function countExtendedRuntimeFlows(flowOverrides: Record<string, Record<string, unknown>>): number;
|
|
40
46
|
/**
|
|
41
47
|
* Generate execution plan for test flows
|
|
42
48
|
*
|
|
@@ -83,6 +83,14 @@ function extractDeviceCloudOverrides(config) {
|
|
|
83
83
|
}
|
|
84
84
|
return overrides;
|
|
85
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* How many flows opt into the extended test runtime (up to 20 minutes, billed
|
|
88
|
+
* accepts: YAML `true` or the string `'true'`.
|
|
89
|
+
* accepts: YAML `true` or the string `'true'`.
|
|
90
|
+
*/
|
|
91
|
+
export function countExtendedRuntimeFlows(flowOverrides) {
|
|
92
|
+
return Object.values(flowOverrides).filter(({ EXTENDED_RUNTIME }) => EXTENDED_RUNTIME === true || EXTENDED_RUNTIME === 'true').length;
|
|
93
|
+
}
|
|
86
94
|
/**
|
|
87
95
|
* Generate execution plan for a single flow file
|
|
88
96
|
* @param normalizedInput - Normalized path to the flow file
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
export type CpuArchitecture = 'arm' | 'x86';
|
|
1
2
|
export interface TAppMetadata {
|
|
3
|
+
/** APK only: the native ABIs shipped under `lib/<abi>/`, sorted. */
|
|
4
|
+
abis?: string[];
|
|
2
5
|
appId: string;
|
|
6
|
+
/** APK only: the CPU families the APK can run on. See `apkArchitectures`. */
|
|
7
|
+
architectures?: CpuArchitecture[];
|
|
3
8
|
platform: 'android' | 'ios';
|
|
4
9
|
}
|
|
5
10
|
/**
|
|
@@ -9,6 +14,14 @@ export interface IMetadataExtractor {
|
|
|
9
14
|
canHandle(filePath: string): boolean;
|
|
10
15
|
extract(filePath: string): Promise<TAppMetadata>;
|
|
11
16
|
}
|
|
17
|
+
/** The native ABIs in an APK: each `lib/<abi>/` directory that holds a file. */
|
|
18
|
+
export declare function apkAbis(entryNames: string[]): string[];
|
|
19
|
+
/**
|
|
20
|
+
* The CPU families an APK can run on, from its native ABIs. An APK with no
|
|
21
|
+
* native code runs on both. ABIs outside arm and x86 (mips, riscv64) are
|
|
22
|
+
* ignored, so an APK that ships only those gets an empty list.
|
|
23
|
+
*/
|
|
24
|
+
export declare function apkArchitectures(abis: string[]): CpuArchitecture[];
|
|
12
25
|
/**
|
|
13
26
|
* Extracts metadata from Android APK files
|
|
14
27
|
*/
|
|
@@ -23,6 +23,34 @@ function parseInfoPlist(buffer) {
|
|
|
23
23
|
}
|
|
24
24
|
return data;
|
|
25
25
|
}
|
|
26
|
+
const ABI_ARCHITECTURE = {
|
|
27
|
+
armeabi: 'arm',
|
|
28
|
+
'armeabi-v7a': 'arm',
|
|
29
|
+
'arm64-v8a': 'arm',
|
|
30
|
+
x86: 'x86',
|
|
31
|
+
x86_64: 'x86',
|
|
32
|
+
};
|
|
33
|
+
/** The native ABIs in an APK: each `lib/<abi>/` directory that holds a file. */
|
|
34
|
+
export function apkAbis(entryNames) {
|
|
35
|
+
const abis = new Set();
|
|
36
|
+
for (const name of entryNames) {
|
|
37
|
+
const match = /^lib\/([^/]+)\/[^/]+$/.exec(name);
|
|
38
|
+
if (match)
|
|
39
|
+
abis.add(match[1]);
|
|
40
|
+
}
|
|
41
|
+
return [...abis].sort();
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The CPU families an APK can run on, from its native ABIs. An APK with no
|
|
45
|
+
* native code runs on both. ABIs outside arm and x86 (mips, riscv64) are
|
|
46
|
+
* ignored, so an APK that ships only those gets an empty list.
|
|
47
|
+
*/
|
|
48
|
+
export function apkArchitectures(abis) {
|
|
49
|
+
if (abis.length === 0)
|
|
50
|
+
return ['arm', 'x86'];
|
|
51
|
+
const found = new Set(abis.map((abi) => ABI_ARCHITECTURE[abi]).filter(Boolean));
|
|
52
|
+
return ['arm', 'x86'].filter((arch) => found.has(arch));
|
|
53
|
+
}
|
|
26
54
|
/**
|
|
27
55
|
* Extracts metadata from Android APK files
|
|
28
56
|
*/
|
|
@@ -34,7 +62,13 @@ export class AndroidMetadataExtractor {
|
|
|
34
62
|
const zip = new StreamZip.async({ file: filePath });
|
|
35
63
|
try {
|
|
36
64
|
const manifest = await zip.entryData('AndroidManifest.xml');
|
|
37
|
-
|
|
65
|
+
const abis = apkAbis(Object.keys(await zip.entries()));
|
|
66
|
+
return {
|
|
67
|
+
abis,
|
|
68
|
+
appId: readManifestPackage(manifest),
|
|
69
|
+
architectures: apkArchitectures(abis),
|
|
70
|
+
platform: 'android',
|
|
71
|
+
};
|
|
38
72
|
}
|
|
39
73
|
finally {
|
|
40
74
|
await zip.close().catch(() => { });
|
|
@@ -105,6 +105,8 @@ export interface DeviceCommandResult {
|
|
|
105
105
|
/** Each flow of a run. Absent from APIs older than this field. */
|
|
106
106
|
flows?: DeviceFlowResult[];
|
|
107
107
|
output?: string;
|
|
108
|
+
/** A failed run: the app's visible text just after it failed. */
|
|
109
|
+
screen_text?: string[];
|
|
108
110
|
success: boolean;
|
|
109
111
|
}
|
|
110
112
|
/** One element of the compact screen (Maestro's key names). */
|
|
@@ -112,8 +114,13 @@ export interface DeviceScreenElement {
|
|
|
112
114
|
/** Bounds, "[left,top][right,bottom]". */
|
|
113
115
|
b: string;
|
|
114
116
|
a11y?: string;
|
|
117
|
+
checked?: true;
|
|
118
|
+
/** False when disabled; absent when enabled. */
|
|
119
|
+
enabled?: false;
|
|
120
|
+
focused?: true;
|
|
115
121
|
hint?: string;
|
|
116
122
|
rid?: string;
|
|
123
|
+
selected?: true;
|
|
117
124
|
txt?: string;
|
|
118
125
|
}
|
|
119
126
|
/** GET .../inspect: the elements worth targeting, and what each key means. */
|
|
@@ -122,6 +129,13 @@ export interface DeviceScreen {
|
|
|
122
129
|
/** False when no new frame came in time; this is then the latest. */
|
|
123
130
|
fresh: boolean;
|
|
124
131
|
height: number;
|
|
132
|
+
/** Keyboard keys and System UI left out (only when some were); --all shows them. */
|
|
133
|
+
hidden?: {
|
|
134
|
+
keyboard: number;
|
|
135
|
+
system: number;
|
|
136
|
+
};
|
|
137
|
+
/** An on-screen keyboard is showing (Android). */
|
|
138
|
+
keyboard_open?: true;
|
|
125
139
|
keys: Record<string, string>;
|
|
126
140
|
width: number;
|
|
127
141
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
|
+
import type { CpuArchitecture } from './services/metadata-extractor.service.js';
|
|
1
2
|
import type { BinaryEnvelope } from './utils/envelope.js';
|
|
2
3
|
export type TAppMetadata = {
|
|
4
|
+
/**
|
|
5
|
+
* APK only: the native ABIs under `lib/<abi>/` (e.g. `arm64-v8a`, `x86_64`).
|
|
6
|
+
* Stored on `binaries.metadata.abis`. Empty when the APK has no native code.
|
|
7
|
+
*/
|
|
8
|
+
abis?: string[];
|
|
3
9
|
appId: string;
|
|
10
|
+
/**
|
|
11
|
+
* APK only: the CPU families the APK can run on, `arm`, `x86` or both.
|
|
12
|
+
* Stored on `binaries.metadata.architectures`. Both when it has no native code.
|
|
13
|
+
*/
|
|
14
|
+
architectures?: CpuArchitecture[];
|
|
4
15
|
platform: 'android' | 'ios';
|
|
5
16
|
/**
|
|
6
17
|
* Present when the binary was client-side envelope-encrypted before upload
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retries for direct-to-Backblaze uploads.
|
|
3
|
+
*
|
|
4
|
+
* B2 expects clients to retry: an upload can be answered with 408, 429 or a
|
|
5
|
+
* 5xx, or have its connection dropped, and B2's own guidance is to back off
|
|
6
|
+
* and try again (for a large-file part, on a different upload URL). The CLI
|
|
7
|
+
* used to make exactly one attempt, so a single dropped B2 request failed the
|
|
8
|
+
* B2 upload outright and left the Supabase upload as the only path.
|
|
9
|
+
*/
|
|
10
|
+
export declare const B2_RETRY: {
|
|
11
|
+
/** Total attempts per request, the first included. */
|
|
12
|
+
attempts: number;
|
|
13
|
+
baseDelayMs: number;
|
|
14
|
+
maxDelayMs: number;
|
|
15
|
+
};
|
|
16
|
+
/** A B2 (or S3-compatible) response that was not 2xx. */
|
|
17
|
+
export declare class B2HttpError extends Error {
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly body: string;
|
|
20
|
+
constructor(message: string, status: number, body: string);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Whether a failed attempt is worth repeating. Network errors (fetch throws a
|
|
24
|
+
* TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
|
|
25
|
+
* the next attempt uses a different upload URL, which B2 hands out with its
|
|
26
|
+
* own token: on the same URL it would fail the same way.
|
|
27
|
+
*/
|
|
28
|
+
export declare function isRetryableB2Error(error: unknown, opts?: {
|
|
29
|
+
rotatesUrl?: boolean;
|
|
30
|
+
}): boolean;
|
|
31
|
+
/** Exponential backoff with full jitter, capped at `maxDelayMs`. */
|
|
32
|
+
export declare function b2RetryDelayMs(attempt: number, random?: () => number): number;
|
|
33
|
+
export interface B2RetryOptions {
|
|
34
|
+
/** Each attempt gets a fresh upload URL, so a 401 is worth retrying. */
|
|
35
|
+
rotatesUrl?: boolean;
|
|
36
|
+
/** Called before each retry; the debug logging hook. */
|
|
37
|
+
onRetry?: (attempt: number, error: unknown, delayMs: number) => void;
|
|
38
|
+
/** Test seam. */
|
|
39
|
+
sleep?: (ms: number) => Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Run `attemptFn` until it resolves, a non-retryable error is thrown, or
|
|
43
|
+
* `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
|
|
44
|
+
* number so a caller can pick a different upload URL each time. The last
|
|
45
|
+
* error is rethrown unchanged.
|
|
46
|
+
*/
|
|
47
|
+
export declare function withB2Retry<T>(attemptFn: (attempt: number) => Promise<T>, opts?: B2RetryOptions): Promise<T>;
|
|
48
|
+
/** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
|
|
49
|
+
export declare function assertB2Ok(response: Response, what: string): Promise<Response>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retries for direct-to-Backblaze uploads.
|
|
3
|
+
*
|
|
4
|
+
* B2 expects clients to retry: an upload can be answered with 408, 429 or a
|
|
5
|
+
* 5xx, or have its connection dropped, and B2's own guidance is to back off
|
|
6
|
+
* and try again (for a large-file part, on a different upload URL). The CLI
|
|
7
|
+
* used to make exactly one attempt, so a single dropped B2 request failed the
|
|
8
|
+
* B2 upload outright and left the Supabase upload as the only path.
|
|
9
|
+
*/
|
|
10
|
+
export const B2_RETRY = {
|
|
11
|
+
/** Total attempts per request, the first included. */
|
|
12
|
+
attempts: 4,
|
|
13
|
+
baseDelayMs: 1000,
|
|
14
|
+
maxDelayMs: 8000,
|
|
15
|
+
};
|
|
16
|
+
/** A B2 (or S3-compatible) response that was not 2xx. */
|
|
17
|
+
export class B2HttpError extends Error {
|
|
18
|
+
status;
|
|
19
|
+
body;
|
|
20
|
+
constructor(message, status, body) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.body = body;
|
|
24
|
+
this.name = 'B2HttpError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Whether a failed attempt is worth repeating. Network errors (fetch throws a
|
|
29
|
+
* TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
|
|
30
|
+
* the next attempt uses a different upload URL, which B2 hands out with its
|
|
31
|
+
* own token: on the same URL it would fail the same way.
|
|
32
|
+
*/
|
|
33
|
+
export function isRetryableB2Error(error, opts = {}) {
|
|
34
|
+
if (error instanceof B2HttpError) {
|
|
35
|
+
const { status } = error;
|
|
36
|
+
if (status === 401)
|
|
37
|
+
return Boolean(opts.rotatesUrl);
|
|
38
|
+
return status === 408 || status === 429 || status >= 500;
|
|
39
|
+
}
|
|
40
|
+
return error instanceof TypeError;
|
|
41
|
+
}
|
|
42
|
+
/** Exponential backoff with full jitter, capped at `maxDelayMs`. */
|
|
43
|
+
export function b2RetryDelayMs(attempt, random = Math.random) {
|
|
44
|
+
const ceiling = Math.min(B2_RETRY.maxDelayMs, B2_RETRY.baseDelayMs * 2 ** (attempt - 1));
|
|
45
|
+
return Math.round(ceiling / 2 + (random() * ceiling) / 2);
|
|
46
|
+
}
|
|
47
|
+
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
48
|
+
setTimeout(resolve, ms);
|
|
49
|
+
});
|
|
50
|
+
/**
|
|
51
|
+
* Run `attemptFn` until it resolves, a non-retryable error is thrown, or
|
|
52
|
+
* `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
|
|
53
|
+
* number so a caller can pick a different upload URL each time. The last
|
|
54
|
+
* error is rethrown unchanged.
|
|
55
|
+
*/
|
|
56
|
+
export async function withB2Retry(attemptFn, opts = {}) {
|
|
57
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
58
|
+
for (let attempt = 1;; attempt++) {
|
|
59
|
+
try {
|
|
60
|
+
return await attemptFn(attempt);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (attempt >= B2_RETRY.attempts || !isRetryableB2Error(error, opts))
|
|
64
|
+
throw error;
|
|
65
|
+
const delayMs = b2RetryDelayMs(attempt);
|
|
66
|
+
opts.onRetry?.(attempt, error, delayMs);
|
|
67
|
+
await sleep(delayMs);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
|
|
72
|
+
export async function assertB2Ok(response, what) {
|
|
73
|
+
if (response.ok)
|
|
74
|
+
return response;
|
|
75
|
+
const body = await response.text().catch(() => '');
|
|
76
|
+
throw new B2HttpError(`${what} failed with status ${response.status}`, response.status, body);
|
|
77
|
+
}
|
package/dist/utils/device-run.js
CHANGED
|
@@ -65,6 +65,14 @@ export function runFailureMessage(result, report) {
|
|
|
65
65
|
* (a single flow's report has no file name).
|
|
66
66
|
*/
|
|
67
67
|
export function printRunResult(log, passed, result, label) {
|
|
68
|
+
printOutcome(log, passed, result, label);
|
|
69
|
+
// What the app showed after the failure: why an assertion missed.
|
|
70
|
+
if (!passed && result.screen_text?.length) {
|
|
71
|
+
log(ui.section('On screen after the failure'));
|
|
72
|
+
log(ui.branch(result.screen_text.map((t) => `"${t}"`)));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function printOutcome(log, passed, result, label) {
|
|
68
76
|
const report = parseRunReport(result);
|
|
69
77
|
if (!report || report.flows.length === 0) {
|
|
70
78
|
log(passed ? ui.success('Flow passed') : `${ui.statusSymbol('FAILED')} Flow failed`);
|
package/package.json
CHANGED