Skip to content

Improve packaging performance #8586

Open

Description

@medikoo

Excerpt from: #6580

While bigger packaging refactor is scheduled, it appears we can improve significantly our current packing logic in place with following steps:

Implementation proposal

  1. (if package.excludeDevDepencies: true) Resolve all devDependencies, and coin their paths in node_modules (take into account Dev dep exclusion should log on package.json errors #4358 error case)
  2. Resolve all files in a service folder (if package.excludeDevDepencies: true avoid traversing into dev dependencies) - To ensure better performance construct logic with callbacks not promises.
  3. Show warning if symlinks are approached (we may consider adding support for them in next PR)
  4. Filter obtained files list against eventual package patterns, but intelligently, do not test to be included filenames against include patterns, and do not test excluded filenames against exclude patterns.

Activity

  1. self-assigned this
    on Dec 7, 2020
  2. ryan-roemer commented on Dec 7, 2020

    @ryan-roemer
    Contributor

    In case it helps @medikoo the means by which serverless-jetpack does this faster production dependency inference from node_modules is entirely encapsulated in a small library: https://github.com/FormidableLabs/inspectdep that just finds all prod dependencies from a starting point with a few other options.

    For a different discussion, long term, I'm not sure if serverless-jetpack is going to continue supporting this current approach (e.g. the drop-in serverless packaging replacement) and will probably commit more to tracing actually used dependencies like webpack/etc. does just with real files not a mutated single bundle. In case you're interested, we have a similar separate library for just tracing (I know you have created a similar one too -- ours uses acorn and handles a lot of common non-static-import cases): https://github.com/FormidableLabs/trace-deps. We actually just produced a tool to package with trace-deps but without using serverless at all (for our projects doing Lambda with straight Terraform): https://github.com/FormidableLabs/trace-pkg

  3. medikoo commented on Dec 8, 2020

    @medikoo
    ContributorAuthor

    In case it helps @medikoo the means by which serverless-jetpack does this faster production dependency inference from node_modules is entirely encapsulated in a small library: https://github.com/FormidableLabs/inspectdep that just finds all prod dependencies from a starting point with a few other options.

    Great thanks @ryan-roemer I definitely planned to look into how you solved that on your side. It's definitely outstanding work. It's likely we will just depend on this library, it all depends on obtained numbers and how that fits us organization wise

    btw. instead of taking only prod dependencies, have you considered other approach, where it's all but dev deps that are taken? Logically it's more on pair with our excludeDevDepencies option (which we anyway plan to deprecate)

    For a different discussion, long term, I'm not sure if serverless-jetpack is going to continue supporting this current approach (e.g. the drop-in serverless packaging replacement)

    Assuming we will internally fix this problem with this issue, there may no longer be a point in serverless-jetpack for addressing that.

    and will probably commit more to tracing actually used dependencies like webpack/etc.

    That's the next step, we would also envision to have in a core, but it's nowhere near, so having serverless-jetpack handling that is definitely very helpful. Anyway we'll definitely check all those tracing libraries you've listed

  4. ryan-roemer commented on Dec 8, 2020

    @ryan-roemer
    Contributor

    instead of taking only prod dependencies, have you considered other approach, where it's all but dev deps that are taken?

    My apologies for not being a bit more specific 😄 inspectdep considers "production" dependencies to be dependencies and optionalDependencies. But not devDependencies or peerDependencies (reasoning for the latter of which should be a prod dependency elsewhere in the project).

    Assuming we will internally fix this problem with this issue, there may no longer be a point in serverless-jetpack for addressing that.

    Yep! That sounds right.

  5. juanjoDiaz commented on Dec 9, 2020

    @juanjoDiaz
    Contributor

    Bringing the discussion here as suggested by @medikoo

    The resolveFilePathsFromPatterns function (https://github.com/serverless/serverless/blob/master/lib/plugins/package/lib/packageService.js#L221-268) is the function that receives the include/exclude props and returns the files to include.

    It uses globby to match all the files given the patterns (patterns is simply exclude + include) and then uses micromatch on the globby results to remove the excludes.
    Apart from adding an extra unnecessary dependency, this approach involves doing the pattern matching twice: one by globby and a second one done manually pattern by pattern using micromatch.

    My suggestion is to do everything in a single pass with globby as I did in #8581 since the whole micromatch filtering is filtering over already filtered results.

    In code, I suggest to change:

        return globby(['**'].concat(params.include), {
          cwd: path.join(this.serverless.config.servicePath, prefix || ''),
          dot: true,
          silent: true,
          follow: true,
          nodir: true,
          expandDirectories: false,
        }).then(allFilePaths => {
          const filePathStates = allFilePaths.reduce((p, c) => Object.assign(p, { [c]: true }), {});	
          patterns	
            // micromatch only does / style path delimiters, so convert them if on windows	
            .map(p => {	
              return process.platform === 'win32' ? p.replace(/\\/g, '/') : p;	
            })	
            .forEach(p => {	
              const exclude = p.startsWith('!');	
              const pattern = exclude ? p.slice(1) : p;	
              micromatch(allFilePaths, [pattern], { dot: true }).forEach(key => {	
                filePathStates[key] = !exclude;	
              });	
            });	
          const filePaths = Object.entries(filePathStates)	
            .filter(r => r[1] === true)	
            .map(r => r[0]);	
          if (filePaths.length !== 0) return filePaths;	
          throw new this.serverless.classes.Error('No file matches include / exclude patterns');	
        });

    by

        return globby(['**'].concat(params.include), {
          cwd: path.join(this.serverless.config.servicePath, prefix || ''),
          dot: true,
          silent: true,
          follow: true,
          nodir: true,
          expandDirectories: false,
        }).then(allFilePaths => {	
          if (allFilePaths.length !== 0) return allFilePaths;	
          throw new this.serverless.classes.Error('No file matches include / exclude patterns');	
        });

    Let me know if you have any comments or if I should make the PR.

  6. ryan-roemer commented on Dec 9, 2020

    @ryan-roemer
    Contributor

    I love the idea for getting rid of include/exclude and doing just patterns straight for globby(). One suggestion that I've made elsewhere before is to get rid of that initial mandatory '**' and start with either nothing or maybe node_modules/**. My original comment is here with this being the first suggestion. The second suggestion is doing what you're doing and getting rid of the extra pattern matching outside the globby() phase so yay 🎉 !

  7. juanjoDiaz commented on Dec 9, 2020

    @juanjoDiaz
    Contributor

    Totally agree with removing '**' and only use it if there are no include patterns provided.
    That was my next suggestion once we agree on the globby issue.

  8. medikoo commented on Dec 10, 2020

    @medikoo
    ContributorAuthor

    @juanjoDiaz thanks for looking into that. Problem with globby is that for every pattern it does another file search (it's at least how it looks from it's internals). It's highly ineffective, and due to that I would lean towards approach I've outlined in description which in short is:
    (1) with most efficient (not promise based) approach resolve all service files (eventually excluding dev dependencies)
    (2) Apply glob patterns via micromatch on them.

    It might be of course a bit more intelligent, e.g. while traversing the files we may take into account patterns config and do not dive into directories which we know are to be fully excluded.

  9. medikoo commented on Dec 10, 2020

    @medikoo
    ContributorAuthor

    One suggestion that I've made elsewhere before is to get rid of that initial mandatory '**'

    I think that approach could be applied only to cases where user explicitly configured !**, as otherwise Framework implies to package everything (it means that any inclusion rules are ineffective, it's just eventual exclusions that play part).

    Anyway that makes a great point, that we probably should have two very different packaging paths. One when no !** is provided, and one where there is (e.g. in that case, we probably should not dive into traversing service folder).

  10. juanjoDiaz commented on Dec 10, 2020

    @juanjoDiaz
    Contributor

    I see.

    Regarding ./**, the easiest but breaking change (so next major version) would be to use ./** only if no patterns are provided. If patterns are provided, then the user needs to add ./** if he really wants it all.
    But let's keep the ./** discussion for once we solve the globbing problem.

    globby(['**'].concat(params.include)) is essentially the same as globby(['**']) unless there are negated patterns or parent directories. Even for negated directories, since we are doing the micromatch filtering on all the patterns, the negated patterns are applied there. So we are applying them twice and, if micromatch is really faster than globby we would be better off just doing globby(['**']) adding there any possible ../ directory and then using micromatch.

    So my question is: why is globby any slower than globbing each pattern against each and every file using micromatch?

    globby is just fast-glob with 2 extra options: gitignore and expandDirectories and we not using either of those.
    Would using fast-glob directly be faster?
    Should benchmark a faster alternative like https://github.com/terkelg/tiny-glob?

    Should we just write a function to list all files under a folder recursively and use micromatch against that if it's really faster?

    Btw, is there any benchmark or example to test performance here? Or how are we measuring the potential improvements?

  11. ryan-roemer commented on Dec 10, 2020

    @ryan-roemer
    Contributor

    As a related aside, my intuition is that globby() vs a more specific library for pure pattern matching of already known file names isn't that big of a difference. The huge difference comes from file I/O. The fastest solution is likely whatever minimizes disk reads...

  12. juanjoDiaz commented on Dec 10, 2020

    @juanjoDiaz
    Contributor

    Yeah. globby read disk whereas micromatch does not.

    I would expect that something like globby does a recursive traverse of the cwd using some implementation similar to micromatch internally to see if it should include or not the current file/dir.

    The brute-force approach would be to get the whole list of files recursively and then apply the matching.
    The smart way would be to consolidate duplicate patterns, stop on folders that you know won't require a deeper inspection, etc. (however that's not trivial).

    The current "optimization" points out that brute-forcing is faster than globby which is really surprising for me.
    The author in #5574 claims that using micromatch is faster because glob uses minimatch. However, we don't use glob. We use globby which uses fast-glob under the hood which uses micromatch and picomatch.

    Both fast-glob and tiny-glob provide benchmarks but none of them really help much choosing.

    Having a test would really help here.
    I tried globbing some random patterns in the codebase of this project (30558 files include node_modules) and it always took a few ms...

  13. medikoo commented on Dec 11, 2020

    @medikoo
    ContributorAuthor

    So my question is: why is globby any slower than globbing each pattern against each and every file using micromatch?

    @juanjoDiaz globby runs actual FS search (fast-glob) for each pattern, while with micromatch we're testing pattern against retrieved filename (no FS access involved)

    Would using fast-glob directly be faster?

    It doesn't support multiple patterns well. At least as I tested ['!foo', 'foo/bar/**'] wouldn't resolve files from foo/bar folder

    The huge difference comes from file I/O.

    @ryan-roemer that's mostly true, but that depends on what setup you work on, e.g. on recent MBPs if you traverse folder with thousands of files and for each file you retrieve stats, you'll find that this operation would be ca 40% faster when constructed with callbacks interface than with promises (which introduce tons of artificial ticks and promise objects to be garbage collected),

    but ofc the slower the FS, the more bottleneck it is to care about

  14. juanjoDiaz commented on Dec 11, 2020

    @juanjoDiaz
    Contributor

    globby runs actual FS search (fast-glob) for each pattern, while with micromatch we're testing pattern against retrieved filename (no FS access involved)

    That's right. However, to run micromatch you need the file names first.
    The current optimization and the discussion here imply that it's faster to just get all the possible file names for all includes and then simply run micromatch over all of them which still sounds strange to me...

  15. BenLanglois commented on Feb 24, 2021

    @BenLanglois

    I recently experienced a performance issue related to this when packaging my project. In serverless.yml, we specify:

    package:
      exclude:
        '**'

    This disables the default behaviour of including all files in the current directory. However, globby is only passed params.include, not params.exclude. So, globby will return all files in the project directory only for micromatch to later filter out most of them. This means that using exclude: '**' instead of include: '!**' has a big performance impact.

    To fix this, globby needs to consider excluded patterns too. The fix for this should be simple: instead of

    globby(['**'].concat(params.include), /* ... */)

    use

    globby(['**'].concat(patterns), /* ... */)

    since patterns contains params.include and the negation of params.exclude.

  16. ryan-roemer commented on Feb 24, 2021

    @ryan-roemer
    Contributor

    Yeah @BenLanglois -- I've got a long comment and suggestion for future packaging tweaks here that also discusses the performance problems you've also identified: #6007 (comment)

  17. added this to the v3-ready milestone on Apr 16, 2021
  18. removed this from the v3-ready milestone on Jun 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug/designcat/packagingenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions