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: upgrade assets-controllers to v38.2.0 #27629

Merged
merged 12 commits into from
Oct 10, 2024

Conversation

sahar-fehri
Copy link
Contributor

@sahar-fehri sahar-fehri commented Oct 4, 2024

Description

Upgrade assets-controllers to v38.2.0

Open in GitHub Codespaces

Related issues

Fixes:

Manual testing steps

  1. Go to this page...

Screenshots/Recordings

Before

After

Pre-merge author checklist

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.

Copy link
Contributor

github-actions bot commented Oct 4, 2024

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

Copy link

socket-security bot commented Oct 4, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@metamask/[email protected] None 0 123 kB metamaskbot
npm/[email protected] None 0 37.6 kB dirtyhairy

🚮 Removed packages: npm/@metamask/[email protected], npm/@metamask/[email protected], npm/[email protected]

View full report↗︎

@sahar-fehri
Copy link
Contributor Author

@metamaskbot update-policies

@sahar-fehri sahar-fehri added the needs-assets-ux-review A shared label between the Assets and UX team to flag PRs ready for consolidated team review. label Oct 4, 2024
@metamaskbot
Copy link
Collaborator

Policies updated.
👀 Please review the diff for suspicious new powers.

🧠 Learn how: https://lavamoat.github.io/guides/policy-diff/#what-to-look-for-when-reviewing-a-policy-diff

bergeron
bergeron previously approved these changes Oct 4, 2024
@sahar-fehri
Copy link
Contributor Author

@metamaskbot update-policies

@metamaskbot
Copy link
Collaborator

Policies updated.
👀 Please review the diff for suspicious new powers.

🧠 Learn how: https://lavamoat.github.io/guides/policy-diff/#what-to-look-for-when-reviewing-a-policy-diff

@sahar-fehri sahar-fehri marked this pull request as ready for review October 7, 2024 10:51
@sahar-fehri sahar-fehri requested review from a team as code owners October 7, 2024 10:51
@metamaskbot
Copy link
Collaborator

Builds ready [f856efb]
Page Load Metrics (1910 ± 105 ms)
PlatformPageMetricMin (ms)Max (ms)Average (ms)StandardDeviation (ms)MarginOfError (ms)
ChromeHomefirstPaint23024981770542260
domContentLoaded160024881888210101
load160424981910218105
domInteractive18187614421
Bundle size diffs [🚀 Bundle size reduced!]
  • background: 1 Bytes (0.00%)
  • ui: 2 Bytes (0.00%)
  • common: -12.14 KiB (-0.16%)

Comment on lines 17 to 18
- const { CID } = await import("multiformats");
+ const { CID } = await Promise.resolve().then(() => _interopRequireWildcard(require("multiformats")));
Copy link
Contributor

@MajorLift MajorLift Oct 7, 2024

Choose a reason for hiding this comment

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

The await import() call being left in there was intentional. Not only is await import() available to commonjs in node v12+, passing an ESM-only module like multiformats into require also crashes node or otherwise may cause undefined behavior.

The import call causing failed test runs is also expected, because dynamic import is only available behind a NODE_OPTIONS=--experimental-vm-modules flag. This is why we've added that to all of our core test scripts (https://github.com/MetaMask/core/blob/main/packages/assets-controllers/package.json#L44-L47). We'll probably need to do the same in extension and mobile.

I guess the question here is whether we can be sure that _interopRequireWildcard is actually executing the CID import correctly, or if it's masking broken behavior.

Another question would be how to handle similar scenarios (upstream ESM-only modules) going forward. Consistently using await import() is the only way that makes sense to me.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@MajorLift thnx a lot for looking into this 🙏 I have added some logs with this current patch and it looks like its working fine, its able to fetch CID and display the NFT media;

Without the patch, i can see the error __import__ is not defined in console again and its not displaying the images correctly;
Screenshot 2024-10-07 at 19 05 08

Thanks for referencing the related test script update on core 🙏 this is not only related to tests, correct? since im able to see the error when running the app locally?

Copy link
Contributor

Choose a reason for hiding this comment

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

The browser uses only ESM, so that's a really weird error message. Maybe it's coming from selenium or some other node process? I tried adding the flag to the e2e test build scripts (#27675) but I'm still getting the same error.

Since you verified that the import is working correctly I think we can move forward with the current patch. Thanks for being on top of that.

Would be nice to figure this error out for the future though. I'll do some more digging.

Copy link
Contributor

Choose a reason for hiding this comment

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

This code is running under lavamoat and dynamic import is deliberately not supported - hence a transform changing all functions named import into __import__

We currently can't have dynamic import work inside compartments. It's not feasible to intercept it the way we'd need to. Since the bundler we use doesn't support it, the dynamic import would be called directly in the browser and "multiformats" is not a URL to a script file, so it would fail with a different error even if LavaMoat transforms weren't there to prevent it.
I recommend addressing this somehow in a minor refactor of the assets controller if it's intended for use in MetaMask.

When we switch to webpack with LavaMoat webpack plugin it's possible webpack will transform the dynamic import into its own syntax if configured for that, but that's the only hope for using dynamic require I see for now. Didn't check how that behaves yet. I can get back to you later.

Copy link
Contributor

@MajorLift MajorLift Oct 8, 2024

Choose a reason for hiding this comment

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

@naugtur Thanks for the insight! I wasn't aware that Lavamoat did this. I'll have to look into what else it blocks.

Unfortunately this a language-level CJS/ESM interop issue that isn't specific to assets-controllers and multiformats -- it applies to any ESM-only module in our dependency tree.

Most of our modules are natively CJS. We use ESM syntax because we write in TypeScript, but we expose dual CJS/ESM builds and our manifests do not specify the "module": "type" property. Because of this, the only way for our modules to handle ESM imports in a CJS-compatible manner is with dynamic import syntax i.e. require doesn't work, and neither does static import syntax that transpiles down to require.

True CommonJS modules can require an ESM-transpiled-to-CJS module, since they’re both CommonJS at runtime. But in Node.js, require crashes if it resolves to an ES module. This means published libraries cannot migrate from transpiled modules to true ESM without breaking their CommonJS (true or transpiled) consumers:

// @Filename: node_modules/dependency/index.js
export function doSomething() { /* ... */ }
// @Filename: dependent.js
import { doSomething } from "dependency";
// ✅ Works if dependent and dependency are both transpiled
// ✅ Works if dependent and dependency are both true ESM
// ✅ Works if dependent is true ESM and dependency is transpiled
// 💥 Crashes if dependent is transpiled and dependency is true ESM

https://www.typescriptlang.org/docs/handbook/modules/appendices/esm-cjs-interop.html#cannot-require-a-true-es-module

This issue was previously masked by our usage of the outdated { module: "commonjs", moduleResolution: "node10" } tsconfig options. However, the core and snaps repos recently updated to "node16" for both options, which enforces sound module resolution restrictions and therefore prohibits ESM-only modules from being passed into require calls. This update is expected to propagate to all of our TypeScript repos.

In this specific case, we can use the patch as is because multiformats happens to work with require calls without breaking things, but this is a coincidence we can't rely on for all ESM packages in general.

To preserve the ban on dynamic import syntax I see three possibilities:

  1. Remove all ESM-only modules from all of our dependency trees, or replace them with CJS-compatible forks (we've done this before e.g. @metamask/superstruct).
  2. Convert all of our modules to "true ESM".
  3. Start using a bundler like Webpack in all of our repos to generate builds (assuming it can be set up to generate dual builds for dependencies in a way that would sidestep this issue).

All of these would be major, if not prohibitive, undertakings.

Copy link
Contributor

Choose a reason for hiding this comment

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

1 and 2 are not options we're fond of.
With the exception of: until we have a lavamoat-node that supports ESM (we're working on it) we might sometimes have to eliminate esm-only packages from builds that run under lavamoat.

We should be able to switch to webpack in the foreseeable future. LavaMoat Webpack plugin is reaching 1.0 by the end of this year and we're wery close to getting a working MetaMask build out of it. 3rdparty audit is finishing too.

Meanwhile,
Joyee has made it possible to require(esm) in Node.js
https://nodejs.org/api/esm.html#interoperability-with-commonjs
https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/

So we're looking for a solution to the typescript situation that we can live with for limited time.

Copy link
Contributor

@MajorLift MajorLift Oct 8, 2024

Choose a reason for hiding this comment

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

Agreed that 1, 2 aren't the most ideal options. ;)

I wasn't aware of --experimental-require-module, but it looks like a great stopgap. Fingers crossed that we don't run into an ESM package with top-level await.

Based on anecdotal experience from applying Node16 to core and snaps, our usage of CJS-incompatible packages is uncommon enough that we should be able to handle them on a case-by-case basis, at least for the time being.

However, the few exceptions can have an outsized impact. Migrating from superstruct to @metamask/superstruct ended up being a massive undertaking because it required us to update and release basically all transitive dependents. Removing the imports for such a widely used package will probably present difficulties as well. Hopefully we don't come across such a scenario again any time soon.

Anyway, it's very good to know that there are fundamental fixes on the way, and thank you for your work on that! Especially excited to potentially have lavamoat-node directly applied to our upstream libraries.

Comment on lines 30 to 33
-import $cockatiel from "cockatiel";
-const { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap, CircuitState } = $cockatiel;
+
+import { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap, CircuitState } from "cockatiel";
Copy link
Contributor

Choose a reason for hiding this comment

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

The fix makes sense, but I don't understand why we're getting a default import here in the first place.

@Mrtenz Is it possible that this is an artifact from ts-bridge processing mixed type vs. value imports in a single import statement?

This is the original code:

import {
  circuitBreaker,
  ConsecutiveBreaker,
  ExponentialBackoff,
  handleAll,
  type IPolicy,
  retry,
  wrap,
  CircuitState,
} from 'cockatiel';

https://github.com/MetaMask/core/blob/main/packages/assets-controllers/src/token-prices-service/codefi-v2.ts#L4-L13

Copy link
Member

Choose a reason for hiding this comment

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

This is not related to type imports, those are supported by ts-bridge. I suspect this is caused by a difference in how Node.js and Webpack handle module detection... 😞

ts-bridge detects whether a package is CommonJS or ESM following Node.js' module resolution algorithm. If the package is detected as CommonJS, it checks what exports it has (using cjs-module-lexer, used by Node.js as well). If some CommonJS exports are not detected, the import is rewritten to a default import, as this is supposed to increase compatibility.

cockatiel has an ESM version, but it's only specified in the module field, which is not used by Node.js (but is used by Webpack). The CommonJS export seems to use a syntax that is not supported by cjs-module-lexer (though I need to verify this), so the exports are not detected.

There are several options here:

  1. We apply this patch.
    • We could do this as temporary solution to get this PR merged either way.
  2. We disable the module field in Webpack's module resolution.
    • This aligns it more with Node.js module resolution, but may result in a larger bundle if many dependencies use the module field, but not package.json exports.
  3. We submit a PR to cockatiel to use the exports field in package.json to allow Node.js to use the ESM version as well.
    • I will do this regardless, but I'm not sure how long it will take for this to be merged and released.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yet another CJS/ESM interop scenario to keep an eye out for. :( Really appreciate the breakdown and your looking into this. I had a couple of questions:

If some CommonJS exports are not detected, the import is rewritten to a default import, as this is supposed to increase compatibility.

According to @sahar-fehri, this causes the following error:

I had this error when doing yarn build:storybook;

export 'default' (imported as '$cockatiel') was not found in 'cockatiel'

Is storybook an outlier here, or will we always see this error if there is no default export?

The CommonJS export seems to use a syntax that is not supported by cjs-module-lexer

Also, for this issue, is an upstream update pretty much the only possible fix?

Copy link
Member

Choose a reason for hiding this comment

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

I guess you could say Webpack is the outlier because it looks at the module field. This is completely valid in Node.js for example:

import $cockatiel from 'cockatiel';
const { circuitBreaker } = $cockatiel;

console.log(circuitBreaker); // [Function: circuitBreaker]

Because Node.js loads the CommonJS version, but Webpack loads the ESM version.

Also, for this issue, is an upstream update pretty much the only possible fix?

I'm leaning towards configuring Webpack to stop using module for better Node.js compatibility. But for a proper fix where both are able to use ESM, without the need for a patch, it will need to be fixed upstream.

Copy link
Member

Choose a reason for hiding this comment

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

We could apply this as patch temporarily until it's updated, rather than patching assets-controller:

Copy link
Contributor

Choose a reason for hiding this comment

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

Really like the idea of patching closer to the root cause.

@sahar-fehri To clarify, we'd want to remove this section of the assets-controllers patch altogether (lines 22-36), and instead add a new patch file for cockatiel that contains the changes in the cockatiel PR #102 linked above.

The Webpack issue is really... not great. I also think configuring Webpack would be the preferable solution here. Fixing or patching every upstream package that triggers this issue doesn't seem advisable or feasible.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you guys for looking into this 🙏 🙏
Just to clarify; so its okay to keep the patch for cockatiel and merge it just temporarily; until this PR is merged?

Copy link
Member

Choose a reason for hiding this comment

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

I just realised we need the assets-controller patch regardless, because it won't with the ESM version of cockatiel otherwise anyway. The cockatiel patch would need to be applied to the core repo, requiring a new release, etc.

So I think the easiest way forward for now is to keep this patch as it is, and hope that cockatiel gets updated quickly 😅.

Copy link
Contributor

Choose a reason for hiding this comment

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

Sounds like a plan! Technically, anything downstream of assets-controllers would need to have this patch applied, but that's just our two clients so doesn't seem too terrible. In any case, it makes sense to avoid a controller release containing a patch. Hopefully the cockatiel maintainers will be responsive.

Copy link
Contributor

Choose a reason for hiding this comment

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

using modules across ESM/CJS boundaries differs a lot across tools and environments too. Here's some examples: https://github.com/endojs/endo-e2e-tests/blob/main/matrix/table.md

MajorLift
MajorLift previously approved these changes Oct 7, 2024
Copy link
Contributor

@MajorLift MajorLift left a comment

Choose a reason for hiding this comment

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

LGTM! For context, both threads above concluded that we should use the patch file as is for now, but look into follow-up measures.

privacy-snapshot.json Outdated Show resolved Hide resolved
@metamaskbot
Copy link
Collaborator

Builds ready [14a7051]
Page Load Metrics (2048 ± 133 ms)
PlatformPageMetricMin (ms)Max (ms)Average (ms)StandardDeviation (ms)MarginOfError (ms)
ChromeHomefirstPaint78324881942336161
domContentLoaded169528212017271130
load172528682048276133
domInteractive28115472311
Bundle size diffs [🚀 Bundle size reduced!]
  • background: 1 Bytes (0.00%)
  • ui: 2 Bytes (0.00%)
  • common: -12.14 KiB (-0.16%)

naugtur
naugtur previously approved these changes Oct 9, 2024
Copy link
Contributor

@naugtur naugtur left a comment

Choose a reason for hiding this comment

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

supply-chain wise this is fine.
I think patching is a good workaround for cjs/esm compatibility issues we're facing.
The async step is likely unnecessary

const cid = index !== -1 ? url.substring(0, index) : url;
const path = index !== -1 ? url.substring(index) : undefined;
- const { CID } = await import("multiformats");
+ const { CID } = await Promise.resolve().then(() => _interopRequireWildcard(require("multiformats")));
Copy link
Contributor

Choose a reason for hiding this comment

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

Going back to the change itself:

The await on an empty promise before running synchronous require seems unnecessary. Does anything depend on this step being asynchronous? Doesn't seem so.

Suggested change
+ const { CID } = await Promise.resolve().then(() => _interopRequireWildcard(require("multiformats")));
+ const { CID } = _interopRequireWildcard(require("multiformats"));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think in v37 this change was introduced:
BREAKING: getIpfsCIDv1AndPath, getFormattedIpfsUrl are now async functions (MetaMask/core#3645)

This patch update matches the generated build after the V37 update;

Copy link
Contributor

@MajorLift MajorLift Oct 9, 2024

Choose a reason for hiding this comment

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

The await is necessary in the CJS source code since we're forced to use a dynamic import. But in the build output that we're patching we definitely don't need to both then and await the synchronous _interopRequireWildcard call.

@naugtur's suggestion looks good to me, although I'd feel better with another manual check on whether CID is sourced at runtime.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you @MajorLift and @naugtur 🙏 i have removed the empty promise; could you please approve again and we merge this 🙏

Copy link

sonarcloud bot commented Oct 10, 2024

@metamaskbot
Copy link
Collaborator

Builds ready [a6a230a]
Page Load Metrics (1787 ± 85 ms)
PlatformPageMetricMin (ms)Max (ms)Average (ms)StandardDeviation (ms)MarginOfError (ms)
ChromeHomefirstPaint15212181177516780
domContentLoaded15142083175415474
load15232187178717685
domInteractive2683462010
Bundle size diffs [🚀 Bundle size reduced!]
  • background: 1 Bytes (0.00%)
  • ui: 2 Bytes (0.00%)
  • common: -12.17 KiB (-0.16%)

@sahar-fehri sahar-fehri added this pull request to the merge queue Oct 10, 2024
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Oct 10, 2024
@sahar-fehri sahar-fehri added this pull request to the merge queue Oct 10, 2024
Merged via the queue into develop with commit 97758a6 Oct 10, 2024
78 checks passed
@sahar-fehri sahar-fehri deleted the feat/update-assets-controllers-v38.2.0 branch October 10, 2024 10:34
@github-actions github-actions bot locked and limited conversation to collaborators Oct 10, 2024
@metamaskbot metamaskbot added the release-12.7.0 Issue or pull request that will be included in release 12.7.0 label Oct 10, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
needs-assets-ux-review A shared label between the Assets and UX team to flag PRs ready for consolidated team review. release-12.7.0 Issue or pull request that will be included in release 12.7.0 team-assets
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

7 participants