Skip to content

Commit 6d8e1dd

Browse files
authored
Fix Wasm build cache mismatch in ResidentWebRunner and browser 404 fallbacks (flutter#190786)
This pull request resolves unnecessary Wasm recompilations during `flutter run` by removing hardcoded compiler variables that mismatched with `flutter build`, and ensures missing web assets correctly return HTTP 404s to prevent browser instantiation crashes. Specifically: * Removed explicitly hardcoded `optimizationLevel` and `stripWasm` defaults in `ResidentWebRunner`'s `WasmCompilerConfig`. This allows it to gracefully inherit dynamic defaults downstream, achieving cache key parity with `flutter build web --wasm`. * Updated `ReleaseAssetServer` to properly return `404 Not Found` for missing static file requests (`.wasm`, `.mjs`, `.js`, `assets/`, `canvaskit/`) instead of serving `index.html`. This prevents obscure `WebAssembly.instantiate` syntax errors in the browser when caching or compilation pipelines fail to produce an artifact. Related to flutter#67053.
1 parent 9b797f6 commit 6d8e1dd

4 files changed

Lines changed: 233 additions & 5 deletions

File tree

‎packages/flutter_tools/lib/src/isolated/release_asset_server.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ class ReleaseAssetServer {
5252
// contains generated, publishable assets.
5353
static const Set<String> _sourceMapExtensions = <String>{'.dart', '.map'};
5454

55+
static const Set<String> _staticAssetExtensions = <String>{
56+
'.wasm',
57+
'.mjs',
58+
'.js',
59+
'.css',
60+
'.json',
61+
'.ico',
62+
'.map',
63+
};
64+
5565
// Locations where source files, assets, or source maps may be located, paired
5666
// with the set of file extensions allowed to be served from each location. An
5767
// empty set means no extension restriction is applied.
@@ -111,7 +121,24 @@ class ReleaseAssetServer {
111121
);
112122
}
113123

124+
// Requests for specific compiled web build artifacts (.wasm, .mjs, .js, assets/, canvaskit/)
125+
// that do not exist on disk must return 404 Not Found so browser entrypoint fallback
126+
// functions properly. SPA index.html fallback is preserved for navigation routes and
127+
// unallowed project path fallthroughs.
128+
final String cleanPath = requestPath.startsWith('/') ? requestPath.substring(1) : requestPath;
129+
final String extension = _fileSystem.path.extension(cleanPath);
130+
final bool isMissingStaticAsset =
131+
_staticAssetExtensions.contains(extension) ||
132+
cleanPath.startsWith('assets/') ||
133+
cleanPath.startsWith('canvaskit/');
134+
if (isMissingStaticAsset) {
135+
return shelf.Response.notFound('');
136+
}
137+
114138
final File file = _fileSystem.file(_fileSystem.path.join(_webBuildDirectory!, 'index.html'));
139+
if (!file.existsSync()) {
140+
return shelf.Response.notFound('');
141+
}
115142
return shelf.Response.ok(
116143
file.readAsBytesSync(),
117144
headers: <String, String>{

‎packages/flutter_tools/lib/src/isolated/resident_web_runner.dart‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -429,11 +429,7 @@ class ResidentWebRunner extends ResidentRunner {
429429

430430
WebCompilerConfig get _compilerConfig {
431431
if (debuggingOptions.webUseWasm) {
432-
return WasmCompilerConfig(
433-
optimizationLevel: 0,
434-
stripWasm: false,
435-
renderer: debuggingOptions.webRenderer,
436-
);
432+
return WasmCompilerConfig(renderer: debuggingOptions.webRenderer);
437433
}
438434
return JsCompilerConfig.run(
439435
nativeNullAssertions: debuggingOptions.nativeNullAssertions,

‎packages/flutter_tools/test/general.shard/resident_web_runner_test.dart‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import 'package:flutter_tools/src/base/terminal.dart';
1919
import 'package:flutter_tools/src/base/time.dart';
2020
import 'package:flutter_tools/src/build_info.dart';
2121
import 'package:flutter_tools/src/build_system/build_system.dart';
22+
import 'package:flutter_tools/src/build_system/targets/web.dart';
2223
import 'package:flutter_tools/src/build_system/tools/shader_compiler.dart';
2324
import 'package:flutter_tools/src/bundle.dart';
2425
import 'package:flutter_tools/src/compile.dart';
@@ -32,6 +33,7 @@ import 'package:flutter_tools/src/project.dart';
3233
import 'package:flutter_tools/src/resident_runner.dart';
3334
import 'package:flutter_tools/src/vmservice.dart';
3435
import 'package:flutter_tools/src/web/chrome.dart';
36+
import 'package:flutter_tools/src/web/compiler_config.dart';
3537
import 'package:flutter_tools/src/web/devfs_config.dart';
3638
import 'package:flutter_tools/src/web/web_device.dart';
3739
import 'package:package_config/package_config.dart';
@@ -2338,6 +2340,108 @@ flutter:
23382340
},
23392341
);
23402342
});
2343+
2344+
group('WasmCompilerConfig defaults', () {
2345+
WebCompilerConfig? capturedConfig;
2346+
2347+
testUsingContext(
2348+
'ResidentWebRunner passes WasmCompilerConfig with dynamic cache-equivalent defaults in release mode',
2349+
() async {
2350+
capturedConfig = null;
2351+
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
2352+
setupMocks();
2353+
2354+
final residentWebRunner = ResidentWebRunner(
2355+
flutterDevice,
2356+
flutterProject: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory),
2357+
debuggingOptions: DebuggingOptions.enabled(BuildInfo.release, webUseWasm: true),
2358+
stayResident: false,
2359+
fileSystem: fileSystem,
2360+
logger: BufferLogger.test(),
2361+
terminal: Terminal.test(),
2362+
platform: FakePlatform(),
2363+
outputPreferences: OutputPreferences.test(),
2364+
analytics: globals.analytics,
2365+
systemClock: globals.systemClock,
2366+
);
2367+
2368+
expect(await residentWebRunner.run(), 0);
2369+
expect(capturedConfig, isA<WasmCompilerConfig>());
2370+
final wasmConfig = capturedConfig! as WasmCompilerConfig;
2371+
2372+
// Relies on `WasmCompilerConfig` native defaults to maintain cache key parity with `flutter build`.
2373+
expect(wasmConfig.optimizationLevel, isNull);
2374+
expect(wasmConfig.stripWasm, isTrue);
2375+
2376+
// Validates the underlying `toCommandOptions` correctly resolves for release mode.
2377+
final List<String> commandOptions = wasmConfig.toCommandOptions(BuildMode.release);
2378+
expect(commandOptions, contains('-O2'));
2379+
expect(commandOptions, contains('--strip-wasm'));
2380+
},
2381+
overrides: <Type, Generator>{
2382+
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (
2383+
Target target,
2384+
Environment environment,
2385+
) {
2386+
if (target is WebServiceWorker) {
2387+
capturedConfig = target.compileConfigs.first;
2388+
}
2389+
}),
2390+
FileSystem: () => fileSystem,
2391+
ProcessManager: () => processManager,
2392+
Pub: ThrowingPub.new,
2393+
},
2394+
);
2395+
2396+
testUsingContext(
2397+
'ResidentWebRunner passes WasmCompilerConfig with dynamic cache-equivalent defaults in debug mode',
2398+
() async {
2399+
capturedConfig = null;
2400+
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[]);
2401+
setupMocks();
2402+
2403+
final residentWebRunner = ResidentWebRunner(
2404+
flutterDevice,
2405+
flutterProject: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory),
2406+
debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, webUseWasm: true),
2407+
stayResident: false,
2408+
fileSystem: fileSystem,
2409+
logger: BufferLogger.test(),
2410+
terminal: Terminal.test(),
2411+
platform: FakePlatform(),
2412+
outputPreferences: OutputPreferences.test(),
2413+
analytics: globals.analytics,
2414+
systemClock: globals.systemClock,
2415+
);
2416+
2417+
expect(await residentWebRunner.run(), 0);
2418+
expect(capturedConfig, isA<WasmCompilerConfig>());
2419+
final wasmConfig = capturedConfig! as WasmCompilerConfig;
2420+
2421+
// Relies on `WasmCompilerConfig` native defaults to maintain cache key parity with `flutter build`.
2422+
expect(wasmConfig.optimizationLevel, isNull);
2423+
expect(wasmConfig.stripWasm, isTrue);
2424+
2425+
// Validates the underlying `toCommandOptions` correctly resolves for debug mode.
2426+
final List<String> commandOptions = wasmConfig.toCommandOptions(BuildMode.debug);
2427+
expect(commandOptions, contains('-O0'));
2428+
expect(commandOptions, contains('--no-strip-wasm'));
2429+
},
2430+
overrides: <Type, Generator>{
2431+
BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (
2432+
Target target,
2433+
Environment environment,
2434+
) {
2435+
if (target is WebServiceWorker) {
2436+
capturedConfig = target.compileConfigs.first;
2437+
}
2438+
}),
2439+
FileSystem: () => fileSystem,
2440+
ProcessManager: () => processManager,
2441+
Pub: ThrowingPub.new,
2442+
},
2443+
);
2444+
});
23412445
}
23422446

23432447
ResidentRunner setUpResidentRunner(

‎packages/flutter_tools/test/general.shard/web/web_asset_server_test.dart‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,5 +770,106 @@ void main() {
770770
},
771771
);
772772
});
773+
testWithoutContext(
774+
'release asset server returns 404 for missing static file asset requests across all static cases',
775+
() async {
776+
final assetServer = ReleaseAssetServer(
777+
Uri.base,
778+
fileSystem: fileSystem,
779+
platform: platform,
780+
flutterRoot: '/flutter',
781+
webBuildDirectory: 'build/web',
782+
needsCoopCoep: true,
783+
);
784+
785+
// Populate build/web with index.html only
786+
fileSystem.file('build/web/index.html')
787+
..createSync(recursive: true)
788+
..writeAsStringSync('<html></html>');
789+
790+
// Case 1: assets/ prefix missing
791+
final Response assetsResponse = await assetServer.handle(
792+
Request('GET', Uri.parse('http://localhost:8080/assets/icons/missing.png')),
793+
);
794+
expect(assetsResponse.statusCode, equals(404));
795+
796+
// Case 2: canvaskit/ prefix missing
797+
final Response canvaskitResponse = await assetServer.handle(
798+
Request('GET', Uri.parse('http://localhost:8080/canvaskit/skwasm.wasm')),
799+
);
800+
expect(canvaskitResponse.statusCode, equals(404));
801+
802+
// Case 3: *.wasm file missing
803+
final Response wasmResponse = await assetServer.handle(
804+
Request('GET', Uri.parse('http://localhost:8080/main.dart.wasm')),
805+
);
806+
expect(wasmResponse.statusCode, equals(404));
807+
808+
// Case 4: *.mjs file missing
809+
final Response mjsResponse = await assetServer.handle(
810+
Request('GET', Uri.parse('http://localhost:8080/main.dart.mjs')),
811+
);
812+
expect(mjsResponse.statusCode, equals(404));
813+
814+
// Case 5: *.js file missing
815+
final Response jsResponse = await assetServer.handle(
816+
Request('GET', Uri.parse('http://localhost:8080/main.dart.js')),
817+
);
818+
expect(jsResponse.statusCode, equals(404));
819+
820+
// Case 6: *.css file missing
821+
final Response cssResponse = await assetServer.handle(
822+
Request('GET', Uri.parse('http://localhost:8080/styles.css')),
823+
);
824+
expect(cssResponse.statusCode, equals(404));
825+
826+
// Case 7: *.json file missing
827+
final Response jsonResponse = await assetServer.handle(
828+
Request('GET', Uri.parse('http://localhost:8080/manifest.json')),
829+
);
830+
expect(jsonResponse.statusCode, equals(404));
831+
832+
// Case 8: *.ico file missing
833+
final Response icoResponse = await assetServer.handle(
834+
Request('GET', Uri.parse('http://localhost:8080/favicon.ico')),
835+
);
836+
expect(icoResponse.statusCode, equals(404));
837+
838+
// Case 9: *.map file missing
839+
final Response mapResponse = await assetServer.handle(
840+
Request('GET', Uri.parse('http://localhost:8080/main.dart.js.map')),
841+
);
842+
expect(mapResponse.statusCode, equals(404));
843+
},
844+
);
845+
846+
testWithoutContext(
847+
'release asset server serves index.html SPA fallback for route paths without file extensions',
848+
() async {
849+
final assetServer = ReleaseAssetServer(
850+
Uri.base,
851+
fileSystem: fileSystem,
852+
platform: platform,
853+
flutterRoot: '/flutter',
854+
webBuildDirectory: 'build/web',
855+
needsCoopCoep: false,
856+
);
857+
858+
fileSystem.file('build/web/index.html')
859+
..createSync(recursive: true)
860+
..writeAsStringSync('<html>index</html>');
861+
862+
// Client-side route paths like /settings, /assets, or /canvaskit must fall back to index.html
863+
for (final route in <String>['/settings', '/assets', '/canvaskit']) {
864+
final Response routeResponse = await assetServer.handle(
865+
Request('GET', Uri.parse('http://localhost:8080$route')),
866+
);
867+
868+
expect(routeResponse.statusCode, equals(200));
869+
expect(routeResponse.headers['Content-Type'], equals('text/html'));
870+
expect(await routeResponse.readAsString(), equals('<html>index</html>'));
871+
}
872+
},
873+
);
773874
});
774875
}

0 commit comments

Comments
 (0)