Skip to content

Commit 2bee6bc

Browse files
RobertHerholdfacebook-github-bot
authored andcommitted
Keep the dev server revision of each bundle and hot update (#59985)
Summary: The dev server labels every bundle response with the revision of the module graph it was built from (`X-Metro-Delta-ID`) and every hot update with a `revisionId`, but React Native drops both, so development tooling cannot tell which revision of the app's JavaScript is running. This keeps them where tooling can read them, through the hooks React Native already has: - iOS: `RCTJavaScriptLoader` keeps a downloaded bundle's `X-Metro-Delta-ID` as `RCTSource.revisionId` (nil for a bundle read from disk or served without the header). An `RCTHostDelegate` that loads bundles itself sees it with the source. - Android: `BundleDownloader.BundleInfo` keeps it as `revisionId`, and includes it in its JSON, which the `DOWNLOAD_END` performance marker already carries. - Both: when Metro finishes a batch of updates (`update-done`), `HMRClient` reports each update's `revisionId` to an optional, development-only `global.__HMR_UPDATE_REPORTER__`, next to the existing Fast Refresh completion events. A reporter that throws is logged as a warning and does not stop the update. Changelog: [iOS][Added] - Expose a dev server bundle's revision as `RCTSource.revisionId` [Android][Added] - Expose a dev server bundle's revision as `BundleDownloader.BundleInfo.revisionId` [General][Added] - Report each Fast Refresh update's revision to an optional development-only `global.__HMR_UPDATE_REPORTER__` Differential Revision: D131359967
1 parent ce56c6c commit 2bee6bc

12 files changed

Lines changed: 418 additions & 5 deletions

File tree

‎packages/react-native/Libraries/Utilities/HMRClient.js‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ const invariant = require('invariant');
2020
const MetroHMRClient = require('metro-runtime/src/modules/HMRClient');
2121
const prettyFormat = require('pretty-format');
2222

23+
// Internal to React Native's development tooling; it can change without notice.
24+
declare var global: {
25+
__HMR_UPDATE_REPORTER__?: {
26+
onUpdate: (update: Readonly<{revisionId: ?string, ...}>) => void,
27+
},
28+
...
29+
};
30+
2331
const pendingEntryPoints = [];
2432
let hmrClient = null;
2533
let hmrUnavailableReason: string | null = null;
@@ -224,6 +232,7 @@ Error: ${e.message}`;
224232
});
225233

226234
let pendingUpdatesCount = 0;
235+
let updatedRevisionIds: Array<?string> = [];
227236
let lastMarkerChangeId: string | null = null;
228237
client.on('update-start', ({isInitialUpdate}) => {
229238
pendingUpdatesCount++;
@@ -235,15 +244,21 @@ Error: ${e.message}`;
235244
}
236245
});
237246

238-
client.on('update', ({isInitialUpdate}) => {
247+
client.on('update', ({isInitialUpdate, revisionId}) => {
239248
if (client.isEnabled() && !isInitialUpdate) {
240249
dismissRedbox();
241250
LogBox.clearAllLogs();
242251
}
252+
// The client applied the update before this listener runs, or stashed it
253+
// until Fast Refresh is enabled. An update that throws is not recorded.
254+
updatedRevisionIds.push(revisionId);
243255
});
244256

245257
client.on('update-done', body => {
246258
pendingUpdatesCount--;
259+
const revisionIds = updatedRevisionIds;
260+
updatedRevisionIds = [];
261+
revisionIds.forEach(reportUpdate);
247262
if (pendingUpdatesCount === 0) {
248263
DevLoadingView.hide();
249264
const changeId = body?.changeId;
@@ -396,6 +411,14 @@ function showCompileError() {
396411
throw error;
397412
}
398413

414+
function reportUpdate(revisionId: ?string) {
415+
try {
416+
global.__HMR_UPDATE_REPORTER__?.onUpdate({revisionId});
417+
} catch (error: unknown) {
418+
console.warn('HMR update reporter failed:', error);
419+
}
420+
}
421+
399422
function emitFastRefreshCompleteEvents() {
400423
// Add marker entry in performance timeline
401424
performance.mark('Fast Refresh - Update done', {
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict-local
8+
* @format
9+
*/
10+
11+
'use strict';
12+
13+
type Handler = (payload: unknown) => void;
14+
15+
interface MockClient {
16+
emit(event: string, payload: unknown): void;
17+
}
18+
19+
const mockClients: Array<MockClient> = [];
20+
21+
jest.mock('metro-runtime/src/modules/HMRClient', () => {
22+
return class {
23+
enabled: boolean = false;
24+
handlers: Map<string, Handler> = new Map();
25+
constructor() {
26+
mockClients.push(this);
27+
}
28+
on(event: string, handler: Handler) {
29+
this.handlers.set(event, handler);
30+
}
31+
emit(event: string, payload: unknown) {
32+
this.handlers.get(event)?.(payload);
33+
}
34+
isEnabled(): boolean {
35+
return this.enabled;
36+
}
37+
enable() {
38+
this.enabled = true;
39+
}
40+
disable() {
41+
this.enabled = false;
42+
}
43+
hasPendingUpdates(): boolean {
44+
return false;
45+
}
46+
send() {}
47+
close() {}
48+
};
49+
});
50+
jest.mock('../../Core/Devtools/getDevServer', () => ({
51+
__esModule: true,
52+
default: () => ({
53+
bundleLoadedFromServer: true,
54+
fullBundleUrl: 'http://localhost:8081/index.bundle?platform=ios',
55+
url: 'http://localhost:8081/',
56+
}),
57+
}));
58+
jest.mock('../DevLoadingView', () => ({
59+
__esModule: true,
60+
default: {showMessage: jest.fn(), hide: jest.fn()},
61+
}));
62+
jest.mock('../../LogBox/LogBox', () => ({
63+
__esModule: true,
64+
default: {clearAllLogs: jest.fn()},
65+
}));
66+
jest.mock('../../NativeModules/specs/NativeRedBox', () => ({
67+
__esModule: true,
68+
default: null,
69+
}));
70+
jest.mock('../../Core/NativeExceptionsManager', () => ({
71+
__esModule: true,
72+
default: {dismissRedbox: jest.fn()},
73+
}));
74+
75+
describe('HMRClient', () => {
76+
let onUpdate;
77+
78+
beforeEach(() => {
79+
jest.resetModules();
80+
mockClients.length = 0;
81+
onUpdate = jest.fn();
82+
global.__HMR_UPDATE_REPORTER__ = {onUpdate};
83+
});
84+
85+
afterEach(() => {
86+
delete global.__HMR_UPDATE_REPORTER__;
87+
});
88+
89+
function setUp(isEnabled: boolean) {
90+
const HMRClient = require('../HMRClient').default;
91+
HMRClient.setup('ios', 'index.bundle', 'localhost', 8081, isEnabled);
92+
return mockClients[0];
93+
}
94+
95+
function applyUpdate(client: MockClient, update: unknown) {
96+
client.emit('update-start', {isInitialUpdate: false});
97+
client.emit('update', update);
98+
client.emit('update-done', {changeId: 'change'});
99+
}
100+
101+
it('reports the revision of an applied update once it is done', () => {
102+
const client = setUp(true);
103+
104+
client.emit('update-start', {isInitialUpdate: false});
105+
client.emit('update', {isInitialUpdate: false, revisionId: 'rev-2'});
106+
expect(onUpdate).not.toHaveBeenCalled();
107+
client.emit('update-done', {changeId: 'change'});
108+
109+
expect(onUpdate.mock.calls).toEqual([[{revisionId: 'rev-2'}]]);
110+
});
111+
112+
it('reports an update that Fast Refresh stashed', () => {
113+
const client = setUp(false);
114+
115+
applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-3'});
116+
117+
expect(onUpdate.mock.calls).toEqual([[{revisionId: 'rev-3'}]]);
118+
});
119+
120+
it('reports the initial update and one without a revision', () => {
121+
const client = setUp(true);
122+
123+
applyUpdate(client, {isInitialUpdate: true, revisionId: 'rev-1'});
124+
applyUpdate(client, {isInitialUpdate: false});
125+
126+
expect(onUpdate.mock.calls).toEqual([
127+
[{revisionId: 'rev-1'}],
128+
[{revisionId: undefined}],
129+
]);
130+
});
131+
132+
it('keeps handling updates when the reporter throws', () => {
133+
onUpdate.mockImplementation(() => {
134+
throw new Error('reporter failed');
135+
});
136+
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
137+
const DevLoadingView = require('../DevLoadingView').default;
138+
const client = setUp(true);
139+
140+
expect(() =>
141+
applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-2'}),
142+
).not.toThrow();
143+
expect(warn).toHaveBeenCalledTimes(1);
144+
expect(DevLoadingView.hide).toHaveBeenCalled();
145+
warn.mockRestore();
146+
});
147+
148+
it('handles an update as before when no reporter is installed', () => {
149+
delete global.__HMR_UPDATE_REPORTER__;
150+
const client = setUp(true);
151+
const LogBox = require('../../LogBox/LogBox').default;
152+
const NativeExceptionsManager =
153+
require('../../Core/NativeExceptionsManager').default;
154+
155+
applyUpdate(client, {isInitialUpdate: false, revisionId: 'rev-2'});
156+
157+
expect(NativeExceptionsManager.dismissRedbox).toHaveBeenCalledTimes(1);
158+
expect(LogBox.clearAllLogs).toHaveBeenCalledTimes(1);
159+
});
160+
});

‎packages/react-native/React/Base/RCTJavaScriptLoader.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,13 @@ NS_ENUM(NSInteger){
7676
*/
7777
@property (strong, nonatomic, readonly) NSURL *downloadedBundleFileURL;
7878

79+
/**
80+
* The bundler's identifier for the revision of the module graph this bundle was
81+
* built from, taken from the `X-Metro-Delta-ID` response header. nil when the
82+
* bundle was not served by a bundler that sends one (e.g. read from disk).
83+
*/
84+
@property (copy, nonatomic, readonly) NSString *revisionId;
85+
7986
@end
8087

8188
typedef void (^RCTSourceLoadProgressBlock)(RCTLoadingProgress *progressData);

‎packages/react-native/React/Base/RCTJavaScriptLoader.mm‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ @interface RCTSource () {
2727
NSUInteger _length;
2828
NSInteger _filesChangedCount;
2929
NSURL *_downloadedBundleFileURL;
30+
NSString *_revisionId;
3031
}
3132

3233
@end
@@ -223,6 +224,10 @@ + (NSData *)attemptSynchronousLoadOfBundleAtURL:(NSURL *)scriptURL
223224
static void parseHeaders(NSDictionary *headers, RCTSource *source)
224225
{
225226
source->_filesChangedCount = [headers[@"X-Metro-Files-Changed-Count"] integerValue];
227+
id revisionId = headers[@"X-Metro-Delta-ID"];
228+
if ([revisionId isKindOfClass:[NSString class]] && [revisionId length] > 0) {
229+
source->_revisionId = revisionId;
230+
}
226231
}
227232

228233
static NSURL *persistDownloadedBundle(NSData *data, NSError **error)

‎packages/react-native/ReactAndroid/api/ReactAndroid.api‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1823,6 +1823,7 @@ public final class com/facebook/react/devsupport/BundleDownloader$BundleInfo {
18231823
public fun <init> ()V
18241824
public static final fun fromJSONString (Ljava/lang/String;)Lcom/facebook/react/devsupport/BundleDownloader$BundleInfo;
18251825
public final fun getFilesChangedCount ()I
1826+
public final fun getRevisionId ()Ljava/lang/String;
18261827
public final fun getUrl ()Ljava/lang/String;
18271828
public final fun toJSONString ()Ljava/lang/String;
18281829
}

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.kt‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,17 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
4242
public var filesChangedCount: Int = 0
4343
internal set
4444

45+
/** The dev server's label for the revision it built the bundle from (`X-Metro-Delta-ID`). */
46+
public var revisionId: String? = null
47+
internal set
48+
4549
public fun toJSONString(): String? =
4650
try {
4751
JSONObject()
4852
.apply {
4953
put("url", _url)
5054
put("filesChangedCount", filesChangedCount)
55+
put("revisionId", revisionId)
5156
}
5257
.toString()
5358
} catch (e: JSONException) {
@@ -63,10 +68,11 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
6368
}
6469
return try {
6570
val obj = JSONObject(jsonStr)
66-
BundleInfo().apply {
67-
_url = obj.getString("url")
68-
filesChangedCount = obj.getInt("filesChangedCount")
69-
}
71+
val info = BundleInfo()
72+
info._url = obj.getString("url")
73+
info.filesChangedCount = obj.getInt("filesChangedCount")
74+
info.revisionId = obj.optString("revisionId").ifEmpty { null }
75+
info
7076
} catch (e: JSONException) {
7177
FLog.e(TAG, "Invalid bundle info: ", e)
7278
null
@@ -335,6 +341,7 @@ public class BundleDownloader public constructor(private val client: OkHttpClien
335341

336342
private fun populateBundleInfo(url: String, headers: Headers, bundleInfo: BundleInfo) {
337343
bundleInfo._url = url
344+
bundleInfo.revisionId = headers["X-Metro-Delta-ID"]?.ifEmpty { null }
338345

339346
val filesChangedCountStr = headers["X-Metro-Files-Changed-Count"]
340347
if (filesChangedCountStr != null) {
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
package com.facebook.react.devsupport
9+
10+
import org.assertj.core.api.Assertions.assertThat
11+
import org.junit.Test
12+
import org.junit.runner.RunWith
13+
import org.robolectric.RobolectricTestRunner
14+
15+
@RunWith(RobolectricTestRunner::class)
16+
class BundleInfoTest {
17+
18+
@Test
19+
fun keepsTheDevServerRevisionAcrossJson() {
20+
val info = BundleDownloader.BundleInfo()
21+
info._url = "http://localhost:8081/index.bundle"
22+
info.revisionId = "rev-1"
23+
24+
val parsed = BundleDownloader.BundleInfo.fromJSONString(info.toJSONString())
25+
26+
assertThat(parsed?.revisionId).isEqualTo("rev-1")
27+
}
28+
29+
@Test
30+
fun readsAMissingRevisionAsNull() {
31+
val parsed = BundleDownloader.BundleInfo.fromJSONString("""{"url":"u","filesChangedCount":0}""")
32+
33+
assertThat(parsed?.revisionId).isNull()
34+
}
35+
}

0 commit comments

Comments
 (0)