Skip to content

"Service worker generation failed: Too many open files" with an assets folder with large number of files #45133

Closed

Description

@LucaBruni

Which @angular/* package(s) are the source of the bug?

service-worker

Is this a regression?

Yes

Description

We recently migrated our large single page application from Angular 9 to Angular 13.
Our production build enables the service worker generation, and the "assetsGroups->resources->files " section include "/assets/**"
During our first production build on a Windows 10 machine (16GB ram), we received this message:

Service worker generation failed.
EMFILE: too many open files,

Our application's assets folder contains all the dictionaries for at least 13 different languages: every folder cointains at least a thousand files: the service worker generation stops right in the middle.
We tried to split the assetsGroups in multiple elements (one for each language folder), but the service worker generation stopped exactly in the same spot.

Next we checked the source code for the assetsGroups generation and the difference between angular 9 and 13. If we are looking in the right source file, from what we saw seems like that the hashing of all assets files is responsible for the error (\node_modules@angular-devkit\build-angular\src\utils\service-worker.js)

Attached to the issue you'll find a zip with our sample app: (in any case, we merely create a new app with "ng new", added the angular/service-worker package and the assetsGroup section, and used "ng build --configuration=production"

ang13Test.zip

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

Service worker generation failed: Too many open files

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 13.2.2
Node: 16.14.0
Package Manager: npm 8.4.1
OS: win32 x64

Angular: 13.2.1
... animations, cdk, common, compiler, compiler-cli, core, forms
... language-service, localize, material, platform-browser
... platform-browser-dynamic, router, service-worker

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1302.2
@angular-devkit/build-angular   13.2.2
@angular-devkit/core            13.2.2
@angular-devkit/schematics      13.2.2
@angular/cli                    13.2.2
@angular/flex-layout            13.0.0-beta.38
@schematics/angular             13.2.2
ng-packagr                      13.2.1
rxjs                            6.5.5
typescript                      4.5.5

Intel I7 4771 3.50Ghz
16GB Ram

Anything else?

No response

Activity

  1. added
    area: service-worker
    on Feb 18, 2022
  2. added this to the needsTriage milestone on Feb 18, 2022
  3. ajafff commented on Feb 18, 2022

    @ajafff

    The issue seems to be this line:

    const allMatchedHashes = await Promise.all(allMatchedFiles.map(file => this.fs.hash(file)));

    it basically tries to read and hash all files in parallel. instead it should use some kind of queue to limit the parallelism. that ensures only a limited number of files is open at the same time.

  4. gkalpak commented on Feb 18, 2022

    @gkalpak
    Member

    Thx for reporting this, @LucaBruni 👍
    @ajafff is spot on!

    Would any of you be interested in creating a pull request? 😃

  5. LucaBruni commented on Feb 23, 2022

    @LucaBruni
    Author

    In our solution we used a non-configurable "100" elements limit.
    If that's ok, and adding a dependency to "p-limit" is not a problem, we'll submit a PR.
    Otherwise we can create a suboptimal solution: just let us know.

  6. gkalpak commented on Feb 24, 2022

    @gkalpak
    Member

    Thx for getting back, @LucaBruni.
    A non-configurable limit is fine for now, I believe. I was thinking of a higher limit tbh (500 or 250), as I think that should be fine on all common platforms. Is your limit of 100 arbitrary or did you find higher limits to be problematic?

    Regarding the implementation, I was thinking that bringing in another dependency (such as p-limit) would be an overkill for the task at hand. I was thinking about a simple helper function that would allow us to process an array of items in batches. Something like:

    function processInBatches<I, O>(
        items: I[], batchSize: number, processFn: (item: I) => O | Promise<O>): Promise<O[]> {
      const batches = [];
    
      for (let i = 0; i < items.length; i += batchSize) {
        batches.push(items.slice(i, i + batchSize));
      }
    
      return batches.reduce(
          async (prev, batch) =>
              (await prev).concat(await Promise.all(batch.map(item => processFn(item)))),
          Promise.resolve<O[]>([]));
    }

    Then, we could use it in generator.ts like this (with whatever limit we decide on):

         const allMatchedFiles = ([] as string[]).concat(...Array.from(filesPerGroup.values())).sort();
    -    const allMatchedHashes = await Promise.all(allMatchedFiles.map(file => this.fs.hash(file)));
    +    const allMatchedHashes =
    +        await processInBatches(allMatchedFiles, 500, file => this.fs.hash(file));
         allMatchedFiles.forEach((file, idx) => {
           hashTable[joinUrls(this.baseHref, file)] = allMatchedHashes[idx];
         });

    WDYT, @LucaBruni?

  7. LucaBruni commented on Feb 25, 2022

    @LucaBruni
    Author

    Thanks for the response: 500 is ok: our 100 limit was maybe too much on the safe side :D
    Our critical threshold was around 5000, but I have no idea if that limit is ram-dependant or not.
    Your batch solution works well for me.

  8. gkalpak commented on Feb 25, 2022

    @gkalpak
    Member

    That's great! So, if you wanted to put that code in a PR and throw in a test or two, I would be happy to review and get it merged 😃

  9. LucaBruni commented on Mar 1, 2022

    @LucaBruni
    Author

    We are ready to create PR: we did not create additional tests as the existing ones should cover our needs.
    Also, we have no idea how to create a test that involves hashing of 10000 files :)
    (edit: we tested the service-worker dist on our sample and works just fine)
    Let us know.

  10. gkalpak commented on Mar 2, 2022

    @gkalpak
    Member

    Regarding the test:
    We use a MockFilesystem in tests (example). I was thinking that we could construct a MockFilesystem instance with more files than the limit we have set and also overwrite the hash method to keep track of how many calls there are simultaneously. Then we could check that our limit was not exceeded.

    I.e. something like:

    class HashTrackingMockFilesystem extends MockFilesystem {
      public maxConcurrentHashings = 0;
      private concurrentHashings = 0;
    
      /** @override */
      async hash(path: string): Promise<string> {
        // Increase the concurrent hashings count.
        this.concurrentHashings += 1;
        this.maxConcurrentHashings = Math.max(this.maxConcurrentHashings, this.concurrentHashings);
    
        // Artificial delay to check hashing concurrency.
        await new Promise(resolve => setTimeout(resolve, 250));
    
        // Decrease the concurrent hashings count.
        this.concurrentHashings -= 1;
        
        return super.hash(path);
      }
    }

    Does that make sense?

  11. LucaBruni commented on Mar 4, 2022

    @LucaBruni
    Author

    Yes, it does make sense: we used your HashTrackingMockFilesystem and added a single test.
    Thanks

  12. added a commit that references this issue on Mar 8, 2022
    cff1c56
  13. angular-automatic-lock-bot commented on Apr 8, 2022

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  14. locked and limited conversation to collaborators on Apr 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: service-worker

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions