You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maven.apache.org by gn...@apache.org on 2022/08/23 09:52:02 UTC

[maven] branch master updated: [MNG-7401] [MNG-7474] Keep a single maven session and fix session scope (#743)

This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new e02e0c84c [MNG-7401] [MNG-7474] Keep a single maven session and fix session scope (#743)
e02e0c84c is described below

commit e02e0c84ce2582ac363d40e115fceea4146e999c
Author: Guillaume Nodet <gn...@gmail.com>
AuthorDate: Tue Aug 23 11:19:11 2022 +0200

    [MNG-7401] [MNG-7474] Keep a single maven session and fix session scope (#743)
    
    * [MNG-7474] SessionScoped beans should be singletons for a given session
    
    Now that the Session is not cloned anymore, we can revert to the original
    (Maven < 3.3) behavior of the session scoped components.
    
    Co-authored-by: Christoph Läubrich <ch...@laeubi-soft.de>
    
    This closes #743
    
    * Remove setting a value which is the default already
    
    Co-authored-by: Christoph Läubrich <ch...@laeubi-soft.de>
    # Conflicts:
    #       maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java
    #       maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java
---
 .../org/apache/maven/execution/MavenSession.java   |  20 +--
 .../lifecycle/internal/BuildListCalculator.java    |   7 +-
 .../lifecycle/internal/LifecycleModuleBuilder.java |   6 -
 .../maven/lifecycle/internal/LifecycleStarter.java |   4 +-
 .../maven/lifecycle/internal/ReactorContext.java   |  14 +--
 .../maven/session/scope/internal/SessionScope.java | 139 +++++++++------------
 .../internal/BuildListCalculatorTest.java          |   6 +
 .../internal/LifecycleModuleBuilderTest.java       |  97 ++++++++++++++
 .../lifecycle/internal/stub/MojoExecutorStub.java  |   5 +
 9 files changed, 189 insertions(+), 109 deletions(-)

diff --git a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
index 5af173410..4551ccffa 100644
--- a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
+++ b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
@@ -55,7 +55,7 @@ public class MavenSession
 
     private Properties executionProperties;
 
-    private MavenProject currentProject;
+    private ThreadLocal<MavenProject> currentProject = new ThreadLocal<>();
 
     /**
      * These projects have already been topologically sorted in the {@link org.apache.maven.Maven} component before
@@ -90,14 +90,15 @@ public class MavenSession
     {
         if ( !projects.isEmpty() )
         {
-            this.currentProject = projects.get( 0 );
+            MavenProject first = projects.get( 0 );
+            this.currentProject = ThreadLocal.withInitial( () -> first );
             this.topLevelProject =
                     projects.stream().filter( project -> project.isExecutionRoot() ).findFirst()
-                            .orElse( currentProject );
+                            .orElse( first );
         }
         else
         {
-            this.currentProject = null;
+            this.currentProject = new ThreadLocal<>();
             this.topLevelProject = null;
         }
         this.projects = projects;
@@ -158,12 +159,12 @@ public class MavenSession
 
     public void setCurrentProject( MavenProject currentProject )
     {
-        this.currentProject = currentProject;
+        this.currentProject.set( currentProject );
     }
 
     public MavenProject getCurrentProject()
     {
-        return currentProject;
+        return currentProject.get();
     }
 
     public ProjectBuildingRequest getProjectBuildingRequest()
@@ -234,7 +235,12 @@ public class MavenSession
     {
         try
         {
-            return (MavenSession) super.clone();
+            MavenSession clone = (MavenSession) super.clone();
+            // the default must become the current project of the thread that clones this
+            MavenProject current = getCurrentProject();
+            // we replace the thread local of the clone to prevent write through and enforce the new default value
+            clone.currentProject = ThreadLocal.withInitial( () -> current );
+            return clone;
         }
         catch ( CloneNotSupportedException e )
         {
diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java
index c35ac4134..b30b560c8 100644
--- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java
+++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/BuildListCalculator.java
@@ -61,15 +61,16 @@ public class BuildListCalculator
             for ( MavenProject project : projects )
             {
                 ClassLoader tccl = Thread.currentThread().getContextClassLoader();
+                MavenProject currentProject = session.getCurrentProject();
                 try
                 {
                     BuilderCommon.attachToThread( project ); // Not totally sure if this is needed for anything
-                    MavenSession copiedSession = session.clone();
-                    copiedSession.setCurrentProject( project );
-                    projectBuilds.add( new ProjectSegment( project, taskSegment, copiedSession ) );
+                    session.setCurrentProject( project );
+                    projectBuilds.add( new ProjectSegment( project, taskSegment, session ) );
                 }
                 finally
                 {
+                    session.setCurrentProject( currentProject );
                     Thread.currentThread().setContextClassLoader( tccl );
                 }
             }
diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java
index a2f90bee1..17340fbe7 100644
--- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java
+++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilder.java
@@ -87,10 +87,6 @@ public class LifecycleModuleBuilder
 
         long buildStartTime = System.currentTimeMillis();
 
-        // session may be different from rootSession seeded in DefaultMaven
-        // explicitly seed the right session here to make sure it is used by Guice
-        sessionScope.enter( reactorContext.getSessionScopeMemento() );
-        sessionScope.seed( MavenSession.class, session );
         try
         {
 
@@ -144,8 +140,6 @@ public class LifecycleModuleBuilder
         }
         finally
         {
-            sessionScope.exit();
-
             session.setCurrentProject( null );
 
             Thread.currentThread().setContextClassLoader( reactorContext.getOriginalContextClassLoader() );
diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
index a96c29a61..9f2eb5e1a 100644
--- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
+++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
@@ -121,9 +121,7 @@ public class LifecycleStarter
 
             ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
             ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus( session.getProjectDependencyGraph() );
-            reactorContext =
-                new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus,
-                                    sessionScope.memento() );
+            reactorContext = new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus );
 
             String builderId = session.getRequest().getBuilderId();
             Builder builder = builders.get( builderId );
diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java
index 7df531404..076c6229f 100644
--- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java
+++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java
@@ -20,7 +20,6 @@ package org.apache.maven.lifecycle.internal;
  */
 
 import org.apache.maven.execution.MavenExecutionResult;
-import org.apache.maven.session.scope.internal.SessionScope;
 
 /**
  * Context that is fixed for the entire reactor build.
@@ -40,17 +39,13 @@ public class ReactorContext
 
     private final ReactorBuildStatus reactorBuildStatus;
 
-    private final SessionScope.Memento sessionScope;
-
     public ReactorContext( MavenExecutionResult result, ProjectIndex projectIndex,
-                           ClassLoader originalContextClassLoader, ReactorBuildStatus reactorBuildStatus,
-                           SessionScope.Memento sessionScope )
+                           ClassLoader originalContextClassLoader, ReactorBuildStatus reactorBuildStatus )
     {
         this.result = result;
         this.projectIndex = projectIndex;
         this.originalContextClassLoader = originalContextClassLoader;
         this.reactorBuildStatus = reactorBuildStatus;
-        this.sessionScope = sessionScope;
     }
 
     public ReactorBuildStatus getReactorBuildStatus()
@@ -73,11 +68,4 @@ public class ReactorContext
         return originalContextClassLoader;
     }
 
-    /**
-     * @since 3.3.0
-     */
-    public SessionScope.Memento getSessionScopeMemento()
-    {
-        return sessionScope;
-    }
 }
diff --git a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java
index de97d4479..7bbf47798 100644
--- a/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java
+++ b/maven-core/src/main/java/org/apache/maven/session/scope/internal/SessionScope.java
@@ -19,16 +19,16 @@ package org.apache.maven.session.scope.internal;
  * under the License.
  */
 
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedList;
+import java.util.Collection;
+import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
 
 import com.google.inject.Key;
 import com.google.inject.OutOfScopeException;
 import com.google.inject.Provider;
 import com.google.inject.Scope;
-import com.google.inject.util.Providers;
 
 /**
  * SessionScope
@@ -36,18 +36,6 @@ import com.google.inject.util.Providers;
 public class SessionScope
     implements Scope
 {
-    /**
-     * @since 3.3.0
-     */
-    public static class Memento
-    {
-        final Map<Key<?>, Provider<?>> seeded;
-
-        Memento( final Map<Key<?>, Provider<?>> seeded )
-        {
-            this.seeded = Collections.unmodifiableMap( new HashMap<>( seeded ) );
-        }
-    }
 
     private static final Provider<Object> SEEDED_KEY_PROVIDER = () ->
     {
@@ -57,106 +45,103 @@ public class SessionScope
     /**
      * ScopeState
      */
-    private static final class ScopeState
+    protected static final class ScopeState
     {
-        private final Map<Key<?>, Provider<?>> seeded = new HashMap<>();
+        private final Map<Key<?>, CachingProvider<?>> provided = new ConcurrentHashMap<>();
 
-        private final Map<Key<?>, Object> provided = new HashMap<>();
-    }
+        public <T> void seed( Class<T> clazz, Provider<T> value )
+        {
+            provided.put( Key.get( clazz ), new CachingProvider<>( value ) );
+        }
 
-    private final ThreadLocal<LinkedList<ScopeState>> values = new ThreadLocal<>();
+        @SuppressWarnings( "unchecked" )
+        public <T> Provider<T> scope( Key<T> key, Provider<T> unscoped )
+        {
+            Provider<?> provider = provided.computeIfAbsent( key, k -> new CachingProvider<>( unscoped ) );
+            return ( Provider<T> ) provider;
+        }
 
-    public void enter()
-    {
-        LinkedList<ScopeState> stack = values.get();
-        if ( stack == null )
+        public Collection<CachingProvider<?>> providers()
         {
-            stack = new LinkedList<>();
-            values.set( stack );
+            return provided.values();
         }
-        stack.addFirst( new ScopeState() );
     }
 
-    /**
-     * @since 3.3.0
-     */
-    public void enter( Memento memento )
+    private final List<ScopeState> values = new CopyOnWriteArrayList<>();
+
+    public void enter()
     {
-        enter();
-        getScopeState().seeded.putAll( memento.seeded );
+        values.add( 0, new ScopeState() );
     }
 
-    private ScopeState getScopeState()
+    protected ScopeState getScopeState()
     {
-        LinkedList<ScopeState> stack = values.get();
-        if ( stack == null || stack.isEmpty() )
+        if ( values.isEmpty() )
         {
-            throw new IllegalStateException();
+            throw new OutOfScopeException( "Cannot access session scope outside of a scoping block" );
         }
-        return stack.getFirst();
+        return values.get( 0 );
     }
 
     public void exit()
     {
-        final LinkedList<ScopeState> stack = values.get();
-        if ( stack == null || stack.isEmpty() )
+        if ( values.isEmpty() )
         {
             throw new IllegalStateException();
         }
-        stack.removeFirst();
-        if ( stack.isEmpty() )
-        {
-            values.remove();
-        }
-    }
-
-    /**
-     * @since 3.3.0
-     */
-    public Memento memento()
-    {
-        LinkedList<ScopeState> stack = values.get();
-        return new Memento( stack != null ? stack.getFirst().seeded : Collections.emptyMap() );
+        values.remove( 0 );
     }
 
     public <T> void seed( Class<T> clazz, Provider<T> value )
     {
-        getScopeState().seeded.put( Key.get( clazz ), value );
+        getScopeState().seed( clazz, value );
     }
 
     public <T> void seed( Class<T> clazz, final T value )
     {
-        getScopeState().seeded.put( Key.get( clazz ), Providers.of( value ) );
+        seed( clazz, ( Provider<T> ) () -> value );
     }
 
     public <T> Provider<T> scope( final Key<T> key, final Provider<T> unscoped )
     {
-        return () ->
-        {
-            LinkedList<ScopeState> stack = values.get();
-            if ( stack == null || stack.isEmpty() )
-            {
-                throw new OutOfScopeException( "Cannot access " + key + " outside of a scoping block" );
-            }
+        // Lazy evaluating provider
+        return () -> getScopeState().scope( key, unscoped ).get();
+    }
 
-            ScopeState state = stack.getFirst();
+    /**
+     * A provider wrapping an existing provider with a cache
+     * @param <T> the provided type
+     */
+    protected static class CachingProvider<T> implements Provider<T>
+    {
+        private final Provider<T> provider;
+        private volatile T value;
 
-            Provider<?> seeded = state.seeded.get( key );
+        CachingProvider( Provider<T> provider )
+        {
+            this.provider = provider;
+        }
 
-            if ( seeded != null )
-            {
-                return (T) seeded.get();
-            }
+        public T value()
+        {
+            return value;
+        }
 
-            T provided = (T) state.provided.get( key );
-            if ( provided == null && unscoped != null )
+        @Override
+        public T get()
+        {
+            if ( value == null )
             {
-                provided = unscoped.get();
-                state.provided.put( key, provided );
+                synchronized ( this )
+                {
+                    if ( value == null )
+                    {
+                        value = provider.get();
+                    }
+                }
             }
-
-            return provided;
-        };
+            return value;
+        }
     }
 
     @SuppressWarnings( { "unchecked" } )
diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java
index 6a73160c1..4f0b0591e 100644
--- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java
+++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/BuildListCalculatorTest.java
@@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
 
 public class BuildListCalculatorTest
 {
@@ -42,6 +43,11 @@ public class BuildListCalculatorTest
         assertEquals( 6, segments.size(), "Stub data contains 6 items" );
         final ProjectSegment build = segments.get( 0 );
         assertNotNull( build );
+
+        for ( ProjectSegment segment : segments )
+        {
+            assertSame( session, segment.getSession() );
+        }
     }
 
     private static LifecycleTaskSegmentCalculator getTaskSegmentCalculator()
diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java
new file mode 100644
index 000000000..7b3bd4059
--- /dev/null
+++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/LifecycleModuleBuilderTest.java
@@ -0,0 +1,97 @@
+package org.apache.maven.lifecycle.internal;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+import javax.inject.Inject;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.maven.execution.AbstractExecutionListener;
+import org.apache.maven.execution.DefaultMavenExecutionRequest;
+import org.apache.maven.execution.DefaultMavenExecutionResult;
+import org.apache.maven.execution.MavenExecutionRequest;
+import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.LifecycleExecutionException;
+import org.apache.maven.lifecycle.internal.stub.MojoExecutorStub;
+import org.apache.maven.lifecycle.internal.stub.ProjectDependencyGraphStub;
+import org.apache.maven.plugin.MojoExecution;
+import org.apache.maven.project.MavenProject;
+import org.codehaus.plexus.PlexusContainer;
+import org.codehaus.plexus.testing.PlexusTest;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+@PlexusTest
+public class LifecycleModuleBuilderTest
+{
+    @Inject
+    PlexusContainer container;
+//    @Override
+//    protected void customizeContainerConfiguration( ContainerConfiguration configuration )
+//    {
+//        configuration.setAutoWiring( true );
+//        configuration.setClassPathScanning( PlexusConstants.SCANNING_INDEX );
+//
+//    }
+
+    @Test
+    public void testCurrentProject() throws Exception
+    {
+        List<MavenProject> currentProjects = new ArrayList<>();
+        MojoExecutorStub mojoExecutor = new MojoExecutorStub()
+        {
+            @Override
+            public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
+                    throws LifecycleExecutionException
+            {
+                super.execute( session, mojoExecutions, projectIndex );
+                currentProjects.add( session.getCurrentProject() );
+            }
+        };
+
+        final DefaultMavenExecutionResult defaultMavenExecutionResult = new DefaultMavenExecutionResult();
+        MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
+        mavenExecutionRequest.setExecutionListener( new AbstractExecutionListener() );
+        mavenExecutionRequest.setGoals( Arrays.asList( "clean" ) );
+        final MavenSession session = new MavenSession( null, null, mavenExecutionRequest, defaultMavenExecutionResult );
+        final ProjectDependencyGraphStub dependencyGraphStub = new ProjectDependencyGraphStub();
+        session.setProjectDependencyGraph( dependencyGraphStub );
+        session.setProjects( dependencyGraphStub.getSortedProjects() );
+
+        LifecycleModuleBuilder moduleBuilder = container.lookup( LifecycleModuleBuilder.class );
+        set( moduleBuilder, "mojoExecutor", mojoExecutor );
+
+        LifecycleStarter ls = container.lookup( LifecycleStarter.class );
+        ls.execute( session );
+
+        assertNull( session.getCurrentProject() );
+        assertEquals( Arrays.asList( ProjectDependencyGraphStub.A, ProjectDependencyGraphStub.B, ProjectDependencyGraphStub.C,
+                ProjectDependencyGraphStub.X, ProjectDependencyGraphStub.Y, ProjectDependencyGraphStub.Z ), currentProjects );
+    }
+
+    static void set( Object obj, String field, Object v ) throws NoSuchFieldException, IllegalAccessException
+    {
+        Field f = obj.getClass().getDeclaredField( field );
+        f.setAccessible( true );
+        f.set( obj, v );
+    }
+
+}
diff --git a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java
index a47b6076a..e71664592 100644
--- a/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java
+++ b/maven-core/src/test/java/org/apache/maven/lifecycle/internal/stub/MojoExecutorStub.java
@@ -46,6 +46,11 @@ public class MojoExecutorStub
 
     public final List<MojoExecution> executions = Collections.synchronizedList(new ArrayList<>() );
 
+    public MojoExecutorStub()
+    {
+        super( null, null, null, null, null );
+    }
+
     public MojoExecutorStub(
             BuildPluginManager pluginManager,
             MavenPluginManager mavenPluginManager,