korlov42 commented on code in PR #980:
URL: https://github.com/apache/ignite-3/pull/980#discussion_r940333995


##########
modules/index/src/main/java/org/apache/ignite/internal/index/IndexManager.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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.ignite.internal.index;
+
+import static 
org.apache.ignite.internal.schema.definition.TableDefinitionImpl.canonicalName;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import org.apache.ignite.configuration.schemas.table.HashIndexView;
+import org.apache.ignite.configuration.schemas.table.SortedIndexView;
+import org.apache.ignite.configuration.schemas.table.TableIndexChange;
+import org.apache.ignite.configuration.schemas.table.TableIndexView;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.manager.IgniteComponent;
+import org.apache.ignite.internal.table.distributed.TableManager;
+import org.apache.ignite.internal.util.CollectionUtils;
+import org.apache.ignite.internal.util.IgniteSpinBusyLock;
+import org.apache.ignite.internal.util.StringUtils;
+import org.apache.ignite.lang.ErrorGroups;
+import org.apache.ignite.lang.ErrorGroups.Common;
+import org.apache.ignite.lang.ErrorGroups.Table;
+import org.apache.ignite.lang.IgniteInternalException;
+import org.apache.ignite.lang.IndexAlreadyExistsException;
+import org.apache.ignite.lang.NodeStoppingException;
+import org.apache.ignite.lang.TableNotFoundException;
+
+/**
+ * An Ignite component that is responsible for handling index-related commands 
like CREATE or DROP
+ * as well as managing indexes lifecycle.
+ */
+public class IndexManager implements IgniteComponent {
+    private static final IgniteLogger LOG = 
Loggers.forClass(IndexManager.class);
+
+    private final TableManager tableManager;
+
+    private final Map<UUID, Index> indices = new ConcurrentHashMap<>();
+
+    /** Busy lock to stop synchronously. */
+    private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
+
+    /** Prevents double stopping of the component. */
+    private final AtomicBoolean stopGuard = new AtomicBoolean();
+
+    /**
+     * Constructor.
+     *
+     * @param tableManager Table manager.
+     */
+    public IndexManager(
+            TableManager tableManager
+    ) {
+        this.tableManager = Objects.requireNonNull(tableManager, 
"tableManager");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void start() {
+        LOG.info("Index manager started");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void stop() throws Exception {
+        LOG.debug("Index manager is about to stop");
+
+        if (!stopGuard.compareAndSet(false, true)) {
+            LOG.debug("Index manager already stopped");
+
+            return;
+        }
+
+        busyLock.block();
+
+        LOG.info("Index manager stopped");
+    }
+
+    /**
+     * Creates index from provided configuration changer.
+     *
+     * @param schemaName A name of the schema to create index in.
+     * @param indexName A name of the index to create.
+     * @param tableName A name of the table to create index for.
+     * @param indexChange A consumer that suppose to change the configuration 
in order to provide description of an index.
+     * @return A future represented the result of creation.
+     */
+    // TODO: https://issues.apache.org/jira/browse/IGNITE-17474
+    // Validation of the index name uniqueness is not implemented, because 
with given
+    // configuration hierarchy this is a bit tricky exercise. Given that this 
hierarchy
+    // is subject to change in the future, seems to be more rational just to 
omit this
+    // part for now
+    public CompletableFuture<Index> createIndexAsync(
+            String schemaName,
+            String indexName,
+            String tableName,
+            Consumer<TableIndexChange> indexChange
+    ) {
+        if (!busyLock.enterBusy()) {
+            return CompletableFuture.failedFuture(new NodeStoppingException());
+        }
+
+        LOG.debug("Going to create index [schemaName={}, tableName={}, 
indexName={}]", schemaName, tableName, indexName);
+
+        try {
+            validateName(indexName);
+        } catch (Exception ex) {
+            return CompletableFuture.failedFuture(ex);
+        }
+
+        try {
+            CompletableFuture<Index> future = new CompletableFuture<>();
+
+            var canonicalName = canonicalName(schemaName, tableName);
+
+            tableManager.tableAsyncInternal(canonicalName).thenAccept((table) 
-> {
+                if (table == null) {
+                    var exception = new TableNotFoundException(canonicalName);
+
+                    LOG.info("Unable to create index [schemaName={}, 
tableName={}, indexName={}]",
+                            exception, schemaName, tableName, indexName);
+
+                    future.completeExceptionally(exception);
+
+                    return;
+                }
+
+                tableManager.alterTableAsync(table.name(), tableChange -> 
tableChange.changeIndices(indexListChange -> {
+                    if (indexListChange.get(indexName) != null) {
+                        var exception = new 
IndexAlreadyExistsException(indexName);
+
+                        LOG.info("Unable to create index [schemaName={}, 
tableName={}, indexName={}]",
+                                exception, schemaName, tableName, indexName);
+
+                        future.completeExceptionally(exception);
+
+                        return;
+                    }
+
+                    indexListChange.create(indexName, indexChange);
+
+                    TableIndexView indexView = indexListChange.get(indexName);
+
+                    Set<String> columnNames = 
Set.copyOf(tableChange.columns().namedListKeys());
+
+                    validateColumns(indexView, columnNames);
+                })).whenComplete((index, th) -> {
+                    if (th != null) {
+                        LOG.info("Unable to create index [schemaName={}, 
tableName={}, indexName={}]",
+                                th, schemaName, tableName, indexName);
+
+                        future.completeExceptionally(th);
+                    } else if (!future.isDone()) {
+                        // don't pay too much attention to this part because 
it should be reworked
+                        // within refactoring of schema objects: when both 
tables and indexes will be derived
+                        // from common parent and become entity of the same 
level in the configuration,
+                        // then there sill be no need to look up indices in 
such way
+
+                        var createdIndex = indices.values().stream()
+                                .filter(idx -> indexName.equals(idx.name()))
+                                .findFirst()
+                                .orElse(null);
+
+                        if (createdIndex != null) {
+                            LOG.info("Index created [schemaName={}, 
tableName={}, indexName={}, indexId={}]",
+                                    schemaName, tableName, indexName, 
createdIndex.id());
+
+                            future.complete(createdIndex);
+                        } else {
+                            var exception = new IgniteInternalException(
+                                    Common.UNEXPECTED_ERR, "Looks like the 
index was concurrently deleted");
+
+                            LOG.info("Unable to create index [schemaName={}, 
tableName={}, indexName={}]",
+                                    exception, schemaName, tableName, 
indexName);
+
+                            future.completeExceptionally(exception);
+                        }
+                    }
+                });
+            });
+
+            return future;
+        } finally {
+            busyLock.leaveBusy();
+        }
+    }
+
+    /**
+     * Drops the index with a given name.
+     *
+     * @param schemaName A name of the schema the index belong to.
+     * @param indexName A name of the index to drop.
+     * @return A future representing the result of the operation.
+     */
+    // TODO: https://issues.apache.org/jira/browse/IGNITE-17474
+    // For now it is impossible to locate the index neither by id nor name.
+    public CompletableFuture<Void> dropIndexAsync(
+            String schemaName,
+            String indexName
+    ) {
+        return CompletableFuture.failedFuture(new 
UnsupportedOperationException());
+    }
+
+    private void validateName(String indexName) {
+        if (StringUtils.nullOrEmpty(indexName)) {
+            throw new IgniteInternalException(
+                    ErrorGroups.Index.INVALID_INDEX_DEFINITION_ERR,
+                    "Index name should be at least 1 character long"
+            );
+        }
+    }
+
+    private void validateColumns(TableIndexView indexView, Set<String> 
tableColumns) {
+        if (indexView instanceof SortedIndexView) {
+            var sortedIndexView = (SortedIndexView) indexView;
+
+            validateColumns(sortedIndexView.columns().namedListKeys(), 
tableColumns);
+        } else if (indexView instanceof HashIndexView) {
+            validateColumns(Arrays.asList(((HashIndexView) 
indexView).columnNames()), tableColumns);
+        } else {
+            throw new IllegalStateException("Unknown index type [type=" + 
(indexView != null ? indexView.getClass() : null) + ']');

Review Comment:
   IgniteException is about violation business rules, and 
IllegalArgumentException is about passing wrong arguments (for instance, 
javadoc said "Argument should be greater than zero" and someone passed -1). 
Both of these are exception of valid codebase, but line in question is about 
someone just added new index types, but failed to update all required places, 
hence we got inconsistency in our codebase
   
   Is it OK to throw AssertionError here? 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to