Deduplicate concurrent SchemaContext loads
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / SharedSchemaContextFactory.java
index ab146fcfc6d732196966f3697c36cee12aad0c3d..10a81fa01e32e5f8edaf388e0b66cefccbe26b94 100644 (file)
@@ -7,9 +7,11 @@
  */
 package org.opendaylight.yangtools.yang.parser.repo;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
+
 import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.collect.Collections2;
@@ -17,10 +19,12 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Maps;
 import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
 import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
@@ -28,121 +32,111 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
-import javax.annotation.Nullable;
+import java.util.concurrent.ExecutionException;
 import org.antlr.v4.runtime.ParserRuleContext;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
-import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
-import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
+import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
+import org.opendaylight.yangtools.yang.parser.impl.DefaultReactors;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
-import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-final class SharedSchemaContextFactory implements SchemaContextFactory {
-    private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
+final class SharedSchemaContextFactory implements EffectiveModelContextFactory {
     private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
 
-    private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
-        @Override
-        public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
-            return repository.getSchemaSource(input, ASTSchemaSource.class);
-        }
-    };
-    private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues().build();
-
-    private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
-        @Override
-        public ListenableFuture<SchemaContext> apply(final List<ASTSchemaSource> sources) throws SchemaResolutionException, SourceException, ReactorException {
-            final Map<SourceIdentifier, ASTSchemaSource> srcs =
-                    Maps.uniqueIndex(sources, ASTSchemaSource.GET_IDENTIFIER);
-            final Map<SourceIdentifier, YangModelDependencyInfo> deps =
-                    Maps.transformValues(srcs, ASTSchemaSource.GET_DEPINFO);
-
-            LOG.debug("Resolving dependency reactor {}", deps);
-
-            final DependencyResolver res = DependencyResolver.create(deps);
-            if (!res.getUnresolvedSources().isEmpty()) {
-                LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(), res.getUnsatisfiedImports());
-                throw new SchemaResolutionException("Failed to resolve required models",
-                        res.getResolvedSources(), res.getUnsatisfiedImports());
-            }
-
-            final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
-            final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
-
-            for (final Entry<SourceIdentifier, ParserRuleContext> e : asts.entrySet()) {
-                final ParserRuleContext parserRuleCtx = e.getValue();
-                Preconditions.checkArgument(parserRuleCtx instanceof StatementContext,
-                    "Unsupported context class %s for source %s", parserRuleCtx.getClass(), e.getKey());
-
-                reactor.addSource(new YangStatementSourceImpl(e.getKey(), (StatementContext) parserRuleCtx));
-            }
-
-            SchemaContext schemaContext = reactor.buildEffective();
-
-            return Futures.immediateCheckedFuture(schemaContext);
-        }
-    };
-
-    private final SharedSchemaRepository repository;
-    // FIXME: ignored right now
-    private final SchemaSourceFilter filter;
-
-    // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository (final implementation)
-    public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
-        this.repository = Preconditions.checkNotNull(repository);
-        this.filter = Preconditions.checkNotNull(filter);
+    private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> revisionCache = CacheBuilder.newBuilder()
+            .weakValues().build();
+    private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> semVerCache = CacheBuilder.newBuilder()
+            .weakValues().build();
+    private final @NonNull SchemaRepository repository;
+    private final @NonNull SchemaContextFactoryConfiguration config;
+
+    SharedSchemaContextFactory(final @NonNull SchemaRepository repository,
+        final @NonNull SchemaContextFactoryConfiguration config) {
+        this.repository = requireNonNull(repository);
+        this.config = requireNonNull(config);
     }
 
     @Override
-    public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
+    public @NonNull ListenableFuture<EffectiveModelContext> createEffectiveModelContext(
+            final @NonNull Collection<SourceIdentifier> requiredSources) {
+        return createSchemaContext(requiredSources,
+                config.getStatementParserMode() == StatementParserMode.SEMVER_MODE ? semVerCache : revisionCache,
+                new AssembleSources(config));
+    }
+
+    private @NonNull ListenableFuture<EffectiveModelContext> createSchemaContext(
+            final Collection<SourceIdentifier> requiredSources,
+            final Cache<Collection<SourceIdentifier>, EffectiveModelContext> cache,
+            final AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> assembleSources) {
         // Make sources unique
         final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
 
-        final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
+        final EffectiveModelContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
         if (existing != null) {
             LOG.debug("Returning cached context {}", existing);
-            return Futures.immediateCheckedFuture(existing);
+            return immediateFluentFuture(existing);
         }
 
         // Request all sources be loaded
-        ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources));
+        ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
+            this::requestSource));
 
         // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
         // Also remove duplicates if present
         // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
-        sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));
+        sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
+            MoreExecutors.directExecutor());
 
         // Assemble sources into a schema context
-        final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
+        final ListenableFuture<EffectiveModelContext> cf = Futures.transformAsync(sf, assembleSources,
+            MoreExecutors.directExecutor());
 
-        // Populate cache when successful
-        Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
+        final SettableFuture<EffectiveModelContext> rf = SettableFuture.create();
+        Futures.addCallback(cf, new FutureCallback<EffectiveModelContext>() {
             @Override
-            public void onSuccess(final SchemaContext result) {
-                cache.put(uniqueSourceIdentifiers, result);
+            public void onSuccess(final EffectiveModelContext result) {
+                // Deduplicate concurrent loads
+                final EffectiveModelContext existing;
+                try {
+                    existing = cache.get(uniqueSourceIdentifiers, () -> result);
+                } catch (ExecutionException e) {
+                    LOG.warn("Failed to recheck result with cache, will use computed value", e);
+                    rf.set(result);
+                    return;
+                }
+
+                rf.set(existing);
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.debug("Failed to assemble sources", t);
+            public void onFailure(final Throwable cause) {
+                LOG.debug("Failed to assemble sources", cause);
+                rf.setException(cause);
             }
-        });
+        }, MoreExecutors.directExecutor());
 
-        return Futures.makeChecked(cf, MAPPER);
+        return rf;
+    }
+
+    private ListenableFuture<ASTSchemaSource> requestSource(final @NonNull SourceIdentifier identifier) {
+        return repository.getSchemaSource(identifier, ASTSchemaSource.class);
     }
 
     /**
+     * Return a set of de-duplicated inputs.
+     *
      * @return set (preserving ordering) from the input collection
      */
     private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
@@ -153,20 +147,16 @@ final class SharedSchemaContextFactory implements SchemaContextFactory {
         }
 
         LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
-            Collections2.filter(uniqueSourceIdentifiers, new Predicate<SourceIdentifier>() {
-                @Override
-                public boolean apply(@Nullable final SourceIdentifier input) {
-                    return Iterables.frequency(requiredSources, input) > 1;
-                }
-            }));
+            Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
         return ImmutableList.copyOf(uniqueSourceIdentifiers);
     }
 
-    private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>, List<ASTSchemaSource>> {
+    private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
+            List<ASTSchemaSource>> {
         private final List<SourceIdentifier> sourceIdentifiers;
 
-        public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
-            this.sourceIdentifiers = Preconditions.checkNotNull(sourceIdentifiers);
+        SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
+            this.sourceIdentifiers = requireNonNull(sourceIdentifiers);
         }
 
         @Override
@@ -180,8 +170,8 @@ final class SharedSchemaContextFactory implements SchemaContextFactory {
                 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
 
                 if (!expectedSId.equals(realSId)) {
-                    LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. Using actual id",
-                        expectedSId.getName(), expectedSId, realSId);
+                    LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. "
+                        + "Using actual id", expectedSId.getName(), expectedSId, realSId);
                 }
 
                 if (filtered.containsKey(realSId)) {
@@ -194,4 +184,63 @@ final class SharedSchemaContextFactory implements SchemaContextFactory {
             return ImmutableList.copyOf(filtered.values());
         }
     }
+
+    private static final class AssembleSources implements AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> {
+        private final @NonNull SchemaContextFactoryConfiguration config;
+        private final @NonNull Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
+
+        private AssembleSources(final @NonNull SchemaContextFactoryConfiguration config) {
+            this.config = config;
+            switch (config.getStatementParserMode()) {
+                case SEMVER_MODE:
+                    this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
+                    break;
+                default:
+                    this.getIdentifier = ASTSchemaSource::getIdentifier;
+            }
+        }
+
+        @Override
+        public FluentFuture<EffectiveModelContext> apply(final List<ASTSchemaSource> sources)
+                throws SchemaResolutionException, ReactorException {
+            final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
+            final Map<SourceIdentifier, YangModelDependencyInfo> deps =
+                    Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
+
+            LOG.debug("Resolving dependency reactor {}", deps);
+
+            final StatementParserMode statementParserMode = config.getStatementParserMode();
+            final DependencyResolver res = statementParserMode == StatementParserMode.SEMVER_MODE
+                    ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
+            if (!res.getUnresolvedSources().isEmpty()) {
+                LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
+                    res.getUnsatisfiedImports());
+                throw new SchemaResolutionException("Failed to resolve required models",
+                        res.getResolvedSources(), res.getUnsatisfiedImports());
+            }
+
+            final BuildAction reactor = DefaultReactors.defaultReactor().newBuild(statementParserMode);
+            config.getSupportedFeatures().ifPresent(reactor::setSupportedFeatures);
+            config.getModulesDeviatedByModules().ifPresent(reactor::setModulesWithSupportedDeviations);
+
+            for (final Entry<SourceIdentifier, ASTSchemaSource> e : srcs.entrySet()) {
+                final ASTSchemaSource ast = e.getValue();
+                final ParserRuleContext parserRuleCtx = ast.getAST();
+                checkArgument(parserRuleCtx instanceof StatementContext, "Unsupported context class %s for source %s",
+                    parserRuleCtx.getClass(), e.getKey());
+
+                reactor.addSource(YangStatementStreamSource.create(e.getKey(), (StatementContext) parserRuleCtx,
+                    ast.getSymbolicName().orElse(null)));
+            }
+
+            final EffectiveModelContext schemaContext;
+            try {
+                schemaContext = reactor.buildEffective();
+            } catch (final ReactorException ex) {
+                throw new SchemaResolutionException("Failed to resolve required models", ex.getSourceIdentifier(), ex);
+            }
+
+            return immediateFluentFuture(schemaContext);
+        }
+    }
 }