Skip to content

Slow "unreachable modules" rule #989

@neelance

Description

@neelance

This rule has become very slow (additional 25 seconds) on our large repo:

{
  name: "no-unreachable-from-entrypoint",
  severity: "error",
  from: {
    path: entrypointsRegex,
  },
  to: {
    path: "src",
    pathNot: entrypointsRegex,
    reachable: false,
  },
},

Here is a diff that already cuts half of the duration:

diff --git a/src/enrich/derive/reachable.mjs b/src/enrich/derive/reachable.mjs
index a384cdcb..99ad6049 100644
--- a/src/enrich/derive/reachable.mjs
+++ b/src/enrich/derive/reachable.mjs
@@ -139,11 +139,10 @@ function addReachesToModule(pModule, pGraph, pIndexedGraph, pReachableRule) {
   return pModule;
 }
 
-function addReachableToModule(pModule, pGraph, pIndexedGraph, pReachableRule) {
-  const lFromModules = pGraph.filter(isModuleInRuleFrom(pReachableRule));
+function addReachableToModule(pModule, pIndexedGraph, pReachableRule, pFromModules) {
   let lFound = false;
 
-  for (let lFromModule of lFromModules) {
+  for (let lFromModule of pFromModules) {
     if (
       !lFound &&
       pModule.source !== lFromModule.source &&
@@ -164,6 +163,8 @@ function addReachableToModule(pModule, pGraph, pIndexedGraph, pReachableRule) {
 }
 
 function addReachabilityToGraph(pGraph, pIndexedGraph, pReachableRule) {
+  const lFromModules = pGraph.filter(isModuleInRuleFrom(pReachableRule));
+
   return pGraph.map((pModule) => {
     let lClonedModule = structuredClone(pModule);
 
@@ -178,9 +179,9 @@ function addReachabilityToGraph(pGraph, pIndexedGraph, pReachableRule) {
     if (shouldAddReachable(pReachableRule, lClonedModule, pGraph)) {
       lClonedModule = addReachableToModule(
         lClonedModule,
-        pGraph,
         pIndexedGraph,
         pReachableRule,
+        lFromModules,
       );
     }
     return lClonedModule;

Additionally the rule is slow because it searches the graph for a path repeatedly by calling getPath for each module. In theory it should be possible to just calculate all reachability from the entry points once to determine which modules are not reachable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementthis will make dependency-cruiser sweeter

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions