Skip to content

Commit 60903e6

Browse files
DeltaCalculator: Apply changes made during a (failed or successful) build on top (#2007)
* DeltaCalculator: Apply changes made during a failed build on top When a delta build fails, getDelta put back the change sets it took as a plain union with the changes that arrived during the build. A file deleted before the build and recreated during it then sat in both the added and the deleted set and was skipped by the next delta, so the client kept the old module; a file modified before the build and deleted during it was traversed after its deletion. The taken sets are now restored as the base, and the later changes are replayed on top through the transitions the change handler uses. * DeltaCalculator: Revisit a file recreated while a build was in flight A file deleted before a build and recreated before its importer re-resolves it leaves the build green with the graph still holding the old module. The recreated file then only ever sits in the added set, which nothing traverses, so the client keeps stale code until the file changes again. An added file that already has a module in the graph can only be one the graph never saw deleted, so it is now treated as modified and revisited on the next delta. This covers the successful build as well as the failed one. --------- Co-authored-by: Rob Hogan <2590098+robhogan@users.noreply.github.com>
1 parent 0a936c2 commit 60903e6

2 files changed

Lines changed: 150 additions & 27 deletions

File tree

‎packages/metro/src/DeltaBundler/DeltaCalculator.js‎

Lines changed: 52 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,17 @@ export default class DeltaCalculator<T> extends EventEmitter {
147147
// processed (since we haven't actually created any delta). If we do not
148148
// do so, asking for a delta after an error will produce an empty Delta,
149149
// which is not correct.
150-
modifiedFiles.forEach((file: string) => this._modifiedFiles.add(file));
151-
deletedFiles.forEach((file: string) => this._deletedFiles.add(file));
152-
addedFiles.forEach((file: string) => this._addedFiles.add(file));
150+
// Changes that arrived while this delta was being built happened after
151+
// the ones it took, so they are applied on top of them.
152+
const laterAddedFiles = this._addedFiles;
153+
const laterModifiedFiles = this._modifiedFiles;
154+
const laterDeletedFiles = this._deletedFiles;
155+
this._addedFiles = addedFiles;
156+
this._modifiedFiles = modifiedFiles;
157+
this._deletedFiles = deletedFiles;
158+
laterAddedFiles.forEach((file: string) => this.#markAdded(file));
159+
laterModifiedFiles.forEach((file: string) => this.#markModified(file));
160+
laterDeletedFiles.forEach((file: string) => this.#markDeleted(file));
153161

154162
throw error;
155163
} finally {
@@ -199,51 +207,60 @@ export default class DeltaCalculator<T> extends EventEmitter {
199207
return false;
200208
}
201209

210+
// Deleted+added = modified, otherwise added.
211+
#markAdded(absolutePath: string): void {
212+
if (this._deletedFiles.has(absolutePath)) {
213+
this._deletedFiles.delete(absolutePath);
214+
this._modifiedFiles.add(absolutePath);
215+
} else {
216+
this._addedFiles.add(absolutePath);
217+
this._modifiedFiles.delete(absolutePath);
218+
}
219+
}
220+
221+
// Added+modified stays added, otherwise modified.
222+
#markModified(absolutePath: string): void {
223+
if (!this._addedFiles.has(absolutePath)) {
224+
this._modifiedFiles.add(absolutePath);
225+
}
226+
this._deletedFiles.delete(absolutePath);
227+
}
228+
229+
// Added+deleted = no change, otherwise deleted.
230+
#markDeleted(absolutePath: string): void {
231+
if (this._addedFiles.has(absolutePath)) {
232+
this._addedFiles.delete(absolutePath);
233+
} else {
234+
this._deletedFiles.add(absolutePath);
235+
this._modifiedFiles.delete(absolutePath);
236+
}
237+
}
238+
202239
_handleMultipleFileChanges = (changeEvent: ChangeEvent) => {
203240
const {changes, logger, rootDir} = changeEvent;
204241

205-
// Process added files: deleted+added = modified, otherwise added
206242
for (const [canonicalPath, metadata] of changes.addedFiles) {
207243
debug('Handling add: %s', canonicalPath);
208244
if (this.#shouldReset(canonicalPath, metadata)) {
209245
this._requiresReset = true;
210246
}
211-
const absolutePath = path.join(rootDir, canonicalPath);
212-
if (this._deletedFiles.has(absolutePath)) {
213-
this._deletedFiles.delete(absolutePath);
214-
this._modifiedFiles.add(absolutePath);
215-
} else {
216-
this._addedFiles.add(absolutePath);
217-
this._modifiedFiles.delete(absolutePath);
218-
}
247+
this.#markAdded(path.join(rootDir, canonicalPath));
219248
}
220249

221-
// Process modified files: added+modified stays added, otherwise modified
222250
for (const [canonicalPath, metadata] of changes.modifiedFiles) {
223251
debug('Handling change: %s', canonicalPath);
224252
if (this.#shouldReset(canonicalPath, metadata)) {
225253
this._requiresReset = true;
226254
}
227-
const absolutePath = path.join(rootDir, canonicalPath);
228-
if (!this._addedFiles.has(absolutePath)) {
229-
this._modifiedFiles.add(absolutePath);
230-
}
231-
this._deletedFiles.delete(absolutePath);
255+
this.#markModified(path.join(rootDir, canonicalPath));
232256
}
233257

234-
// Process removed files: added+deleted = no change, otherwise deleted
235258
for (const [canonicalPath, metadata] of changes.removedFiles) {
236259
debug('Handling delete: %s', canonicalPath);
237260
if (this.#shouldReset(canonicalPath, metadata)) {
238261
this._requiresReset = true;
239262
}
240-
const absolutePath = path.resolve(rootDir, canonicalPath);
241-
if (this._addedFiles.has(absolutePath)) {
242-
this._addedFiles.delete(absolutePath);
243-
} else {
244-
this._deletedFiles.add(absolutePath);
245-
this._modifiedFiles.delete(absolutePath);
246-
}
263+
this.#markDeleted(path.resolve(rootDir, canonicalPath));
247264
}
248265

249266
let changeId = changeEventIds.get(changeEvent);
@@ -287,6 +304,15 @@ export default class DeltaCalculator<T> extends EventEmitter {
287304
}
288305
});
289306

307+
// An added file that already has a module in the graph was deleted and
308+
// recreated while a build was in flight. The graph never saw the deletion,
309+
// so the module it holds is stale and needs revisiting.
310+
addedFiles.forEach((filePath: string) => {
311+
if (this._graph.dependencies.has(filePath)) {
312+
modifiedFiles.add(filePath);
313+
}
314+
});
315+
290316
// NOTE(EvanBacon): This check adds extra complexity so we feature gate it
291317
// to enable users to opt out.
292318
if (this._options.unstable_allowRequireContext) {

‎packages/metro/src/DeltaBundler/__tests__/DeltaCalculator-test.js‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ describe.each(['posix', 'win32'])('DeltaCalculator (%s)', osPlatform => {
304304
test('should calculate a delta after a file addition', async () => {
305305
await deltaCalculator.getDelta({reset: false, shallow: false});
306306

307-
emitChange({addedFiles: ['foo']});
307+
emitChange({addedFiles: ['unrelated']});
308308

309309
traverseDependencies.mockResolvedValueOnce({
310310
added: new Map([[p('/foo'), fooModule]]),
@@ -566,6 +566,103 @@ describe.each(['posix', 'win32'])('DeltaCalculator (%s)', osPlatform => {
566566
expect(traverseDependencies.mock.calls[0][0]).toEqual([p('/foo')]);
567567
});
568568

569+
test('should traverse a file re-added while a failed delta was being built', async () => {
570+
await deltaCalculator.getDelta({reset: false, shallow: false});
571+
572+
emitChange({removedFiles: ['foo']});
573+
574+
let rejectTraversal: (error: Error) => void = () => {};
575+
traverseDependencies.mockReturnValueOnce(
576+
new Promise((resolve, reject) => {
577+
rejectTraversal = reject;
578+
}),
579+
);
580+
const failedDelta = deltaCalculator.getDelta({
581+
reset: false,
582+
shallow: false,
583+
});
584+
585+
// The file is recreated while the delta that saw it deleted is still being built.
586+
emitChange({addedFiles: ['foo']});
587+
rejectTraversal(new Error('Unable to resolve module'));
588+
await expect(failedDelta).rejects.toBeInstanceOf(Error);
589+
590+
traverseDependencies.mockResolvedValueOnce({
591+
added: new Map(),
592+
modified: new Map([[p('/foo'), fooModule]]),
593+
deleted: new Set(),
594+
});
595+
await deltaCalculator.getDelta({reset: false, shallow: false});
596+
597+
expect(traverseDependencies).toHaveBeenCalledTimes(2);
598+
expect(traverseDependencies.mock.calls[1][0]).toContain(p('/foo'));
599+
});
600+
601+
test('should not traverse a file deleted while a failed delta was being built', async () => {
602+
await deltaCalculator.getDelta({reset: false, shallow: false});
603+
604+
emitChange({modifiedFiles: ['foo']});
605+
606+
let rejectTraversal: (error: Error) => void = () => {};
607+
traverseDependencies.mockReturnValueOnce(
608+
new Promise((resolve, reject) => {
609+
rejectTraversal = reject;
610+
}),
611+
);
612+
const failedDelta = deltaCalculator.getDelta({
613+
reset: false,
614+
shallow: false,
615+
});
616+
617+
emitChange({removedFiles: ['foo']});
618+
rejectTraversal(new Error('Unable to resolve module'));
619+
await expect(failedDelta).rejects.toBeInstanceOf(Error);
620+
621+
traverseDependencies.mockResolvedValueOnce({
622+
added: new Map(),
623+
modified: new Map([[p('/bundle'), entryModule]]),
624+
deleted: new Set([p('/foo')]),
625+
});
626+
await deltaCalculator.getDelta({reset: false, shallow: false});
627+
628+
expect(traverseDependencies).toHaveBeenCalledTimes(2);
629+
expect(traverseDependencies.mock.calls[1][0]).toEqual([p('/bundle')]);
630+
});
631+
632+
test('should traverse a file re-added while a successful delta was being built', async () => {
633+
await deltaCalculator.getDelta({reset: false, shallow: false});
634+
635+
emitChange({removedFiles: ['foo']});
636+
637+
let resolveTraversal: (result: Result<$FlowFixMe>) => void = () => {};
638+
traverseDependencies.mockReturnValueOnce(
639+
new Promise(resolve => {
640+
resolveTraversal = resolve;
641+
}),
642+
);
643+
const delta = deltaCalculator.getDelta({reset: false, shallow: false});
644+
645+
// The file is recreated before its importer re-resolves it, so the build
646+
// succeeds without revisiting the module the graph already holds.
647+
emitChange({addedFiles: ['foo']});
648+
resolveTraversal({
649+
added: new Map(),
650+
modified: new Map([[p('/bundle'), entryModule]]),
651+
deleted: new Set(),
652+
});
653+
await delta;
654+
655+
traverseDependencies.mockResolvedValueOnce({
656+
added: new Map(),
657+
modified: new Map([[p('/foo'), fooModule]]),
658+
deleted: new Set(),
659+
});
660+
await deltaCalculator.getDelta({reset: false, shallow: false});
661+
662+
expect(traverseDependencies).toHaveBeenCalledTimes(2);
663+
expect(traverseDependencies.mock.calls[1][0]).toEqual([p('/foo')]);
664+
});
665+
569666
test.each(['add', 'delete'])(
570667
"should re-traverse everything after a symlink '%s'",
571668
async eventType => {

0 commit comments

Comments
 (0)