Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-remote-instance-cleanup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@module-federation/runtime-core': patch
---

removeRemote now also matches the remote's runtime instance by entryGlobalName and warns when no instance can be found, instead of silently leaving stale instances in __FEDERATION__.__INSTANCES__ after registerRemotes({ force: true }).
136 changes: 135 additions & 1 deletion packages/runtime-core/__tests__/register-remotes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { assert, describe, it, expect, rs } from '@rstest/core';
import { ModuleFederation } from '../src/index';
import {
ModuleFederation,
CurrentGlobal,
setGlobalFederationInstance,
} from '../src/index';

describe('ModuleFederation', () => {
it('registers new remotes and loads them correctly', async () => {
Expand Down Expand Up @@ -102,6 +106,136 @@ describe('ModuleFederation', () => {
// Value is different from the registered remote
expect(newApp1Res).toBe('hello app1 entry2');
});
it('removes the remote runtime instance matched by entryGlobalName when force registering', async () => {
const buildName = '@register-remotes/app1';
const registeredName = '@register-remotes/app1-alias';
// Drop any container global left behind by earlier tests so the entry
// script is executed again instead of being reused.
delete (CurrentGlobal as Record<string, unknown>)[buildName];
const FM = new ModuleFederation({
name: '@federation/instance',
version: '1.0.1',
remotes: [
{
// Registered name differs from the name the remote was built with
name: registeredName,
entryGlobalName: buildName,
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry.js',
},
],
});
const app1Module = await FM.loadRemote<Promise<() => string>>(
`${registeredName}/say`,
);
assert(app1Module);
expect(await app1Module()).toBe('hello app1 entry1');

// Simulate the remote's own runtime instance, named after its build name
const remoteInstance = new ModuleFederation({
name: buildName,
remotes: [],
});
setGlobalFederationInstance(remoteInstance);
expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).toContain(
remoteInstance,
);
const warnSpy = rs.spyOn(console, 'warn').mockImplementation(() => {});

try {
FM.registerRemotes(
[
{
name: registeredName,
entryGlobalName: buildName,
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry2.js',
},
],
{ force: true },
);

expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).not.toContain(
remoteInstance,
);
expect(FM.moduleCache.has(registeredName)).toBe(false);
expect(
warnSpy.mock.calls.some((call) =>
call.some(
(arg) =>
typeof arg === 'string' &&
arg.includes('__FEDERATION__.__INSTANCES__'),
),
),
).toBe(false);
} finally {
warnSpy.mockRestore();
}

const newApp1Module = await FM.loadRemote<Promise<() => string>>(
`${registeredName}/say`,
);
assert(newApp1Module);
expect(await newApp1Module()).toBe('hello app1 entry2');
});
it('warns and keeps __INSTANCES__ unchanged when no runtime instance matches the removed remote', async () => {
delete (CurrentGlobal as Record<string, unknown>)['@register-remotes/app1'];
const FM = new ModuleFederation({
name: '@federation/instance',
version: '1.0.1',
remotes: [
{
name: '@register-remotes/app1',
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry.js',
},
],
});
const app1Module = await FM.loadRemote<Promise<() => string>>(
'@register-remotes/app1/say',
);
assert(app1Module);
expect(await app1Module()).toBe('hello app1 entry1');

const unrelatedInstance = new ModuleFederation({
name: '@register-remotes/unrelated',
remotes: [],
});
setGlobalFederationInstance(unrelatedInstance);
const instancesBefore = [...CurrentGlobal.__FEDERATION__.__INSTANCES__];
const warnSpy = rs.spyOn(console, 'warn').mockImplementation(() => {});

try {
FM.registerRemotes(
[
{
name: '@register-remotes/app1',
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry2.js',
},
],
{ force: true },
);

expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).toEqual(
instancesBefore,
);
const warning = warnSpy.mock.calls
.flat()
.find(
(arg) =>
typeof arg === 'string' &&
arg.includes('__FEDERATION__.__INSTANCES__'),
);
expect(warning).toBeDefined();
expect(warning).toContain('"@register-remotes/app1"');
expect(warning).toContain(
'share scope and instance could not be released',
);
} finally {
warnSpy.mockRestore();
}
});
it('reloads manifest snapshots when a manifest remote is force registered with the same entry', async () => {
const manifestUrl =
'http://localhost:1111/resources/register-remotes/manifest/federation-manifest.json';
Expand Down
43 changes: 32 additions & 11 deletions packages/runtime-core/src/remote/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,17 +762,29 @@ export class RemoteHandler {
let remoteInsId = remoteInfo.buildVersion
? composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion)
: remoteInfo.name;
const remoteInsIndex =
CurrentGlobal.__FEDERATION__.__INSTANCES__.findIndex((ins) => {
if (remoteInfo.buildVersion) {
return ins.options.id === remoteInsId;
} else {
return ins.name === remoteInsId;
}
});
const instances = CurrentGlobal.__FEDERATION__.__INSTANCES__;
let remoteInsIndex = instances.findIndex((ins) => {
if (remoteInfo.buildVersion) {
return ins.options.id === remoteInsId;
} else {
return ins.name === remoteInsId;
}
});
// The registered name may differ from the name the remote was built
// with. The remote's runtime instance is named after its build name,
// which for enhanced/webpack containers equals entryGlobalName.
const { entryGlobalName } = remoteInfo;
const canMatchByEntryGlobalName =
typeof entryGlobalName === 'string' &&
entryGlobalName !== '' &&
entryGlobalName !== remoteInfo.name;
if (remoteInsIndex === -1 && canMatchByEntryGlobalName) {
remoteInsIndex = instances.findIndex(
(ins) => ins.name === entryGlobalName,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Match the exact built instance instead of entryGlobalName

When an aliased remote uses a custom library.name, entryGlobalName is that library global rather than the Module Federation build name used by the runtime instance; this lookup therefore misses the intended instance and can splice an unrelated instance whose name happens to equal the library global. It also ignores buildVersion, so multiple stale builds with the same name can cause the first, wrong version to be removed. Match the instance using the remote's actual build name and versioned ID instead of treating entryGlobalName as an instance identity.

Useful? React with 👍 / 👎.

}
if (remoteInsIndex !== -1) {
const remoteIns =
CurrentGlobal.__FEDERATION__.__INSTANCES__[remoteInsIndex];
const remoteIns = instances[remoteInsIndex];
remoteInsId = remoteIns.options.id || remoteInsId;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clean aliased shares using the matched build name

When this fallback successfully finds an aliased remote, its shared entries are registered with from and useIn values based on the remote instance's build name, but the cleanup below still compares and filters using the registered alias in remoteInfo.name. Consequently none of those entries are queued for deletion before the instance is spliced, leaving stale factories in the host share scope that can be selected after the replacement remote loads; derive the cleanup name from the matched remoteIns.

Useful? React with 👍 / 👎.

const globalShareScopeMap = getGlobalShareScope();

Expand Down Expand Up @@ -834,7 +846,16 @@ export class RemoteHandler {
];
},
);
CurrentGlobal.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
instances.splice(remoteInsIndex, 1);
} else {
// Containers built without the federation runtime legitimately have
// no instance, so only warn: a stale instance would otherwise stay
// in __INSTANCES__ and leak once the remote is loaded again.
logger.warn(
`No runtime instance named "${remoteInfo.name}"${
canMatchByEntryGlobalName ? ` (or "${entryGlobalName}")` : ''
} was found in __FEDERATION__.__INSTANCES__ while removing remote "${remote.name}", so its share scope and instance could not be released. Make sure the registered remote name matches the name the remote was built with.`,
);
}

host.moduleCache.delete(remote.name);
Expand Down
136 changes: 135 additions & 1 deletion packages/runtime/__tests__/register-remotes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { assert, describe, it, expect } from '@rstest/core';
import { assert, describe, it, expect, rs } from '@rstest/core';
import {
CurrentGlobal,
setGlobalFederationInstance,
} from '@module-federation/runtime-core';
import { ModuleFederation } from '../src/index';

describe('ModuleFederation', () => {
Expand Down Expand Up @@ -102,4 +106,134 @@ describe('ModuleFederation', () => {
// Value is different from the registered remote
expect(newApp1Res).toBe('hello app1 entry2');
});
it('removes the remote runtime instance matched by entryGlobalName when force registering', async () => {
const buildName = '@register-remotes/app1';
const registeredName = '@register-remotes/app1-alias';
// Drop any container global left behind by earlier tests so the entry
// script is executed again instead of being reused.
delete (CurrentGlobal as Record<string, unknown>)[buildName];
const FM = new ModuleFederation({
name: '@federation/instance',
version: '1.0.1',
remotes: [
{
// Registered name differs from the name the remote was built with
name: registeredName,
entryGlobalName: buildName,
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry.js',
},
],
});
const app1Module = await FM.loadRemote<Promise<() => string>>(
`${registeredName}/say`,
);
assert(app1Module);
expect(await app1Module()).toBe('hello app1 entry1');

// Simulate the remote's own runtime instance, named after its build name
const remoteInstance = new ModuleFederation({
name: buildName,
remotes: [],
});
setGlobalFederationInstance(remoteInstance);
expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).toContain(
remoteInstance,
);
const warnSpy = rs.spyOn(console, 'warn').mockImplementation(() => {});

try {
FM.registerRemotes(
[
{
name: registeredName,
entryGlobalName: buildName,
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry2.js',
},
],
{ force: true },
);

expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).not.toContain(
remoteInstance,
);
expect(FM.moduleCache.has(registeredName)).toBe(false);
expect(
warnSpy.mock.calls.some((call) =>
call.some(
(arg) =>
typeof arg === 'string' &&
arg.includes('__FEDERATION__.__INSTANCES__'),
),
),
).toBe(false);
} finally {
warnSpy.mockRestore();
}

const newApp1Module = await FM.loadRemote<Promise<() => string>>(
`${registeredName}/say`,
);
assert(newApp1Module);
expect(await newApp1Module()).toBe('hello app1 entry2');
});
it('warns and keeps __INSTANCES__ unchanged when no runtime instance matches the removed remote', async () => {
delete (CurrentGlobal as Record<string, unknown>)['@register-remotes/app1'];
const FM = new ModuleFederation({
name: '@federation/instance',
version: '1.0.1',
remotes: [
{
name: '@register-remotes/app1',
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry.js',
},
],
});
const app1Module = await FM.loadRemote<Promise<() => string>>(
'@register-remotes/app1/say',
);
assert(app1Module);
expect(await app1Module()).toBe('hello app1 entry1');

const unrelatedInstance = new ModuleFederation({
name: '@register-remotes/unrelated',
remotes: [],
});
setGlobalFederationInstance(unrelatedInstance);
const instancesBefore = [...CurrentGlobal.__FEDERATION__.__INSTANCES__];
const warnSpy = rs.spyOn(console, 'warn').mockImplementation(() => {});

try {
FM.registerRemotes(
[
{
name: '@register-remotes/app1',
entry:
'http://localhost:1111/resources/register-remotes/app1/federation-remote-entry2.js',
},
],
{ force: true },
);

expect(CurrentGlobal.__FEDERATION__.__INSTANCES__).toEqual(
instancesBefore,
);
const warning = warnSpy.mock.calls
.flat()
.find(
(arg) =>
typeof arg === 'string' &&
arg.includes('__FEDERATION__.__INSTANCES__'),
);
expect(warning).toBeDefined();
expect(warning).toContain('"@register-remotes/app1"');
expect(warning).toContain(
'share scope and instance could not be released',
);
} finally {
warnSpy.mockRestore();
}
});
});
Loading