Skip to content

fix(node): Improve chunk flushing #1985

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

Merged
merged 23 commits into from
Jan 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
d75dfde
fix(node): improve public path calculation
ScriptedAlchemy Jan 17, 2024
4e1d84c
fix(node): refactor public path runtime module
ScriptedAlchemy Jan 17, 2024
20e1426
fix(node): refactor public path runtime module
ScriptedAlchemy Jan 17, 2024
d416104
chore: disable checkout e2e test
ScriptedAlchemy Jan 17, 2024
3c8a9da
chore: fix types
ScriptedAlchemy Jan 17, 2024
a520756
feat(runtime): onload hook allows custom factory
ScriptedAlchemy Jan 17, 2024
1e2bbda
fix(node): improve chunk flush
ScriptedAlchemy Jan 17, 2024
0502a07
fix(node): improve chunk flush
ScriptedAlchemy Jan 17, 2024
eff2df6
fix(node): improve chunk flush
ScriptedAlchemy Jan 18, 2024
9b390a3
chore: clear all federation instances
2heal1 Jan 18, 2024
047acc3
fix(nextjs-mf): hot reloading
ScriptedAlchemy Jan 18, 2024
357b01d
fix(nextjs-mf): hot reloading
ScriptedAlchemy Jan 18, 2024
0e8f53e
fix(nextjs-mf): hot reloading
ScriptedAlchemy Jan 18, 2024
d5a7b20
fix(nextjs-mf): hot reloading
ScriptedAlchemy Jan 18, 2024
46d7f77
fix(nextjs-mf): resolve to esm runtime
ScriptedAlchemy Jan 18, 2024
022ca1f
Merge branch 'main' into feat/chunk-lush
ScriptedAlchemy Jan 20, 2024
4c04cb5
chore: remove useless packages from next apps
ScriptedAlchemy Jan 20, 2024
653501d
Merge branch 'main' into feat/chunk-lush
ScriptedAlchemy Jan 20, 2024
d279575
chore: lock file
ScriptedAlchemy Jan 20, 2024
e49e786
Merge branch 'main' into feat/chunk-lush
ScriptedAlchemy Jan 20, 2024
e1baee1
Merge branch 'main' into feat/chunk-lush
ScriptedAlchemy Jan 20, 2024
22b953f
Merge remote-tracking branch 'origin/feat/chunk-lush' into feat/chunk…
ScriptedAlchemy Jan 20, 2024
fb23466
chore: update next build commands in ci
ScriptedAlchemy Jan 20, 2024
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/popular-spoons-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@module-federation/nextjs-mf': patch
'@module-federation/node': patch
---

Rewrite chunk flushing and hot reloading to use federation runtime apis
2 changes: 1 addition & 1 deletion .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,4 @@ jobs:
run: lsof -ti tcp:3005,3006,3007 | xargs kill

- name: Build Next.js Apps in Production Mode
run: pnpm app:next:prod
run: pnpm app:next:build
4 changes: 2 additions & 2 deletions apps/3000-home/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
"executor": "@nx/next:build",
"defaultConfiguration": "production",
"options": {
"outputPath": "dist/apps/3000-home"
"outputPath": "apps/3000-home"
},
"configurations": {
"development": {
"outputPath": "dist/apps/3000-home"
"outputPath": "apps/3000-home"
},
"production": {}
},
Expand Down
16 changes: 11 additions & 5 deletions apps/3001-shop/pages/_document.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,20 @@ import {

class MyDocument extends Document {
static async getInitialProps(ctx) {
await revalidate().then((shouldUpdate) => {
if (shouldUpdate) {
ctx.res.writeHead(307, { Location: ctx.req.url });
Copy link
Contributor

@jonthomp jonthomp Jan 19, 2024

Choose a reason for hiding this comment

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

Have you found out why this is required? We have the same - I started going deep, trying to track it down but with this workaround staring me in the face, I couldn't throw too many hours at it for now

Copy link
Member Author

Choose a reason for hiding this comment

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

becuae next is already running, so if you clear require cache mid way though, its router is destroyed.

require cache clear really needs to happen before next entry points are required.

When it comes to federation, next.js is about the worst you money can buy.

Maybe when we introduce true HMR i can find a better solution.

Copy link
Member Author

Choose a reason for hiding this comment

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

I worked aorund this in the past by using a proxy on get initial props and spawn a child worker to run the render and then just return the req/res via the worker and not the host.

Copy link
Contributor

@jonthomp jonthomp Jan 21, 2024

Choose a reason for hiding this comment

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

Ah ok, I had been exploring how I could do something like that, but inside the next.js app. Doing it outside is a rather interesting idea indeed! We haven't needed to run a custom next.js server yet but for this I think we can get one in place. Thanks I'll give it a try!

Copy link
Member Author

Choose a reason for hiding this comment

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

If you are using a custom server, you can easily clear the cache by running the "clear cache" command before it hits the next route handler middleware. You can achieve this by referring to the custom server http example and placing the "require(/next)" in the middleware of HTTP server instead of at the top of the file. By doing this, you can clean and re-require Next.js whenever necessary.

It is entirely doable, but not easy to make it out of the box for users, hence the double redirect hack haha.

If you look in the server dist folder, you can see if Next.js emits some basic HTTP dev server in dev mode. If so, we can patch it via a Webpack plugin by overwriting it or something.

Copy link
Contributor

Choose a reason for hiding this comment

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

@ScriptedAlchemy, we're not currently and would ideally stay away from a custom server. I had a look at your suggestion. but I don't think you can move the require(next) because it's used to prepare the server and create the route handlers.

We have some unique limitations in what we can do in our project, but I'm sure there is a solution with module federation involved. While I continue my journey into the code and try to find a solution, we've had the ok to book some time to chat with you in more detail. Hopefully, that's ok with you? We'll have a look and stick something in calendly

ctx.res.end();
}
});
const initialProps = await Document.getInitialProps(ctx);
const chunks = await flushChunks();
ctx?.res?.on('finish', () => {
revalidate().then((shouldUpdate) => {
if (shouldUpdate) {
console.log('should HMR', shouldUpdate);
}
});
// revalidate().then((shouldUpdate) => {
// if (shouldUpdate) {
// console.log('should HMR', shouldUpdate);
// }
// });
});

return {
Expand Down
4 changes: 2 additions & 2 deletions apps/3001-shop/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
"executor": "@nx/next:build",
"defaultConfiguration": "production",
"options": {
"outputPath": "apps/3001-shop/dist"
"outputPath": "apps/3001-shop"
},
"configurations": {
"development": {
"outputPath": "apps/3001-shop/dist"
"outputPath": "apps/3001-shop"
},
"production": {}
},
Expand Down
4 changes: 2 additions & 2 deletions apps/3002-checkout/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
"executor": "@nx/next:build",
"defaultConfiguration": "production",
"options": {
"outputPath": "{options.outputPath}"
"outputPath": "apps/3002-checkout"
},
"configurations": {
"development": {
"outputPath": "apps/3002-checkout/dist"
"outputPath": "apps/3002-checkout"
},
"production": {}
},
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"extract-i18n:website": "nx run website:extract-i18n",
"sync:pullMFTypes": "concurrently \"node ./packages/enhanced/pullts.js\"",
"app:next:dev": "nx run-many --target=serve --configuration=development -p 3000-home,3001-shop,3002-checkout",
"app:next:prod": "nx run-many --target=build --configuration=production -p 3000-home,3001-shop,3002-checkout",
"app:next:build": "nx run-many --target=build --configuration=production -p 3000-home,3001-shop,3002-checkout",
"app:next:prod": "nx run-many --target=serve --configuration=production -p 3000-home,3001-shop,3002-checkout",
"app:node:dev": "nx run-many --target=serve --configuration=development -p node-host,node-local-remote,node-remote",
"app:runtime:dev": "nx run-many --target=serve -p 3005-runtime-host,3006-runtime-remote,3007-runtime-remote",
"commitlint": "commitlint --edit",
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs-mf/src/federation-noop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ require('next/amp');
require('styled-jsx');
require('styled-jsx/style');
require('next/image');
require('react/jsx-dev-runtime');
// require('react/jsx-dev-runtime');
require('react/jsx-runtime');
10 changes: 10 additions & 0 deletions packages/nextjs-mf/src/plugins/NextFederationPlugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ export class NextFederationPlugin {
// ContainerPlugin will get NextFederationPlugin._options, so NextFederationPlugin._options should be the same as normalFederationPluginOptions
this._options = normalFederationPluginOptions;
new ModuleFederationPlugin(normalFederationPluginOptions).apply(compiler);

const runtimeESMPath = require.resolve(
'@module-federation/runtime/dist/index.esm.js',
);
compiler.hooks.afterPlugins.tap('PatchAliasWebpackPlugin', () => {
compiler.options.resolve.alias = {
...compiler.options.resolve.alias,
'@module-federation/runtime$': runtimeESMPath,
};
});
}

private validateOptions(compiler: Compiler): boolean {
Expand Down
36 changes: 31 additions & 5 deletions packages/nextjs-mf/src/plugins/container/runtimePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function (): FederationRuntimePlugin {
beforeInit(args) {
const { userOptions, shareInfo } = args;
const { shared } = userOptions;

if (!globalThis.usedChunks) globalThis.usedChunks = new Set();
if (shared) {
Object.keys(shared || {}).forEach((sharedKey) => {
if (!shared[sharedKey].strategy) {
Expand All @@ -50,7 +50,7 @@ export default function (): FederationRuntimePlugin {

// if (__webpack_runtime_id__ && !__webpack_runtime_id__.startsWith('webpack')) return args;
const { moduleCache, name } = args.origin;
const gs = (globalThis as any) || new Function('return globalThis')();
const gs = new Function('return globalThis')();
const attachedRemote = gs[name];
if (attachedRemote) {
moduleCache.set(name, attachedRemote);
Expand All @@ -70,9 +70,35 @@ export default function (): FederationRuntimePlugin {
afterResolve(args) {
return args;
},
// onLoad(args) {
// return args;
// },
onLoad(args) {
const { exposeModuleFactory, exposeModule, id } = args;

const moduleOrFactory = exposeModuleFactory || exposeModule;
const exposedModuleExports = moduleOrFactory();
const handler = {
//@ts-ignore
get: function (target, prop, receiver) {
const origMethod = target[prop];
if (typeof origMethod === 'function') {
//@ts-ignore
return function (...args) {
globalThis.usedChunks.add(
//@ts-ignore
id,
);

// console.log(`function as called to ${prop}`, id);
//@ts-ignore
return origMethod.apply(this, args);
};
} else {
return Reflect.get(target, prop, receiver);
}
},
};

return () => new Proxy(exposedModuleExports, handler);
},
resolveShare(args) {
if (
args.pkgName !== 'react' &&
Expand Down
7 changes: 5 additions & 2 deletions packages/nextjs-mf/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ export type { FlushedChunksProps } from './flushedChunks';
* If the function is called on the server side, it imports the revalidate function from the module federation node utilities and returns the result of calling that function.
* @returns {Promise<boolean>} A promise that resolves with a boolean.
*/
export const revalidate = () => {
export const revalidate = (
fetchModule: any = undefined,
force: boolean = false,
) => {
if (typeof window !== 'undefined') {
console.error('revalidate should only be called server-side');
return Promise.resolve(false);
}
// @ts-ignore
return import('@module-federation/node/utils').then((utils) => {
return utils.revalidate();
return utils.revalidate(fetchModule, force);
});
};
1 change: 1 addition & 0 deletions packages/node/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ declare global {
};
}
}
var usedChunks: Set<string>;

var __FEDERATION__: {
__INSTANCES__: Array<{
Expand Down
146 changes: 61 additions & 85 deletions packages/node/src/utils/flush-chunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,104 +91,80 @@ const createShareMap = () => {
*/
// @ts-ignore
const processChunk = async (chunk, shareMap, hostStats) => {
const chunks = new Set();
const [remote, req] = chunk.split('/');
const request = './' + req;
const knownRemotes = getAllKnownRemotes();
//@ts-ignore
if (!knownRemotes[remote]) {
console.error(
`flush chunks: Remote ${remote} is not defined in the global config`,
);
return;
}

try {
// Create a set to store the chunks
const chunks = new Set();
//@ts-ignore
const remoteName = new URL(knownRemotes[remote].entry).pathname
.split('/')
.pop();
//@ts-ignore

// Split the chunk string into remote and request
const [remote, request] = chunk.split('->');
const knownRemotes = getAllKnownRemotes();
const statsFile = knownRemotes[remote].entry
.replace(remoteName, 'federated-stats.json')
.replace('ssr', 'chunks');
let stats = {};

// If the remote is not defined in the global config, return
//@ts-ignore
if (!knownRemotes[remote]) {
console.error(
`flush chunks:`,
`Remote ${remote} is not defined in the global config`,
);
return;
try {
stats = await fetch(statsFile).then((res) => res.json());
} catch (e) {
console.error('flush error', e);
}
//@ts-ignore

try {
// Extract the remote name from the URL
//@ts-ignore
const remoteName = new URL(
//@ts-ignore
globalThis.__remote_scope__._config[remote],
).pathname
.split('/')
.pop();
const [prefix] = knownRemotes[remote].entry.split('static/');
//@ts-ignore

// Construct the stats file URL from the remote config
if (stats.federatedModules) {
//@ts-ignore
const statsFile = globalThis.__remote_scope__._config[remote]
.replace(remoteName, 'federated-stats.json')
.replace('ssr', 'chunks');

let stats = {};
try {
// Fetch the remote config and stats file
stats = await fetch(statsFile).then((res) => res.json());
} catch (e) {
console.error('flush error', e);
}

// Add the main chunk to the chunks set
//TODO: ensure host doesnt embed its own remote in ssr, this causes crash
// chunks.add(
// global.__remote_scope__._config[remote].replace('ssr', 'chunks')
// );
stats.federatedModules.forEach((modules) => {
if (modules.exposes?.[request]) {
//@ts-ignore

// Extract the prefix from the remote config
const [prefix] =
//@ts-ignore
globalThis.__remote_scope__._config[remote].split('static/');
modules.exposes[request].forEach((chunk) => {
chunks.add([prefix, chunk].join(''));

// Process federated modules from the stats object
// @ts-ignore
if (stats.federatedModules) {
// @ts-ignore
stats.federatedModules.forEach((modules) => {
// Process exposed modules
if (modules.exposes?.[request]) {
// @ts-ignore
modules.exposes[request].forEach((chunk) => {
chunks.add([prefix, chunk].join(''));

//TODO: reimplement this
Object.values(chunk).forEach((chunk) => {
// Add files to the chunks set
// @ts-ignore
if (chunk.files) {
// @ts-ignore
chunk.files.forEach((file) => {
chunks.add(prefix + file);
});
}
// Process required modules
// @ts-ignore
if (chunk.requiredModules) {
// @ts-ignore
chunk.requiredModules.forEach((module) => {
// Check if the module is in the shareMap
if (shareMap[module]) {
// If the module is from the host, log the host stats
}
});
}
});
});
}
});
}
Object.values(chunk).forEach((chunk) => {
//@ts-ignore

// Return the array of chunks
return Array.from(chunks);
} catch (e) {
console.error('flush error:', e);
if (chunk.files) {
//@ts-ignore

chunk.files.forEach((file) => {
chunks.add(prefix + file);
});
}
//@ts-ignore

if (chunk.requiredModules) {
//@ts-ignore

chunk.requiredModules.forEach((module) => {
if (shareMap[module]) {
// If the module is from the host, log the host stats
}
});
}
});
});
}
});
}

return Array.from(chunks);
} catch (e) {
// catch just in case
console.error('flush error:', e);
}
};

Expand Down
Loading