Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(runtime): allow errorLoadRemote hook catch remote entry resource loading error #3474

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
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
6 changes: 6 additions & 0 deletions .changeset/long-forks-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@module-federation/runtime-core': patch
'website-new': patch
---

feat: allow errorLoadRemote hook catch remote entry resource loading error
3 changes: 2 additions & 1 deletion apps/router-demo/router-host-2000/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"@module-federation/retry-plugin": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.24.1"
"react-router-dom": "^6.24.1",
"react-error-boundary": "5.0.0"
},
"devDependencies": {
"@module-federation/rsbuild-plugin": "workspace:*",
Expand Down
16 changes: 14 additions & 2 deletions apps/router-demo/router-host-2000/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,24 @@ export default defineConfig({
'remote-render-error':
'remote-render-error@http://localhost:2004/mf-manifest.json',
'remote-resource-error':
'remote-resource-errorr@http://localhost:2008/not-exist-mf-manifest.json',
'remote-resource-error@http://localhost:2008/not-exist-mf-manifest.json',
},
shared: {
react: {
singleton: true,
},
'react-dom': {
singleton: true,
},
// 'react-router-dom': {
// // singleton: true,
// requiredVersion: '6.x',
// },
},
shared: ['react', 'react-dom', 'antd'],
runtimePlugins: [
path.join(__dirname, './src/runtime-plugin/shared-strategy.ts'),
path.join(__dirname, './src/runtime-plugin/retry.ts'),
path.join(__dirname, './src/runtime-plugin/fallback.ts'),
],
// bridge: {
// disableAlias: true,
Expand Down
52 changes: 50 additions & 2 deletions apps/router-demo/router-host-2000/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { useRef, useEffect, ForwardRefExoticComponent } from 'react';
import React, {
useRef,
useEffect,
ForwardRefExoticComponent,
Suspense,
} from 'react';
import { Route, Routes, useLocation } from 'react-router-dom';
import { init, loadRemote } from '@module-federation/enhanced/runtime';
import { RetryPlugin } from '@module-federation/retry-plugin';
Expand All @@ -8,10 +13,28 @@ import Detail from './pages/Detail';
import Home from './pages/Home';
import './App.css';
import BridgeReactPlugin from '@module-federation/bridge-react/plugin';
import { ErrorBoundary } from 'react-error-boundary';
// import Remote1AppNew from 'remote1/app';
import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';

const fallbackPlugin: () => FederationRuntimePlugin = function () {
return {
name: 'fallback-plugin',
errorLoadRemote(args) {
return { default: () => <div> fallback component </div> };
},
};
};

init({
name: 'federation_consumer',
remotes: [],
remotes: [
// {
// name: 'remote1',
// alias: 'remote1',
// entry: 'http://localhost:2001/mf-manifest.json',
// },
],
plugins: [
BridgeReactPlugin(),
// RetryPlugin({
Expand All @@ -30,6 +53,7 @@ init({
// },
// },
// }),
// fallbackPlugin(),
],
});

Expand All @@ -54,6 +78,15 @@ const Remote1App = createRemoteComponent({
loading: FallbackComp,
});

const Remote1AppWithLoadRemote = React.lazy(() => loadRemote('remote1/app'));
const Remote1AppWithErrorBoundary = React.forwardRef<any, any>((props, ref) => (
<ErrorBoundary fallback={<div>Error loading Remote1App...</div>}>
<Suspense fallback={<div> Loading Remote1App...</div>}>
<Remote1AppWithLoadRemote {...props} ref={ref} />
</Suspense>
</ErrorBoundary>
));

const Remote2App = createRemoteComponent({
loader: () => import('remote2/export-app'),
export: 'provider',
Expand Down Expand Up @@ -86,6 +119,11 @@ function Wraper3() {
<div className="grow">
<h2>Remote1</h2>
<Remote1App name={'Ming'} age={12} memoryRoute={{ entryPath: '/' }} />
{/* <Remote1AppWithErrorBoundary
name={'Ming'}
age={12}
memoryRoute={{ entryPath: '/' }}
/> */}
</div>
<div className="grow">
<h2>Remote2</h2>
Expand Down Expand Up @@ -129,6 +167,16 @@ const App = () => {
path="/remote1/*"
Component={() => (
<Remote1App name={'Ming'} age={12} ref={ref} basename="/remote1" />
// <Remote1AppWithErrorBoundary
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can be deleted directly

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, i've add the specific router to show this case.

// name={'Ming'}
// age={12}
// ref={ref}
// basename="/remote1"
// />
// <Remote1AppNew name={'Ming'} age={12} />
// <React.Suspense fallback={<div> Loading Remote1App...</div>}>
// <Remote1AppWithLoadRemote />
// </React.Suspense>
)}
/>
<Route
Expand Down
37 changes: 37 additions & 0 deletions apps/router-demo/router-host-2000/src/runtime-plugin/fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';

const fallbackPlugin = (): FederationRuntimePlugin => {
return {
name: 'fallback-plugin',
async errorLoadRemote(args) {
// if (args.lifecycle === 'onLoad') {
Copy link
Collaborator

Choose a reason for hiding this comment

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

You can simply delete redundant comments

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

// const React = await import('react');
// const FallbackComponent = React.memo(() =>
// React.createElement('div', null, 'fallback component'),
// );
// FallbackComponent.displayName = 'FallbackComponent';
// return () => ({
// __esModule: true,
// default: FallbackComponent,
// });
// } else if (args.lifecycle === 'afterResolve') {
// // you can try another fall back remote entry or return a constant manifest data
// // const response = await fetch('http://localhost:2002/mf-manifest.json');
// // const manifestJson = (await response.json()) as Manifest;
// // return manifestJson;
// }
// return args;

const React = await import('react');
const FallbackComponent = React.memo(() =>
React.createElement('div', null, 'fallback component'),
);
FallbackComponent.displayName = 'FallbackComponent';
return () => ({
__esModule: true,
default: FallbackComponent,
});
},
};
};
export default fallbackPlugin;
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const retryPlugin = () =>
RetryPlugin({
fetch: {
url: 'http://localhost:2001/mf-manifest.json',
fallback: () => 'http://localhost:2001/mf-manifest.json',
// fallback: () => 'http://localhost:2001/mf-manifest.json',
},
script: {
retryTimes: 3,
Expand Down
25 changes: 15 additions & 10 deletions apps/router-demo/router-remote1-2001/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,26 @@ export default defineConfig({
exposes: {
'./button': './src/button.tsx',
'./export-app': './src/export-App.tsx',
'./app': './src/App.tsx',
},
shared: {
// react: {
// singleton: true,
// },
// 'react-dom': {
// singleton: true,
// },
react: {
singleton: true,
},
'react-dom': {
singleton: true,
},
// 'react-router-dom': {
// singleton: true,
// },
// antd: {
// singleton: true,
// // singleton: true,
// requiredVersion: '5.x',
// },
antd: {
singleton: true,
},
},
// bridge: {
// disableAlias: true,
// },
}),
],
});
46 changes: 30 additions & 16 deletions packages/runtime-core/src/plugins/snapshot/SnapshotHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,26 +305,40 @@ export class SnapshotHandler {
res = await fetch(manifestUrl, {});
}
manifestJson = (await res.json()) as Manifest;
assert(
manifestJson.metaData && manifestJson.exposes && manifestJson.shared,
`${manifestUrl} is not a federation manifest`,
);
this.manifestCache.set(manifestUrl, manifestJson);
return manifestJson;
} catch (err) {
delete this.manifestLoading[manifestUrl];
error(
getShortErrorMsg(
RUNTIME_003,
runtimeDescMap,
manifestJson =
(await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit(
{
manifestUrl,
moduleName: moduleInfo.name,
id: manifestUrl,
error,
from: 'runtime',
lifecycle: 'afterResolve',
origin: this.HostInstance,
},
`${err}`,
),
);
)) as Manifest | undefined;

if (!manifestJson) {
delete this.manifestLoading[manifestUrl];
error(
getShortErrorMsg(
RUNTIME_003,
runtimeDescMap,
{
manifestUrl,
moduleName: moduleInfo.name,
},
`${err}`,
),
);
}
}

assert(
manifestJson.metaData && manifestJson.exposes && manifestJson.shared,
`${manifestUrl} is not a federation manifest`,
);
this.manifestCache.set(manifestUrl, manifestJson);
return manifestJson;
};

const asyncLoadProcess = async () => {
Expand Down
6 changes: 5 additions & 1 deletion packages/runtime-core/src/remote/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,11 @@ export class RemoteHandler {
error: unknown;
options?: any;
from: CallFrom;
lifecycle: 'onLoad' | 'beforeRequest' | 'beforeLoadShare';
lifecycle:
| 'beforeRequest'
| 'beforeLoadShare'
| 'afterResolve'
| 'onLoad';
origin: FederationHost;
},
],
Expand Down
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.