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

henrykuijpers pushed a commit to branch master
in repository 
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-testing-sling-mock-oak.git


The following commit(s) were added to refs/heads/master by this push:
     new 185e009  SLING-13405 Add optional Lucene index support for JCR_OAK
185e009 is described below

commit 185e0094d3589fda6bdee99ae355e744a34a77f4
Author: henrykuijpers <[email protected]>
AuthorDate: Tue Nov 24 13:15:41 2026 +0100

    SLING-13405 Add optional Lucene index support for JCR_OAK
    
    Lucene index support is enabled automatically if a compatible oak-lucene
    artifact is in the test class path. oak-lucene is an optional dependency
    and is not embedded in the shaded artifact.
    
    - Lucene query index provider and index editor provider are registered for
      all JCR_OAK contexts if oak-lucene is in the class path, has at least the
      shaded Oak version and is not provided by another artifact (e.g. the AEM
      API JARs). The class path check is done only once.
    - Async Lucene indexes are updated synchronously within each commit, as no
      background async indexing is running in the mock repository. This covers
      all async lanes (e.g. "async", "fulltext-async") and hybrid indexes like
      async=["async", "nrt"]. Only Lucene index definitions select an async
      lane, so Oak's default /oak:index/counter does not cause an additional
      index update per commit.
    - Lucene index definitions are supported below /oak:index and in oak:index
      nodes at non-root paths.
    - If Lucene index support is not enabled, a warning naming the reason is
      logged once per Lucene index definition found. A too old oak-lucene
      version is always reported.
    - No performance impact without oak-lucene in the class path.
    - README documents how to enable it.
---
 README.md                                          |  19 ++
 bnd.bnd                                            |   2 +
 pom.xml                                            |  45 +++++
 .../mock/sling/oak/OakMockSlingRepository.java     |  16 +-
 .../oak/lucene/impl/LuceneIndexMissingWarning.java | 141 +++++++++++++++
 .../sling/oak/lucene/impl/LuceneIndexSupport.java  | 170 ++++++++++++++++++
 .../oak/lucene/impl/SynchronousAsyncIndexHook.java | 144 +++++++++++++++
 .../oak/lucene/LuceneIndexNotAvailableTest.java    | 111 ++++++++++++
 .../mock/sling/oak/lucene/LuceneIndexTest.java     | 199 +++++++++++++++++++++
 .../sling/oak/lucene/NestedLuceneIndexTest.java    | 172 ++++++++++++++++++
 .../mock/sling/oak/lucene/StdErrCapture.java       |  61 +++++++
 .../lucene/impl/LuceneIndexMissingWarningTest.java | 128 +++++++++++++
 .../oak/lucene/impl/LuceneIndexSupportTest.java    |  81 +++++++++
 .../lucene/impl/SynchronousAsyncIndexHookTest.java |  87 +++++++++
 14 files changed, 1375 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 1d0ca56..e3d082c 100644
--- a/README.md
+++ b/README.md
@@ -16,5 +16,24 @@ In order to execute tests with a version **newer than the 
Oak version** shaded i
 
 Downgrading to an **older Oak version** is not supported and will lead to an 
exception (if some earlier artifacts in the class path provide an old Oak 
implementation).
 
+## Lucene index support (optional)
+
+By default only property indexes are available, so full-text queries 
(`jcr:contains`) return no results, and queries relying on Lucene index 
definitions are not served by an index. Lucene index support is enabled 
automatically if `oak-lucene` is in the test class path. Use the same Oak 
version that is shaded into this artifact (the second part of its version, e.g. 
`1.86.0` for `4.1.0-1.86.0`):
+
+```xml
+<dependency>
+    <groupId>org.apache.jackrabbit</groupId>
+    <artifactId>oak-lucene</artifactId>
+    <version>1.86.0</version>
+    <scope>test</scope>
+</dependency>
+```
+
+This applies to all `JCR_OAK` contexts in the module. Note that this also 
applies if `oak-lucene` is already in the test class path as a transitive 
dependency.
+
+Lucene index support stays disabled if `oak-lucene` is missing or older than 
the shaded Oak version. A warning is logged if a Lucene index definition is 
found while Lucene index support is not enabled, naming the reason. Some 
artifacts also contain (parts of) the Oak Lucene classes, e.g. the AEM API JARs 
(`uber-jar`, `aem-sdk-api`). These are not sufficient, so make sure to place 
the `oak-lucene` dependency before such artifacts in the test class path.
+
+Lucene index definitions are created as usual below `/oak:index`, or in an 
`oak:index` node at a non-root path to index only the content below that path 
(e.g. in the test setup or via the content loader). Index definitions from a 
real instance can be used unchanged. No background async indexing is running in 
the mock repository: **async indexes are updated synchronously** within each 
commit instead. This applies to all async lanes referenced by index definitions 
(e.g. `async=["async"]`,  [...]
+
 Documentation:
 <https://sling.apache.org/documentation/development/sling-mock.html>
diff --git a/bnd.bnd b/bnd.bnd
new file mode 100644
index 0000000..60ee0d0
--- /dev/null
+++ b/bnd.bnd
@@ -0,0 +1,2 @@
+Import-Package: 
org.apache.jackrabbit.oak.plugins.index.lucene;resolution:=optional,\
+  *
diff --git a/pom.xml b/pom.xml
index 8c0fa33..f076f3a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -125,6 +125,15 @@
             <scope>compile</scope>
         </dependency>
 
+        <!-- Optional Lucene index support: users have to add oak-lucene to 
their own test class path to enable it -->
+        <dependency>
+            <groupId>org.apache.jackrabbit</groupId>
+            <artifactId>oak-lucene</artifactId>
+            <version>${oak.version}</version>
+            <scope>compile</scope>
+            <optional>true</optional>
+        </dependency>
+
         <!-- those two compile dependencies are requires to avoid 
"Dependency-reduced POM written" endless loop in maven-shade-plugin -->
         <dependency>
             <groupId>javax.jcr</groupId>
@@ -187,6 +196,36 @@
                 <artifactId>bnd-baseline-maven-plugin</artifactId>
             </plugin>
 
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>default-test</id>
+                        <configuration>
+                            <excludes>
+                                
<exclude>**/LuceneIndexNotAvailableTest.java</exclude>
+                            </excludes>
+                        </configuration>
+                    </execution>
+                    <!-- verify behavior without the optional oak-lucene 
dependency -->
+                    <execution>
+                        <id>test-without-oak-lucene</id>
+                        <goals>
+                            <goal>test</goal>
+                        </goals>
+                        <configuration>
+                            <includes>
+                                
<include>**/LuceneIndexNotAvailableTest.java</include>
+                            </includes>
+                            <classpathDependencyExcludes>
+                                
<classpathDependencyExclude>org.apache.jackrabbit:oak-lucene</classpathDependencyExclude>
+                            </classpathDependencyExcludes>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-shade-plugin</artifactId>
@@ -202,6 +241,12 @@
                         <includes>
                             <include>org.apache.jackrabbit:*</include>
                         </includes>
+                        <!-- optional Lucene index support is not embedded, 
see README -->
+                        <excludes>
+                            <exclude>org.apache.jackrabbit:oak-lucene</exclude>
+                            <exclude>org.apache.jackrabbit:oak-search</exclude>
+                            
<exclude>org.apache.jackrabbit:oak-store-document</exclude>
+                        </excludes>
                     </artifactSet>
                     <createSourcesJar>true</createSourcesJar>
                 </configuration>
diff --git 
a/src/main/java/org/apache/sling/testing/mock/sling/oak/OakMockSlingRepository.java
 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/OakMockSlingRepository.java
index c0ba571..840ef0b 100644
--- 
a/src/main/java/org/apache/sling/testing/mock/sling/oak/OakMockSlingRepository.java
+++ 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/OakMockSlingRepository.java
@@ -46,6 +46,8 @@ import org.apache.jackrabbit.oak.spi.state.NodeState;
 import org.apache.jackrabbit.oak.spi.state.NodeStore;
 import org.apache.sling.jcr.api.SlingRepository;
 import org.apache.sling.testing.mock.sling.oak.impl.ComparableVersion;
+import 
org.apache.sling.testing.mock.sling.oak.lucene.impl.LuceneIndexMissingWarning;
+import org.apache.sling.testing.mock.sling.oak.lucene.impl.LuceneIndexSupport;
 import org.osgi.framework.BundleContext;
 import org.osgi.service.component.ComponentContext;
 import org.osgi.service.component.annotations.Activate;
@@ -63,6 +65,7 @@ public final class OakMockSlingRepository implements 
SlingRepository {
     private Repository repository;
     private ExecutorService executor;
     private ScheduledExecutorService scheduledExecutor;
+    private Runnable luceneIndexProviderCloser;
 
     private final NodeStore nodeStore;
     private final boolean fromScratch;
@@ -94,11 +97,18 @@ public final class OakMockSlingRepository implements 
SlingRepository {
         if (fromScratch) {
             jcr.with(new ExtraSlingContent());
         }
+        // optional Lucene index support, enabled if a compatible oak-lucene 
artifact is in the class path
+        String expectedVersion = getExpectedVersion();
+        String luceneUnavailableReason = 
LuceneIndexSupport.getUnavailableReason(expectedVersion);
+        if (luceneUnavailableReason == null) {
+            luceneIndexProviderCloser = LuceneIndexSupport.register(jcr);
+        } else {
+            jcr.with(new LuceneIndexMissingWarning(luceneUnavailableReason));
+        }
 
         this.repository = jcr.createRepository();
         // check if the right Oak version is loaded (older versions may be 
loaded in case of non-deliberate class loader
         // collisions)
-        String expectedVersion = getExpectedVersion();
         String actualVersion = repository.getDescriptor(REP_VERSION_DESC);
         if (new ComparableVersion(expectedVersion).compareTo(new 
ComparableVersion(actualVersion)) > 0) {
             throw new IllegalStateException(
@@ -126,6 +136,10 @@ public final class OakMockSlingRepository implements 
SlingRepository {
 
         // shutdown OAK JCR repository
         ((JackrabbitRepository) repository).shutdown();
+
+        if (luceneIndexProviderCloser != null) {
+            luceneIndexProviderCloser.run();
+        }
     }
 
     private void shutdownExecutorService(Object instance, String fieldName) {
diff --git 
a/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarning.java
 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarning.java
new file mode 100644
index 0000000..3bf54ba
--- /dev/null
+++ 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarning.java
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.jackrabbit.oak.commons.PathUtils;
+import org.apache.jackrabbit.oak.plugins.index.IndexConstants;
+import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
+import org.apache.jackrabbit.oak.spi.commit.DefaultEditor;
+import org.apache.jackrabbit.oak.spi.commit.Editor;
+import org.apache.jackrabbit.oak.spi.commit.EditorProvider;
+import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
+import org.apache.jackrabbit.oak.spi.state.NodeState;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Logs a warning if a Lucene index definition is added to or changed in an 
oak:index node (at any path) while
+ * Lucene index support is not enabled - queries would not use this index, and 
full-text queries would return no results.
+ * The warning is logged only once per index path.
+ * <p>
+ * Uses only Oak core classes, so it can be used without oak-lucene in the 
class path.
+ * </p>
+ */
+public final class LuceneIndexMissingWarning implements EditorProvider {
+
+    private static final String TYPE_LUCENE = "lucene";
+
+    // log only once per index path, many tests typically load the same index 
definitions
+    private static final Set<String> WARNED_INDEX_PATHS = 
ConcurrentHashMap.newKeySet();
+
+    private static final Logger log = 
LoggerFactory.getLogger(LuceneIndexMissingWarning.class);
+
+    private final String unavailableReason;
+
+    /**
+     * @param unavailableReason Reason why Lucene index support is not 
available, including a hint how to enable it
+     */
+    public LuceneIndexMissingWarning(@NotNull String unavailableReason) {
+        this.unavailableReason = unavailableReason;
+    }
+
+    @Override
+    public @Nullable Editor getRootEditor(
+            @NotNull NodeState before,
+            @NotNull NodeState after,
+            @NotNull NodeBuilder builder,
+            @NotNull CommitInfo info) {
+        return new ContentEditor(PathUtils.ROOT_PATH);
+    }
+
+    /**
+     * Visits all changed content nodes to find index definitions in 
<code>oak:index</code> nodes at any path.
+     */
+    private final class ContentEditor extends DefaultEditor {
+
+        private final String path;
+
+        ContentEditor(@NotNull String path) {
+            this.path = path;
+        }
+
+        @Override
+        public @Nullable Editor childNodeAdded(@NotNull String name, @NotNull 
NodeState after) {
+            return getChildEditor(name);
+        }
+
+        @Override
+        public @Nullable Editor childNodeChanged(
+                @NotNull String name, @NotNull NodeState before, @NotNull 
NodeState after) {
+            return getChildEditor(name);
+        }
+
+        private @Nullable Editor getChildEditor(@NotNull String name) {
+            if (IndexConstants.INDEX_DEFINITIONS_NAME.equals(name)) {
+                return new IndexDefinitionsEditor(PathUtils.concat(path, 
name));
+            }
+            if (name.startsWith(":")) {
+                // hidden nodes (e.g. index data) do not contain index 
definitions
+                return null;
+            }
+            return new ContentEditor(PathUtils.concat(path, name));
+        }
+    }
+
+    /**
+     * Checks the index definitions in an <code>oak:index</code> node.
+     */
+    private final class IndexDefinitionsEditor extends DefaultEditor {
+
+        private final String path;
+
+        IndexDefinitionsEditor(@NotNull String path) {
+            this.path = path;
+        }
+
+        @Override
+        public @Nullable Editor childNodeAdded(@NotNull String name, @NotNull 
NodeState after) {
+            checkIndexDefinition(PathUtils.concat(path, name), after);
+            return null;
+        }
+
+        @Override
+        public @Nullable Editor childNodeChanged(
+                @NotNull String name, @NotNull NodeState before, @NotNull 
NodeState after) {
+            checkIndexDefinition(PathUtils.concat(path, name), after);
+            return null;
+        }
+
+        private void checkIndexDefinition(@NotNull String indexPath, @NotNull 
NodeState definition) {
+            if 
(TYPE_LUCENE.equals(definition.getString(IndexConstants.TYPE_PROPERTY_NAME))
+                    && WARNED_INDEX_PATHS.add(indexPath)) {
+                log.warn(
+                        "Lucene index definition {} found, but Lucene index 
support is not enabled: queries will not "
+                                + "use this index, and full-text queries 
return no results. {}",
+                        indexPath,
+                        unavailableReason);
+            }
+        }
+    }
+}
diff --git 
a/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupport.java
 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupport.java
new file mode 100644
index 0000000..3315f4a
--- /dev/null
+++ 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupport.java
@@ -0,0 +1,170 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.jackrabbit.oak.Oak;
+import org.apache.jackrabbit.oak.jcr.Jcr;
+import org.apache.jackrabbit.oak.plugins.index.CompositeIndexEditorProvider;
+import org.apache.jackrabbit.oak.plugins.index.IndexConstants;
+import org.apache.jackrabbit.oak.plugins.index.IndexEditorProvider;
+import org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants;
+import 
org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexEditorProvider;
+import org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProvider;
+import org.apache.jackrabbit.oak.spi.commit.DefaultEditor;
+import org.apache.jackrabbit.oak.spi.commit.Observer;
+import org.apache.jackrabbit.oak.spi.query.QueryIndexProvider;
+import org.apache.sling.testing.mock.sling.oak.impl.ComparableVersion;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Registers Oak Lucene index support. Enabled automatically if a compatible 
oak-lucene artifact is present in the
+ * class path (optional dependency).
+ * <p>
+ * Lucene classes are only referenced from this class, so callers must check 
{@link #getUnavailableReason(String)}
+ * before calling {@link #register(Jcr)} to avoid a {@link 
NoClassDefFoundError}.
+ * </p>
+ * <p>
+ * No async indexing is running in the mock repository: index definitions with 
<code>async</code> property are
+ * updated synchronously within each commit instead, see {@link 
SynchronousAsyncIndexHook}.
+ * </p>
+ */
+public final class LuceneIndexSupport {
+
+    private static final String LUCENE_INDEX_PROVIDER_CLASS =
+            
"org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProvider";
+    private static final String OAK_LUCENE_IMPLEMENTATION_TITLE = "Oak Lucene";
+
+    private static final AtomicBoolean TOO_OLD_WARNING_LOGGED = new 
AtomicBoolean();
+
+    // the class path does not change at runtime, so the check is done only 
once (per expected Oak version)
+    private static final Map<String, Optional<String>> UNAVAILABLE_REASONS = 
new ConcurrentHashMap<>();
+
+    private static final Logger log = 
LoggerFactory.getLogger(LuceneIndexSupport.class);
+
+    private LuceneIndexSupport() {
+        // static methods only
+    }
+
+    /**
+     * Checks whether a compatible oak-lucene artifact is present in the class 
path.
+     * <p>
+     * Lucene classes may also be provided by other artifacts like the AEM API 
JARs (uber-jar, aem-sdk-api), which do
+     * not contain a complete and compatible oak-lucene implementation. So the 
Lucene classes have to be loaded from
+     * the oak-lucene artifact itself.
+     * </p>
+     * <p>
+     * The result is cached, as the class path does not change at runtime.
+     * </p>
+     * @param expectedOakVersion Oak version this artifact is built for
+     * @return null if a compatible oak-lucene artifact is found, otherwise 
the reason why Lucene index support
+     *         is not available
+     */
+    public static @Nullable String getUnavailableReason(@NotNull String 
expectedOakVersion) {
+        return UNAVAILABLE_REASONS
+                .computeIfAbsent(
+                        expectedOakVersion,
+                        version -> 
Optional.ofNullable(getUnavailableReason(version, LUCENE_INDEX_PROVIDER_CLASS)))
+                .orElse(null);
+    }
+
+    static @Nullable String getUnavailableReason(@NotNull String 
expectedOakVersion, @NotNull String className) {
+        Class<?> luceneIndexProviderClass;
+        try {
+            luceneIndexProviderClass = Class.forName(className, false, 
LuceneIndexSupport.class.getClassLoader());
+        } catch (ClassNotFoundException | LinkageError ex) {
+            return "oak-lucene is not in the class path. To enable it, add a 
test dependency to "
+                    + "org.apache.jackrabbit:oak-lucene:" + expectedOakVersion 
+ ".";
+        }
+        // check that the class is provided by oak-lucene, and not by another 
artifact embedding it
+        Package pkg = luceneIndexProviderClass.getPackage();
+        return getUnavailableReason(
+                expectedOakVersion, className, pkg.getImplementationTitle(), 
pkg.getImplementationVersion());
+    }
+
+    static @Nullable String getUnavailableReason(
+            @NotNull String expectedOakVersion,
+            @NotNull String className,
+            @Nullable String implementationTitle,
+            @Nullable String implementationVersion) {
+        if (!OAK_LUCENE_IMPLEMENTATION_TITLE.equals(implementationTitle) || 
implementationVersion == null) {
+            return className + " is loaded from another artifact (" + 
implementationTitle + " "
+                    + implementationVersion + ") instead of oak-lucene. To 
enable it, add a test dependency to "
+                    + "org.apache.jackrabbit:oak-lucene:" + expectedOakVersion
+                    + " and place it before other dependencies containing Oak 
Lucene classes, "
+                    + "e.g. the AEM API JARs.";
+        }
+        if (new ComparableVersion(expectedOakVersion).compareTo(new 
ComparableVersion(implementationVersion)) > 0) {
+            String reason = "oak-lucene version " + implementationVersion + " 
is older than the expected version "
+                    + expectedOakVersion + ".";
+            // oak-lucene was added deliberately, so tell about the mismatch 
also without Lucene index definitions
+            if (TOO_OLD_WARNING_LOGGED.compareAndSet(false, true)) {
+                log.warn("Lucene index support is not enabled: {}", reason);
+            }
+            return reason;
+        }
+        return null;
+    }
+
+    /**
+     * Registers Lucene query index provider and index editor provider, and 
updates async indexes synchronously.
+     * @param jcr JCR repository builder
+     * @return Action which closes the Lucene index provider, has to be called 
when the repository is shut down
+     */
+    public static @NotNull Runnable register(@NotNull Jcr jcr) {
+        LuceneIndexProvider indexProvider = new LuceneIndexProvider();
+        LuceneIndexEditorProvider indexEditorProvider = new 
LuceneIndexEditorProvider();
+        jcr.with((QueryIndexProvider) indexProvider)
+                .with((Observer) indexProvider)
+                .with(syncOnly(indexEditorProvider));
+
+        // async indexes are updated synchronously with the same index editors 
as the sync indexes
+        List<IndexEditorProvider> asyncIndexEditorProviders = new 
ArrayList<>();
+        new 
Oak.OakDefaultComponents().indexEditorProviders().forEach(asyncIndexEditorProviders::add);
+        asyncIndexEditorProviders.add(indexEditorProvider);
+        jcr.with(new 
SynchronousAsyncIndexHook(CompositeIndexEditorProvider.compose(asyncIndexEditorProviders)));
+
+        return indexProvider::close;
+    }
+
+    /**
+     * Wraps the Lucene index editor provider for the default (sync) index 
update, which also includes hybrid
+     * indexes (e.g. <code>async=["async", "nrt"]</code>). As no NRT indexing 
is configured, Lucene would write
+     * the persisted index for them, which is done already by {@link 
SynchronousAsyncIndexHook} for the async lane.
+     * A no-op editor is returned for them to avoid indexing twice (returning 
null would log a warning).
+     */
+    private static @NotNull IndexEditorProvider syncOnly(@NotNull 
IndexEditorProvider luceneIndexEditorProvider) {
+        return (type, definition, root, callback) -> {
+            if (LuceneIndexConstants.TYPE_LUCENE.equals(type)
+                    && 
definition.hasProperty(IndexConstants.ASYNC_PROPERTY_NAME)) {
+                return new DefaultEditor();
+            }
+            return luceneIndexEditorProvider.getIndexEditor(type, definition, 
root, callback);
+        };
+    }
+}
diff --git 
a/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHook.java
 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHook.java
new file mode 100644
index 0000000..44b02ff
--- /dev/null
+++ 
b/src/main/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHook.java
@@ -0,0 +1,144 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.apache.jackrabbit.oak.api.CommitFailedException;
+import org.apache.jackrabbit.oak.api.PropertyState;
+import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.plugins.index.IndexConstants;
+import org.apache.jackrabbit.oak.plugins.index.IndexEditorProvider;
+import org.apache.jackrabbit.oak.plugins.index.IndexUpdateProvider;
+import org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants;
+import org.apache.jackrabbit.oak.spi.commit.CommitHook;
+import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
+import org.apache.jackrabbit.oak.spi.commit.EditorHook;
+import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
+import org.apache.jackrabbit.oak.spi.state.DefaultNodeStateDiff;
+import org.apache.jackrabbit.oak.spi.state.NodeState;
+import org.jetbrains.annotations.NotNull;
+
+import static 
org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
+
+/**
+ * Updates asynchronous indexes synchronously as part of each commit.
+ * <p>
+ * No async indexing is running in the mock repository. Instead, for each 
async indexing lane
+ * (e.g. <code>async</code> or <code>fulltext-async</code>) referenced by a 
Lucene index definition that may be affected
+ * by the commit, an index update for this lane is executed within the commit. 
This way index definitions
+ * with <code>async</code> property (including hybrid indexes like 
<code>async=["async", "nrt"]</code>)
+ * can be used unchanged, and content is searchable as soon as it is saved.
+ * </p>
+ * <p>
+ * Only Lucene index definitions are taken into account: Oak's default content 
contains async index definitions of
+ * other types (e.g. <code>/oak:index/counter</code>), which would otherwise 
trigger an additional index update for
+ * each commit, even if no Lucene index is defined.
+ * </p>
+ * <p>
+ * Index definitions are supported in <code>/oak:index</code> and in 
<code>oak:index</code> nodes at non-root paths
+ * (only supported by Lucene indexes), which only index content below that 
path.
+ * </p>
+ */
+public final class SynchronousAsyncIndexHook implements CommitHook {
+
+    private final IndexEditorProvider indexEditorProvider;
+
+    /**
+     * @param indexEditorProvider Index editor provider (should include all 
index types)
+     */
+    public SynchronousAsyncIndexHook(@NotNull IndexEditorProvider 
indexEditorProvider) {
+        this.indexEditorProvider = indexEditorProvider;
+    }
+
+    @Override
+    public @NotNull NodeState processCommit(
+            @NotNull NodeState before, @NotNull NodeState after, @NotNull 
CommitInfo info)
+            throws CommitFailedException {
+        NodeState result = after;
+        for (String asyncLane : getAsyncLanes(before, after)) {
+            result = new EditorHook(new 
IndexUpdateProvider(indexEditorProvider, asyncLane, false))
+                    .processCommit(before, result, info);
+        }
+        return result;
+    }
+
+    /**
+     * Collects the async lane names of all Lucene index definitions that may 
be affected by the changes: the index
+     * definitions in the <code>oak:index</code> nodes of all changed nodes, 
including the root node. As changes
+     * are reported for all ancestors of a changed node, this covers all index 
definitions containing changed
+     * content, and new index definitions.
+     */
+    static @NotNull Set<String> getAsyncLanes(@NotNull NodeState before, 
@NotNull NodeState after) {
+        Set<String> asyncLanes = new TreeSet<>();
+        collectAsyncLanes(before, after, asyncLanes);
+        return asyncLanes;
+    }
+
+    /**
+     * Collects the async lane names of a single index definition, if it is a 
Lucene index definition.
+     */
+    private static void addAsyncLanesOfDefinition(@NotNull NodeState 
definition, @NotNull Set<String> asyncLanes) {
+        if 
(!LuceneIndexConstants.TYPE_LUCENE.equals(definition.getString(IndexConstants.TYPE_PROPERTY_NAME)))
 {
+            return;
+        }
+        PropertyState async = 
definition.getProperty(IndexConstants.ASYNC_PROPERTY_NAME);
+        if (async == null) {
+            return;
+        }
+        for (String value : async.getValue(Type.STRINGS)) {
+            if (!IndexConstants.INDEXING_MODE_NRT.equals(value) && 
!IndexConstants.INDEXING_MODE_SYNC.equals(value)) {
+                asyncLanes.add(value);
+            }
+        }
+    }
+
+    private static void collectAsyncLanes(
+            @NotNull NodeState before, @NotNull NodeState after, @NotNull 
Set<String> asyncLanes) {
+        for (ChildNodeEntry entry :
+                
after.getChildNode(IndexConstants.INDEX_DEFINITIONS_NAME).getChildNodeEntries())
 {
+            addAsyncLanesOfDefinition(entry.getNodeState(), asyncLanes);
+        }
+        after.compareAgainstBaseState(before, new DefaultNodeStateDiff() {
+            @Override
+            public boolean childNodeAdded(String name, NodeState after) {
+                if (isContentNode(name)) {
+                    collectAsyncLanes(EMPTY_NODE, after, asyncLanes);
+                }
+                return true;
+            }
+
+            @Override
+            public boolean childNodeChanged(String name, NodeState before, 
NodeState after) {
+                if (isContentNode(name)) {
+                    collectAsyncLanes(before, after, asyncLanes);
+                }
+                return true;
+            }
+        });
+    }
+
+    /**
+     * Index definitions and hidden nodes (e.g. index data) do not contain 
further index definitions.
+     */
+    static boolean isContentNode(@NotNull String name) {
+        return !IndexConstants.INDEX_DEFINITIONS_NAME.equals(name) && 
!name.startsWith(":");
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexNotAvailableTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexNotAvailableTest.java
new file mode 100644
index 0000000..bc66d58
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexNotAvailableTest.java
@@ -0,0 +1,111 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.query.Query;
+
+import org.apache.jackrabbit.JcrConstants;
+import org.apache.sling.testing.mock.sling.ResourceResolverType;
+import org.apache.sling.testing.mock.sling.junit.SlingContext;
+import org.apache.sling.testing.mock.sling.oak.lucene.impl.LuceneIndexSupport;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests the behavior without oak-lucene in the class path.
+ * Executed in a separate surefire execution which removes oak-lucene from the 
test class path.
+ */
+public class LuceneIndexNotAvailableTest {
+
+    private final StdErrCapture stdErr = new StdErrCapture();
+    private final SlingContext context = new 
SlingContext(ResourceResolverType.JCR_OAK);
+
+    @Rule
+    public RuleChain rules = RuleChain.outerRule(stdErr).around(context);
+
+    @Before
+    public void assumeOakLuceneMissing() {
+        try {
+            
Class.forName("org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProvider");
+            throw new AssertionError("oak-lucene is expected not to be in the 
class path for this test");
+        } catch (ClassNotFoundException ex) {
+            // expected
+        }
+    }
+
+    @Test
+    public void testLuceneIndexNotUsed() throws RepositoryException {
+        Session session = context.resourceResolver().adaptTo(Session.class);
+
+        Node index = 
session.getNode("/oak:index").addNode("luceneNotAvailable", 
"oak:QueryIndexDefinition");
+        index.setProperty("type", "lucene");
+        index.setProperty("compatVersion", 2L);
+        Node property = index.addNode("indexRules", 
JcrConstants.NT_UNSTRUCTURED)
+                .addNode(JcrConstants.NT_UNSTRUCTURED, 
JcrConstants.NT_UNSTRUCTURED)
+                .addNode("properties", JcrConstants.NT_UNSTRUCTURED)
+                .addNode("text", JcrConstants.NT_UNSTRUCTURED);
+        property.setProperty("name", "text");
+        property.setProperty("analyzed", true);
+        property.setProperty("nodeScopeIndex", true);
+        session.getRootNode()
+                .addNode("content", JcrConstants.NT_UNSTRUCTURED)
+                .setProperty("text", "The quick brown fox");
+        session.save();
+
+        assertTrue(
+                stdErr.getOutput(),
+                stdErr.getOutput()
+                        .contains("Lucene index definition 
/oak:index/luceneNotAvailable found, but Lucene index "
+                                + "support is not enabled: queries will not 
use this index, and full-text queries "
+                                + "return no results. oak-lucene is not in the 
class path."));
+
+        Query query = session.getWorkspace()
+                .getQueryManager()
+                .createQuery("SELECT * FROM [nt:unstructured] AS n WHERE 
CONTAINS(n.*, 'quick')", Query.JCR_SQL2);
+        assertEquals(0, query.execute().getNodes().getSize());
+
+        String plan = session.getWorkspace()
+                .getQueryManager()
+                .createQuery("EXPLAIN SELECT * FROM [nt:unstructured] AS n 
WHERE n.[text] = 'x'", Query.JCR_SQL2)
+                .execute()
+                .getRows()
+                .nextRow()
+                .getValue("plan")
+                .getString();
+        assertFalse("Unexpected query plan: " + plan, 
plan.contains("lucene:"));
+    }
+
+    @Test
+    public void testUnavailableReasonCached() {
+        String reason = LuceneIndexSupport.getUnavailableReason("1.86.0");
+        assertTrue(reason, reason.startsWith("oak-lucene is not in the class 
path."));
+        // the check is done only once, the same result is returned for 
further calls
+        assertSame(reason, LuceneIndexSupport.getUnavailableReason("1.86.0"));
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexTest.java
new file mode 100644
index 0000000..7346c3b
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/LuceneIndexTest.java
@@ -0,0 +1,199 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.query.Query;
+import javax.jcr.query.QueryManager;
+import javax.jcr.query.Row;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.jackrabbit.JcrConstants;
+import org.apache.sling.testing.mock.sling.ResourceResolverType;
+import org.apache.sling.testing.mock.sling.junit.SlingContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests Lucene index support, enabled automatically as oak-lucene is in the 
test class path.
+ * Async indexes are expected to be updated synchronously within each commit.
+ */
+@RunWith(Parameterized.class)
+public class LuceneIndexTest {
+
+    private static final String QUERY_FULLTEXT =
+            "SELECT * FROM [nt:unstructured] AS n WHERE ISDESCENDANTNODE(n, 
'/content') AND CONTAINS(n.*, 'quick')";
+    private static final String QUERY_PROPERTY =
+            "SELECT * FROM [nt:unstructured] AS n WHERE ISDESCENDANTNODE(n, 
'/content') AND n.[category] = 'news'";
+
+    @Parameters(name = "async={0}")
+    public static Collection<Object[]> data() {
+        return Arrays.asList(new Object[][] {
+            {"none", null},
+            {"async", new String[] {"async"}},
+            {"async,nrt", new String[] {"async", "nrt"}},
+            {"async,sync", new String[] {"async", "sync"}},
+            {"fulltext-async", new String[] {"fulltext-async"}}
+        });
+    }
+
+    @Parameter(0)
+    public String asyncLabel;
+
+    @Parameter(1)
+    public String[] async;
+
+    @Rule
+    public SlingContext context = new 
SlingContext(ResourceResolverType.JCR_OAK);
+
+    private Session session;
+
+    @Before
+    public void setUp() throws RepositoryException {
+        session = context.resourceResolver().adaptTo(Session.class);
+
+        Node properties = addIndex("luceneTest");
+        Node text = properties.addNode("text", JcrConstants.NT_UNSTRUCTURED);
+        text.setProperty("name", "text");
+        text.setProperty("analyzed", true);
+        text.setProperty("nodeScopeIndex", true);
+        Node category = properties.addNode("category", 
JcrConstants.NT_UNSTRUCTURED);
+        category.setProperty("name", "category");
+        category.setProperty("propertyIndex", true);
+        session.save();
+
+        Node content = session.getRootNode().addNode("content", 
JcrConstants.NT_UNSTRUCTURED);
+        addNode(content, "page1", "The quick brown fox", "news");
+        addNode(content, "page2", "jumps over the lazy dog", "news");
+        addNode(content, "page3", "A quick reply", "blog");
+        session.save();
+    }
+
+    /**
+     * Adds a Lucene index definition with the "async" property of the current 
test parameter.
+     * @return Properties node of the index rule for nt:unstructured
+     */
+    private Node addIndex(String name) throws RepositoryException {
+        Node index = session.getNode("/oak:index").addNode(name, 
"oak:QueryIndexDefinition");
+        index.setProperty("type", "lucene");
+        index.setProperty("compatVersion", 2L);
+        index.setProperty("evaluatePathRestrictions", true);
+        index.setProperty("includedPaths", new String[] {"/content"});
+        if (async != null) {
+            index.setProperty("async", async);
+        }
+        return index.addNode("indexRules", JcrConstants.NT_UNSTRUCTURED)
+                .addNode(JcrConstants.NT_UNSTRUCTURED, 
JcrConstants.NT_UNSTRUCTURED)
+                .addNode("properties", JcrConstants.NT_UNSTRUCTURED);
+    }
+
+    private static void addNode(Node parent, String name, String text, String 
category) throws RepositoryException {
+        Node node = parent.addNode(name, JcrConstants.NT_UNSTRUCTURED);
+        node.setProperty("text", text);
+        node.setProperty("category", category);
+    }
+
+    @Test
+    public void testFulltextQuery() throws RepositoryException {
+        assertUsesLuceneIndex(QUERY_FULLTEXT);
+        assertEquals(Set.of("/content/page1", "/content/page3"), 
queryPaths(QUERY_FULLTEXT));
+    }
+
+    @Test
+    public void testPropertyQuery() throws RepositoryException {
+        assertUsesLuceneIndex(QUERY_PROPERTY);
+        assertEquals(Set.of("/content/page1", "/content/page2"), 
queryPaths(QUERY_PROPERTY));
+    }
+
+    @Test
+    public void testContentChangesAreIndexedSynchronously() throws 
RepositoryException {
+        addNode(session.getNode("/content"), "page4", "quick update", "news");
+        session.save();
+
+        assertEquals(Set.of("/content/page1", "/content/page3", 
"/content/page4"), queryPaths(QUERY_FULLTEXT));
+        assertEquals(Set.of("/content/page1", "/content/page2", 
"/content/page4"), queryPaths(QUERY_PROPERTY));
+    }
+
+    @Test
+    public void testContentRemovalIsIndexedSynchronously() throws 
RepositoryException {
+        session.getNode("/content/page1").remove();
+        session.getNode("/content/page2").setProperty("category", "blog");
+        session.save();
+
+        assertEquals(Set.of("/content/page3"), queryPaths(QUERY_FULLTEXT));
+        assertEquals(Set.of(), queryPaths(QUERY_PROPERTY));
+    }
+
+    @Test
+    public void testIndexAddedForExistingContent() throws RepositoryException {
+        Node tag = addIndex("luceneLate").addNode("tag", 
JcrConstants.NT_UNSTRUCTURED);
+        tag.setProperty("name", "tag");
+        tag.setProperty("propertyIndex", true);
+        session.getNode("/content/page2").setProperty("tag", "animal");
+        session.save();
+        session.getNode("/content/page3").setProperty("tag", "animal");
+        session.save();
+
+        String query =
+                "SELECT * FROM [nt:unstructured] AS n WHERE 
ISDESCENDANTNODE(n, '/content') AND n.[tag] = 'animal'";
+        assertUsesLuceneIndex(query, "luceneLate");
+        assertEquals(Set.of("/content/page2", "/content/page3"), 
queryPaths(query));
+    }
+
+    private Set<String> queryPaths(String statement) throws 
RepositoryException {
+        QueryManager queryManager = session.getWorkspace().getQueryManager();
+        NodeIterator nodes =
+                queryManager.createQuery(statement, 
Query.JCR_SQL2).execute().getNodes();
+        Set<String> paths = new HashSet<>();
+        while (nodes.hasNext()) {
+            paths.add(nodes.nextNode().getPath());
+        }
+        return paths;
+    }
+
+    private void assertUsesLuceneIndex(String statement) throws 
RepositoryException {
+        assertUsesLuceneIndex(statement, "luceneTest");
+    }
+
+    private void assertUsesLuceneIndex(String statement, String indexName) 
throws RepositoryException {
+        QueryManager queryManager = session.getWorkspace().getQueryManager();
+        Row row = queryManager
+                .createQuery("EXPLAIN " + statement, Query.JCR_SQL2)
+                .execute()
+                .getRows()
+                .nextRow();
+        String plan = row.getValue("plan").getString();
+        assertTrue("Unexpected query plan: " + plan, plan.contains("lucene:" + 
indexName));
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/NestedLuceneIndexTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/NestedLuceneIndexTest.java
new file mode 100644
index 0000000..07c83bd
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/NestedLuceneIndexTest.java
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.query.Query;
+import javax.jcr.query.QueryManager;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.jackrabbit.JcrConstants;
+import org.apache.sling.testing.mock.sling.ResourceResolverType;
+import org.apache.sling.testing.mock.sling.junit.SlingContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests Lucene index definitions in an oak:index node at a non-root path, 
which only index content below that path.
+ * The "fulltext-async" lane is used only by the nested index definition, so 
it is not referenced in /oak:index.
+ */
+@RunWith(Parameterized.class)
+public class NestedLuceneIndexTest {
+
+    private static final String QUERY_SITE =
+            "SELECT * FROM [nt:unstructured] AS n WHERE ISDESCENDANTNODE(n, 
'/content/site') AND CONTAINS(n.*, 'quick')";
+    private static final String QUERY_OTHER =
+            "SELECT * FROM [nt:unstructured] AS n WHERE ISDESCENDANTNODE(n, 
'/content/other') AND CONTAINS(n.*, 'quick')";
+
+    @Parameters(name = "async={0}")
+    public static Collection<Object[]> data() {
+        return Arrays.asList(new Object[][] {
+            {"none", null},
+            {"async", new String[] {"async"}},
+            {"async,nrt", new String[] {"async", "nrt"}},
+            {"fulltext-async", new String[] {"fulltext-async"}}
+        });
+    }
+
+    @Parameter(0)
+    public String asyncLabel;
+
+    @Parameter(1)
+    public String[] async;
+
+    @Rule
+    public SlingContext context = new 
SlingContext(ResourceResolverType.JCR_OAK);
+
+    private Session session;
+
+    @Before
+    public void setUp() throws RepositoryException {
+        session = context.resourceResolver().adaptTo(Session.class);
+        Node content = session.getRootNode().addNode("content", 
JcrConstants.NT_UNSTRUCTURED);
+        Node site = content.addNode("site", JcrConstants.NT_UNSTRUCTURED);
+        Node other = content.addNode("other", JcrConstants.NT_UNSTRUCTURED);
+        session.save();
+
+        addIndex(site, "nested");
+        session.save();
+
+        addNode(site, "page1", "The quick brown fox");
+        addNode(site, "page2", "jumps over the lazy dog");
+        addNode(other, "page1", "A quick reply");
+        session.save();
+    }
+
+    private void addIndex(Node parent, String name) throws RepositoryException 
{
+        Node oakIndex = parent.hasNode("oak:index")
+                ? parent.getNode("oak:index")
+                : parent.addNode("oak:index", JcrConstants.NT_UNSTRUCTURED);
+        Node index = oakIndex.addNode(name, "oak:QueryIndexDefinition");
+        index.setProperty("type", "lucene");
+        index.setProperty("compatVersion", 2L);
+        if (async != null) {
+            index.setProperty("async", async);
+        }
+        Node text = index.addNode("indexRules", JcrConstants.NT_UNSTRUCTURED)
+                .addNode(JcrConstants.NT_UNSTRUCTURED, 
JcrConstants.NT_UNSTRUCTURED)
+                .addNode("properties", JcrConstants.NT_UNSTRUCTURED)
+                .addNode("text", JcrConstants.NT_UNSTRUCTURED);
+        text.setProperty("name", "text");
+        text.setProperty("analyzed", true);
+        text.setProperty("nodeScopeIndex", true);
+    }
+
+    private static void addNode(Node parent, String name, String text) throws 
RepositoryException {
+        parent.addNode(name, JcrConstants.NT_UNSTRUCTURED).setProperty("text", 
text);
+    }
+
+    @Test
+    public void testFulltextQuery() throws RepositoryException {
+        assertTrue(getPlan(QUERY_SITE), 
getPlan(QUERY_SITE).contains("lucene:nested"));
+        assertEquals(Set.of("/content/site/page1"), queryPaths(QUERY_SITE));
+    }
+
+    @Test
+    public void testContentOutsideIndexPathIsNotIndexed() throws 
RepositoryException {
+        assertFalse(getPlan(QUERY_OTHER), 
getPlan(QUERY_OTHER).contains("lucene:"));
+        assertEquals(Set.of(), queryPaths(QUERY_OTHER));
+    }
+
+    @Test
+    public void testContentChangesAreIndexedSynchronously() throws 
RepositoryException {
+        addNode(session.getNode("/content/site"), "page3", "quick update");
+        session.getNode("/content/site/page1").remove();
+        session.save();
+
+        assertEquals(Set.of("/content/site/page3"), queryPaths(QUERY_SITE));
+    }
+
+    @Test
+    public void testIndexAddedForExistingContent() throws RepositoryException {
+        addIndex(session.getNode("/content/other"), "nestedLate");
+        session.save();
+
+        assertTrue(getPlan(QUERY_OTHER), 
getPlan(QUERY_OTHER).contains("lucene:nestedLate"));
+        assertEquals(Set.of("/content/other/page1"), queryPaths(QUERY_OTHER));
+    }
+
+    private Set<String> queryPaths(String statement) throws 
RepositoryException {
+        QueryManager queryManager = session.getWorkspace().getQueryManager();
+        NodeIterator nodes =
+                queryManager.createQuery(statement, 
Query.JCR_SQL2).execute().getNodes();
+        Set<String> paths = new HashSet<>();
+        while (nodes.hasNext()) {
+            paths.add(nodes.nextNode().getPath());
+        }
+        return paths;
+    }
+
+    private String getPlan(String statement) throws RepositoryException {
+        return session.getWorkspace()
+                .getQueryManager()
+                .createQuery("EXPLAIN " + statement, Query.JCR_SQL2)
+                .execute()
+                .getRows()
+                .nextRow()
+                .getValue("plan")
+                .getString();
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/StdErrCapture.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/StdErrCapture.java
new file mode 100644
index 0000000..926979f
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/StdErrCapture.java
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+
+import org.junit.rules.ExternalResource;
+
+/**
+ * Captures System.err, which is where slf4j-simple writes log messages to in 
the tests.
+ */
+public final class StdErrCapture extends ExternalResource {
+
+    private final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+    private PrintStream originalErr;
+
+    @Override
+    protected void before() {
+        originalErr = System.err;
+        System.setErr(new PrintStream(buffer, true, StandardCharsets.UTF_8));
+    }
+
+    @Override
+    protected void after() {
+        System.setErr(originalErr);
+        originalErr.print(getOutput());
+    }
+
+    public String getOutput() {
+        return buffer.toString(StandardCharsets.UTF_8);
+    }
+
+    public int count(String text) {
+        String output = getOutput();
+        int count = 0;
+        int index = output.indexOf(text);
+        while (index >= 0) {
+            count++;
+            index = output.indexOf(text, index + text.length());
+        }
+        return count;
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarningTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarningTest.java
new file mode 100644
index 0000000..39a2cc2
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexMissingWarningTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import org.apache.jackrabbit.oak.api.CommitFailedException;
+import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
+import org.apache.jackrabbit.oak.spi.commit.EditorHook;
+import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
+import org.apache.jackrabbit.oak.spi.state.NodeState;
+import org.apache.sling.testing.mock.sling.oak.lucene.StdErrCapture;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static 
org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
+import static org.junit.Assert.assertEquals;
+
+public class LuceneIndexMissingWarningTest {
+
+    private static final String REASON = "Reason with hint.";
+    // index names are unique per test, as warnings are logged only once per 
index path and JVM
+    private static final String PREFIX = 
LuceneIndexMissingWarningTest.class.getSimpleName();
+
+    @Rule
+    public StdErrCapture stdErr = new StdErrCapture();
+
+    private final EditorHook hook = new EditorHook(new 
LuceneIndexMissingWarning(REASON));
+
+    @Test
+    public void testLuceneIndexAdded() throws CommitFailedException {
+        NodeBuilder after = EMPTY_NODE.builder();
+        after.child("content");
+        addIndex(after, PREFIX + "Added", "lucene");
+
+        commit(EMPTY_NODE, after.getNodeState());
+
+        assertWarnings(PREFIX + "Added", 1);
+    }
+
+    @Test
+    public void testLuceneIndexChanged() throws CommitFailedException {
+        NodeBuilder before = EMPTY_NODE.builder();
+        before.child("content");
+        addIndex(before, PREFIX + "Changed", "property");
+        NodeState beforeState = before.getNodeState();
+
+        // non-Lucene index definition changed, other root node changed
+        NodeBuilder after1 = beforeState.builder();
+        after1.child("content").setProperty("prop", "value1");
+        after1.child("oak:index").child(PREFIX + 
"Changed").setProperty("prop", "value1");
+        NodeState after1State = after1.getNodeState();
+        commit(beforeState, after1State);
+        assertWarnings(PREFIX + "Changed", 0);
+
+        // changed to Lucene index definition
+        NodeBuilder after2 = after1State.builder();
+        after2.child("oak:index").child(PREFIX + 
"Changed").setProperty("type", "lucene");
+        NodeState after2State = after2.getNodeState();
+        commit(after1State, after2State);
+        assertWarnings(PREFIX + "Changed", 1);
+
+        // changed again - no additional warning
+        NodeBuilder after3 = after2State.builder();
+        after3.child("oak:index").child(PREFIX + 
"Changed").setProperty("prop", "value2");
+        commit(after2State, after3.getNodeState());
+        assertWarnings(PREFIX + "Changed", 1);
+    }
+
+    @Test
+    public void testNonLuceneIndexAdded() throws CommitFailedException {
+        NodeBuilder after = EMPTY_NODE.builder();
+        addIndex(after, PREFIX + "Property", "property");
+        addIndex(after, PREFIX + "NoType", null);
+
+        commit(EMPTY_NODE, after.getNodeState());
+
+        assertEquals(stdErr.getOutput(), 0, stdErr.count("Lucene index 
definition"));
+    }
+
+    @Test
+    public void testNestedLuceneIndexAdded() throws CommitFailedException {
+        NodeBuilder after = EMPTY_NODE.builder();
+        NodeBuilder site = after.child("content").child("site");
+        site.child("oak:index").child(PREFIX + "Nested").setProperty("type", 
"lucene");
+        // hidden nodes are not inspected
+        site.child(":hidden").child("oak:index").child(PREFIX + 
"Hidden").setProperty("type", "lucene");
+
+        commit(EMPTY_NODE, after.getNodeState());
+
+        assertWarnings("/content/site/oak:index/" + PREFIX + "Nested", 1);
+        assertEquals(stdErr.getOutput(), 0, stdErr.count(PREFIX + "Hidden"));
+    }
+
+    private void commit(NodeState before, NodeState after) throws 
CommitFailedException {
+        hook.processCommit(before, after, CommitInfo.EMPTY);
+    }
+
+    private static void addIndex(NodeBuilder root, String name, String type) {
+        NodeBuilder index = root.child("oak:index").child(name);
+        if (type != null) {
+            index.setProperty("type", type);
+        }
+    }
+
+    private void assertWarnings(String indexName, int expected) {
+        assertEquals(
+                stdErr.getOutput(),
+                expected,
+                stdErr.count("Lucene index definition " + 
(indexName.startsWith("/") ? "" : "/oak:index/") + indexName
+                        + " found, but Lucene index support is not enabled: 
queries will not use this index, "
+                        + "and full-text queries return no results. " + 
REASON));
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupportTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupportTest.java
new file mode 100644
index 0000000..3b3426d
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/LuceneIndexSupportTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import org.apache.sling.testing.mock.sling.oak.lucene.StdErrCapture;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class LuceneIndexSupportTest {
+
+    private static final String LUCENE_INDEX_PROVIDER_CLASS =
+            
"org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProvider";
+
+    @Rule
+    public StdErrCapture stdErr = new StdErrCapture();
+
+    @Test
+    public void testAvailable() {
+        assertNull(LuceneIndexSupport.getUnavailableReason("1.0"));
+    }
+
+    @Test
+    public void testNotInClassPath() {
+        String reason = LuceneIndexSupport.getUnavailableReason("1.86.0", 
"org.example.DoesNotExist");
+        assertTrue(reason, reason.startsWith("oak-lucene is not in the class 
path."));
+        assertTrue(reason, 
reason.contains("org.apache.jackrabbit:oak-lucene:1.86.0"));
+    }
+
+    @Test
+    public void testOtherArtifact() {
+        // class from another artifact with different implementation title
+        String reason = LuceneIndexSupport.getUnavailableReason("1.86.0", 
Test.class.getName());
+        assertTrue(reason, reason.contains("is loaded from another artifact"));
+        assertTrue(reason, reason.contains("e.g. the AEM API JARs"));
+    }
+
+    @Test
+    public void testOakLuceneTitleWithoutVersion() {
+        String reason =
+                LuceneIndexSupport.getUnavailableReason("1.86.0", 
LUCENE_INDEX_PROVIDER_CLASS, "Oak Lucene", null);
+        assertTrue(reason, reason.contains("is loaded from another artifact 
(Oak Lucene null)"));
+    }
+
+    @Test
+    public void testTooOldVersion() {
+        String reason1 =
+                LuceneIndexSupport.getUnavailableReason("1.86.0", 
LUCENE_INDEX_PROVIDER_CLASS, "Oak Lucene", "1.80.0");
+        String reason2 =
+                LuceneIndexSupport.getUnavailableReason("1.86.0", 
LUCENE_INDEX_PROVIDER_CLASS, "Oak Lucene", "1.80.0");
+        assertEquals("oak-lucene version 1.80.0 is older than the expected 
version 1.86.0.", reason1);
+        assertEquals(reason1, reason2);
+        // warning is logged only once
+        assertEquals(1, stdErr.count("Lucene index support is not enabled: " + 
reason1));
+    }
+
+    @Test
+    public void testNewerVersion() {
+        assertNull(
+                LuceneIndexSupport.getUnavailableReason("1.86.0", 
LUCENE_INDEX_PROVIDER_CLASS, "Oak Lucene", "1.88.0"));
+    }
+}
diff --git 
a/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHookTest.java
 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHookTest.java
new file mode 100644
index 0000000..b04c28a
--- /dev/null
+++ 
b/src/test/java/org/apache/sling/testing/mock/sling/oak/lucene/impl/SynchronousAsyncIndexHookTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+package org.apache.sling.testing.mock.sling.oak.lucene.impl;
+
+import java.util.Set;
+
+import org.apache.jackrabbit.oak.api.CommitFailedException;
+import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
+import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
+import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
+import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
+import org.apache.jackrabbit.oak.spi.state.NodeState;
+import org.junit.Test;
+
+import static 
org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
+import static org.junit.Assert.assertEquals;
+
+public class SynchronousAsyncIndexHookTest {
+
+    @Test
+    public void testAsyncLanesOfChangedPaths() throws CommitFailedException {
+        MemoryNodeStore store = new MemoryNodeStore();
+        NodeBuilder builder = store.getRoot().builder();
+        addIndex(builder, "root", "async", "nrt");
+        addIndex(builder.child("content").child("site"), "nested", 
"fulltext-async", "sync");
+        addIndex(builder.child("content").child("unchanged"), "unchanged", 
"unchanged-lane");
+        // index definitions in hidden nodes are not collected
+        addIndex(builder.child(":hidden"), "hidden", "hidden-lane");
+        // async index definitions of other types are not collected
+        addIndexOfType(builder, "counter", "counter", "other-lane");
+
+        // initial content: all index definitions outside hidden nodes
+        assertEquals(
+                Set.of("async", "fulltext-async", "unchanged-lane"),
+                SynchronousAsyncIndexHook.getAsyncLanes(EMPTY_NODE, 
builder.getNodeState()));
+
+        // merged into the node store like in a repository, so the diff is 
reported only for changed nodes
+        NodeState before = store.merge(builder, EmptyHook.INSTANCE, 
CommitInfo.EMPTY);
+
+        // content changed below /content/site: index definitions of the root 
and /content/site
+        NodeBuilder changed = before.builder();
+        
changed.child("content").child("site").child("page").setProperty("text", 
"value");
+        assertEquals(
+                Set.of("async", "fulltext-async"),
+                SynchronousAsyncIndexHook.getAsyncLanes(before, 
changed.getNodeState()));
+    }
+
+    @Test
+    public void testNoAsyncLanesWithoutLuceneIndex() throws 
CommitFailedException {
+        MemoryNodeStore store = new MemoryNodeStore();
+        NodeBuilder builder = store.getRoot().builder();
+        // like the node counter index of Oak's default content
+        addIndexOfType(builder, "counter", "counter", "async");
+        NodeState before = store.merge(builder, EmptyHook.INSTANCE, 
CommitInfo.EMPTY);
+
+        NodeBuilder changed = before.builder();
+        changed.child("content").setProperty("text", "value");
+        assertEquals(Set.of(), SynchronousAsyncIndexHook.getAsyncLanes(before, 
changed.getNodeState()));
+    }
+
+    private static void addIndex(NodeBuilder parent, String name, String... 
async) {
+        addIndexOfType(parent, name, "lucene", async);
+    }
+
+    private static void addIndexOfType(NodeBuilder parent, String name, String 
type, String... async) {
+        NodeBuilder definition = parent.child("oak:index").child(name);
+        definition.setProperty("type", type);
+        definition.setProperty("async", Set.of(async), Type.STRINGS);
+    }
+}

Reply via email to