Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14363] feat(core): Add domain backing tags (#14559)

Jerry Shao1650b8988da9
diff --git a/core/src/main/java/org/apache/gravitino/SupportsDomainOperations.java b/core/src/main/java/org/apache/gravitino/SupportsDomainOperations.java
index cfeaac272a..9ea3ca1507 100644
--- a/core/src/main/java/org/apache/gravitino/SupportsDomainOperations.java
+++ b/core/src/main/java/org/apache/gravitino/SupportsDomainOperations.java
@@ -20,24 +20,29 @@ package org.apache.gravitino;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
+import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.apache.gravitino.domain.Domain;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.tag.TagValue;
/**
* The domain changes whose rules depend on other domains, or whose authorization depends on the
- * current parent: creating a domain, changing or removing its parent and changing its status. Each
- * change runs in one transaction. It locks the rows of the domains involved, reads them, hands them
- * to the caller's check as a {@link LockedDomainState}, and writes the change only if the check
- * returns. A check that throws rolls the change back, and the exception reaches the caller
- * unchanged, unless it is caused by a database error, which is reported like any other failure of
- * the store.
+ * current parent: creating a domain, changing or removing its parent, changing its status and
+ * changing its backing tag. Each change runs in one transaction. It locks the rows of the domains
+ * involved, reads them, hands them to the caller's check as a {@link LockedDomainState}, and writes
+ * the change only if the check returns. A check that throws rolls the change back, and the
+ * exception reaches the caller unchanged, unless it is caused by a database error, which is
+ * reported like any other failure of the store.
*
* <p>The store only locks, reads and writes; the rules themselves, such as how deep the hierarchy
* may be or which status a parent needs, are the caller's check. Since the check sees the domains
@@ -47,29 +52,89 @@ import org.apache.gravitino.meta.DomainEntity;
* <p>In a {@link LockedDomainState}, the domain being changed and its parent are read with locking
* reads, which do not read the backing tag name, so their {@link DomainEntity#backingTag()} is
* empty; their backing tag ID and value are set. For an insert, the domain is the caller's new
- * entity.
+ * entity with its backing tag set.
*/
public interface SupportsDomainOperations {
/**
- * Inserts a domain. If the domain has a parent, it is inserted as a sub-domain of that parent,
- * together with its parent edge.
+ * Inserts a domain backed by an existing tag. If the domain has a parent, it is inserted as a
+ * sub-domain of that parent, together with its parent edge.
*
- * <p>The metalake is locked shared and the parent, if any, is locked shared, so the parent cannot
- * be attached elsewhere, deleted or unpublished before the change commits. The domain is written
- * before the check runs, so a duplicate name fails first. The check gets the new domain, the
- * parent with its own parent set, and no sub-domains. This operation must own its transaction so
- * a failed check rolls back the inserted domain; it cannot run inside another transaction.
+ * <p>The metalake is locked shared, the parent, if any, shared, and the tag exclusively, so the
+ * parent cannot be attached elsewhere, deleted or unpublished, and the tag cannot be deleted or
+ * bound to another domain, before the change commits. The tag is resolved by name and re-checked
+ * after it is locked. The parent and the tag are locked before the domain is written, so a
+ * missing parent or tag is reported before a duplicate domain name; the domain is written before
+ * the check runs, so a duplicate name is reported before a broken rule. The check gets the new
+ * domain with its backing tag set, the parent with its own parent set, no sub-domains, the tag,
+ * and the domains it already backs. This operation must own its transaction and cannot run inside
+ * another transaction.
*
- * @param domain The domain to insert.
+ * @param domain The domain to insert, without a backing tag.
+ * @param backingTag The existing tag, with an optional value, that backs the domain.
* @param check The check of the locked state.
* @throws IOException If the domain cannot be stored.
* @throws EntityAlreadyExistsException If a domain with the same name exists.
* @throws NoSuchEntityException If the metalake or the parent does not exist.
+ * @throws NoSuchTagException If the tag does not exist.
* @throws IllegalStateException If it is called inside a transaction.
*/
- void insertDomain(DomainEntity domain, Consumer<LockedDomainState> check)
- throws IOException, EntityAlreadyExistsException, NoSuchEntityException;
+ void insertDomainWithBackingTag(
+ DomainEntity domain, TagValue backingTag, Consumer<LockedDomainState> check)
+ throws IOException, EntityAlreadyExistsException, NoSuchEntityException, NoSuchTagException;
+
+ /**
+ * Inserts a domain together with a new tag that backs it without a value. If the domain has a
+ * parent, it is inserted as a sub-domain of that parent, together with its parent edge. The tag,
+ * the domain and the edge are written in one transaction, so a failure leaves none of them.
+ *
+ * <p>The metalake is locked shared and the parent, if any, shared. The new tag has no row to lock
+ * yet; the unique key on its name fails a concurrent tag with the same name. The domain is
+ * written before the tag, so a duplicate domain name is reported before a duplicate tag name, and
+ * both are written before the check runs, so a duplicate name is reported before a broken rule.
+ * The check gets the new domain with its backing tag set, the parent with its own parent set, no
+ * sub-domains, the new tag, and no other domains.
+ *
+ * @param domain The domain to insert, without a backing tag.
+ * @param backingTag The new tag that backs the domain.
+ * @param check The check of the locked state.
+ * @throws IOException If the domain cannot be stored.
+ * @throws EntityAlreadyExistsException If a domain with the same name exists.
+ * @throws NoSuchEntityException If the metalake or the parent does not exist.
+ * @throws TagAlreadyExistsException If a tag with the same name exists.
+ * @throws IllegalStateException If it is called inside a transaction.
+ */
+ void insertDomainWithNewBackingTag(
+ DomainEntity domain, TagEntity backingTag, Consumer<LockedDomainState> check)
+ throws IOException, EntityAlreadyExistsException, NoSuchEntityException,
+ TagAlreadyExistsException;
+
+ /**
+ * Sets or removes the backing tag of a domain. Setting the current backing tag writes nothing.
+ *
+ * <p>The metalake is locked shared, the domain exclusively and then the new tag, if any,
+ * exclusively, so the tag cannot be deleted or bound to another domain before the change commits.
+ * The tag is resolved by name and re-checked after it is locked. The check gets the domain with
+ * its current parent and backing tag set, no parent and no sub-domains, the new tag, and the
+ * domains it already backs, which include this domain if it is already backed by the tag.
+ *
+ * @param ident The identifier of the domain.
+ * @param backingTag The existing tag, with an optional value, that backs the domain, or null to
+ * remove the backing tag.
+ * @param auditInfo The audit info of the change; the domain keeps its creator and takes its last
+ * modifier.
+ * @param check The check of the locked state.
+ * @return The domain after the change.
+ * @throws IOException If the change cannot be stored.
+ * @throws NoSuchEntityException If the domain does not exist.
+ * @throws NoSuchTagException If the tag does not exist.
+ */
+ DomainEntity updateDomainBackingTagAndGet(
+ NameIdentifier ident,
+ @Nullable TagValue backingTag,
+ AuditInfo auditInfo,
+ Consumer<LockedDomainState> check)
+ throws IOException, NoSuchEntityException, NoSuchTagException;
/**
* Sets the parent of a domain: attaches a top-level domain, or moves a sub-domain to another
@@ -161,9 +226,11 @@ public interface SupportsDomainOperations {
private final DomainEntity domain;
@Nullable private final DomainEntity parent;
private final List<DomainEntity> subDomains;
+ @Nullable private final TagEntity backingTag;
+ private final List<DomainEntity> backingTagBindings;
/**
- * Creates the locked state of a change.
+ * Creates the locked state of a change that involves no backing tag.
*
* @param domain The domain being changed, with its current parent set.
* @param parent The parent involved in the change, with its own parent set, or null if none.
@@ -171,9 +238,29 @@ public interface SupportsDomainOperations {
*/
public LockedDomainState(
DomainEntity domain, @Nullable DomainEntity parent, List<DomainEntity> subDomains) {
+ this(domain, parent, subDomains, null, Collections.emptyList());
+ }
+
+ /**
+ * Creates the locked state of a change.
+ *
+ * @param domain The domain being changed, with its current parent set.
+ * @param parent The parent involved in the change, with its own parent set, or null if none.
+ * @param subDomains The sub-domains of the domain being changed.
+ * @param backingTag The backing tag the change binds, or null if none.
+ * @param backingTagBindings The domains the backing tag backs before the change.
+ */
+ public LockedDomainState(
+ DomainEntity domain,
+ @Nullable DomainEntity parent,
+ List<DomainEntity> subDomains,
+ @Nullable TagEntity backingTag,
+ List<DomainEntity> backingTagBindings) {
this.domain = domain;
this.parent = parent;
this.subDomains = ImmutableList.copyOf(subDomains);
+ this.backingTag = backingTag;
+ this.backingTagBindings = ImmutableList.copyOf(backingTagBindings);
}
/**
@@ -206,5 +293,25 @@ public interface SupportsDomainOperations {
public List<DomainEntity> subDomains() {
return subDomains;
}
+
+ /**
+ * Returns the backing tag the change binds, as it is under the lock: the existing tag to bind,
+ * or the new tag to create.
+ *
+ * @return The backing tag, or empty if the change binds none.
+ */
+ public Optional<TagEntity> backingTag() {
+ return Optional.ofNullable(backingTag);
+ }
+
+ /**
+ * Returns the domains that the backing tag of the change backs before the change, read under
+ * the lock on the tag. Their parents are not set.
+ *
+ * @return The domains bound to the backing tag.
+ */
+ public List<DomainEntity> backingTagBindings() {
+ return backingTagBindings;
+ }
}
}
diff --git a/core/src/main/java/org/apache/gravitino/domain/DomainDispatcher.java b/core/src/main/java/org/apache/gravitino/domain/DomainDispatcher.java
index 3e75233f96..deb4ba6e02 100644
--- a/core/src/main/java/org/apache/gravitino/domain/DomainDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/domain/DomainDispatcher.java
@@ -22,12 +22,16 @@ import java.util.Arrays;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.gravitino.annotation.Evolving;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchDomainException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NonEmptyDomainException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.tag.TagValue;
/**
* The domain operations of the server. Domains are one level deep: a domain is either top-level or
@@ -48,6 +52,11 @@ import org.apache.gravitino.meta.DomainEntity;
* <p>A new domain is a draft. A sub-domain can be published only under a published parent, and a
* domain can be unpublished only when none of its sub-domains is published.
*
+ * <p>Every new domain is backed by a tag, either a new tag without values or an existing tag with
+ * an optional value allowed by the tag. A tag has either one binding without a value, or bindings
+ * with values where each value backs at most one domain; a conflicting binding fails with {@link
+ * BackingTagAlreadyBoundException}.
+ *
* <p>The rules are checked against the domains as they are under the row locks of the change, so a
* concurrent change cannot break them. A rule that does not hold fails the operation with an {@link
* IllegalArgumentException}.
@@ -86,29 +95,39 @@ public interface DomainDispatcher {
*/
DomainEntity getDomain(String metalake, String name) throws NoSuchDomainException;
- // TODO: The next PR of #13884 adds the explicit backing tag to createDomain and
- // createSubdomain, which every create request must name, and adds updateBackingTag.
-
/**
- * Creates a top-level domain in draft status.
+ * Creates a top-level domain in draft status, backed by a new or an existing tag.
*
* @param metalake The name of the metalake.
* @param name The name of the domain.
* @param comment The comment of the domain, or null.
* @param properties The properties of the domain, or null.
+ * @param backingTag The backing tag of the domain: the name of the tag to create, or an existing
+ * tag with an optional value.
+ * @param createBackingTag Whether to create the backing tag as a new tag without values.
* @return The created domain.
* @throws NoSuchMetalakeException If the metalake does not exist.
* @throws DomainAlreadyExistsException If a domain with the same name exists.
+ * @throws NoSuchTagException If the existing backing tag to bind does not exist.
+ * @throws TagAlreadyExistsException If the backing tag to create already exists.
+ * @throws BackingTagAlreadyBoundException If the binding conflicts with the backing tag of
+ * another domain.
+ * @throws IllegalArgumentException If the backing tag is null, a value is given for a tag to
+ * create, or the value is not allowed by the existing tag.
*/
DomainEntity createDomain(
String metalake,
String name,
@Nullable String comment,
- @Nullable Map<String, String> properties)
- throws DomainAlreadyExistsException;
+ @Nullable Map<String, String> properties,
+ TagValue backingTag,
+ boolean createBackingTag)
+ throws DomainAlreadyExistsException, NoSuchTagException, TagAlreadyExistsException,
+ BackingTagAlreadyBoundException, IllegalArgumentException;
/**
- * Creates a sub-domain in draft status under a top-level domain.
+ * Creates a sub-domain in draft status under a top-level domain, backed by a new or an existing
+ * tag.
*
* <p>If the metalake is deleted after the initial existence check, creation reports the parent
* domain as not found.
@@ -118,19 +137,31 @@ public interface DomainDispatcher {
* @param name The name of the sub-domain.
* @param comment The comment of the sub-domain, or null.
* @param properties The properties of the sub-domain, or null.
+ * @param backingTag The backing tag of the sub-domain: the name of the tag to create, or an
+ * existing tag with an optional value.
+ * @param createBackingTag Whether to create the backing tag as a new tag without values.
* @return The created sub-domain.
* @throws NoSuchMetalakeException If the metalake does not exist.
* @throws NoSuchDomainException If the parent does not exist.
* @throws DomainAlreadyExistsException If a domain with the same name exists.
- * @throws IllegalArgumentException If the parent is the sub-domain itself or a sub-domain.
+ * @throws NoSuchTagException If the existing backing tag to bind does not exist.
+ * @throws TagAlreadyExistsException If the backing tag to create already exists.
+ * @throws BackingTagAlreadyBoundException If the binding conflicts with the backing tag of
+ * another domain.
+ * @throws IllegalArgumentException If the parent is the sub-domain itself or a sub-domain, the
+ * backing tag is null, a value is given for a tag to create, or the value is not allowed by
+ * the existing tag.
*/
DomainEntity createSubdomain(
String metalake,
String parent,
String name,
@Nullable String comment,
- @Nullable Map<String, String> properties)
- throws NoSuchDomainException, DomainAlreadyExistsException, IllegalArgumentException;
+ @Nullable Map<String, String> properties,
+ TagValue backingTag,
+ boolean createBackingTag)
+ throws NoSuchDomainException, DomainAlreadyExistsException, NoSuchTagException,
+ TagAlreadyExistsException, BackingTagAlreadyBoundException, IllegalArgumentException;
/**
* Alters a domain. Its status and parent are not changed by this method.
@@ -186,6 +217,26 @@ public interface DomainDispatcher {
DomainEntity unpublishDomain(String metalake, String name)
throws NoSuchDomainException, IllegalArgumentException;
+ /**
+ * Replaces the backing tag of a domain, or removes it. Setting the current backing tag changes
+ * nothing. Objects that carry only the old backing tag are no longer members of the domain.
+ *
+ * @param metalake The name of the metalake.
+ * @param name The name of the domain.
+ * @param backingTag The existing tag, with an optional value, that backs the domain, or null to
+ * remove the backing tag.
+ * @return The updated domain.
+ * @throws NoSuchMetalakeException If the metalake does not exist.
+ * @throws NoSuchDomainException If the domain does not exist.
+ * @throws NoSuchTagException If the tag does not exist.
+ * @throws BackingTagAlreadyBoundException If the binding conflicts with the backing tag of
+ * another domain.
+ * @throws IllegalArgumentException If the value is not allowed by the tag.
+ */
+ DomainEntity updateBackingTag(String metalake, String name, @Nullable TagValue backingTag)
+ throws NoSuchDomainException, NoSuchTagException, BackingTagAlreadyBoundException,
+ IllegalArgumentException;
+
/**
* Lists the names of the sub-domains of a domain.
*
diff --git a/core/src/main/java/org/apache/gravitino/domain/DomainManager.java b/core/src/main/java/org/apache/gravitino/domain/DomainManager.java
index 2fc4e0ef7e..220bd8ad90 100644
--- a/core/src/main/java/org/apache/gravitino/domain/DomainManager.java
+++ b/core/src/main/java/org/apache/gravitino/domain/DomainManager.java
@@ -29,6 +29,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.gravitino.Audit;
@@ -37,16 +39,22 @@ import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.SupportsDomainOperations;
import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchDomainException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NonEmptyDomainException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.IdGenerator;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.tag.TagValueConstraint;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -55,8 +63,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * The domain manager. It keeps the domain hierarchy one level deep and the status of each domain
- * consistent with its parent and sub-domains (see {@link DomainDispatcher}).
+ * The domain manager. It keeps the domain hierarchy one level deep, the status of each domain
+ * consistent with its parent and sub-domains, and the backing tag bindings free of conflicts (see
+ * {@link DomainDispatcher}).
*
* <p>The rules that involve other domains are checked by the entity store's domain operations,
* against the domains as they are under the row locks of the change, so that a concurrent change
@@ -115,9 +124,12 @@ public class DomainManager implements DomainDispatcher {
String metalake,
String name,
@Nullable String comment,
- @Nullable Map<String, String> properties)
- throws DomainAlreadyExistsException {
- return insertDomain(metalake, null, name, comment, properties);
+ @Nullable Map<String, String> properties,
+ TagValue backingTag,
+ boolean createBackingTag)
+ throws DomainAlreadyExistsException, NoSuchTagException, TagAlreadyExistsException,
+ BackingTagAlreadyBoundException, IllegalArgumentException {
+ return insertDomain(metalake, null, name, comment, properties, backingTag, createBackingTag);
}
@Override
@@ -126,10 +138,13 @@ public class DomainManager implements DomainDispatcher {
String parent,
String name,
@Nullable String comment,
- @Nullable Map<String, String> properties)
- throws NoSuchDomainException, DomainAlreadyExistsException, IllegalArgumentException {
+ @Nullable Map<String, String> properties,
+ TagValue backingTag,
+ boolean createBackingTag)
+ throws NoSuchDomainException, DomainAlreadyExistsException, NoSuchTagException,
+ TagAlreadyExistsException, BackingTagAlreadyBoundException, IllegalArgumentException {
checkParentName(name, parent);
- return insertDomain(metalake, parent, name, comment, properties);
+ return insertDomain(metalake, parent, name, comment, properties, backingTag, createBackingTag);
}
@Override
@@ -202,6 +217,27 @@ public class DomainManager implements DomainDispatcher {
return updateStatus(metalake, name, Domain.Status.DRAFT);
}
+ @Override
+ public DomainEntity updateBackingTag(String metalake, String name, @Nullable TagValue backingTag)
+ throws NoSuchDomainException, NoSuchTagException, BackingTagAlreadyBoundException,
+ IllegalArgumentException {
+ checkMetalake(NameIdentifierUtil.ofMetalake(metalake), entityStore);
+ try {
+ return domainOperations()
+ .updateDomainBackingTagAndGet(
+ NameIdentifierUtil.ofDomain(metalake, name),
+ backingTag,
+ newAuditInfo(),
+ state -> checkBackingTagUpdate(state, backingTag));
+ } catch (NoSuchEntityException e) {
+ throw noSuchDomain(e, metalake, name);
+ } catch (IOException ioe) {
+ LOG.error(
+ "Failed to update the backing tag of domain {} under metalake {}", name, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
+ }
+
@Override
public DomainEntity[] listSubdomainInfos(String metalake, String name)
throws NoSuchDomainException {
@@ -260,15 +296,39 @@ public class DomainManager implements DomainDispatcher {
}
/**
- * Checks a new sub-domain against its locked parent: the parent must be top-level, so that a
- * sub-domain has no sub-domains. A new domain has no sub-domains of its own and is a draft, so
- * the other rules of an attach hold for it.
+ * Checks a new domain against the locked state: the parent of a new sub-domain must be top-level,
+ * so that a sub-domain has no sub-domains, and the backing tag must allow the value and not
+ * conflict with the bindings of other domains. A new domain has no sub-domains of its own and is
+ * a draft, so the other rules of an attach hold for it.
*
* @param state The locked state of the insert.
*/
@VisibleForTesting
static void checkNewDomain(LockedDomainState state) {
- state.parent().ifPresent(parent -> checkParentIsTopLevel(state.domain(), parent));
+ DomainEntity domain = state.domain();
+ state.parent().ifPresent(parent -> checkParentIsTopLevel(domain, parent));
+ checkBinding(domain, Optional.ofNullable(domain.backingTagValue()), state);
+ }
+
+ /**
+ * Checks a change of the backing tag against the locked state. Removing the backing tag, or
+ * setting the current one, changes no binding and is not checked.
+ *
+ * @param state The locked state of the change.
+ * @param backingTag The new backing tag, or null to remove it.
+ */
+ @VisibleForTesting
+ static void checkBackingTagUpdate(LockedDomainState state, @Nullable TagValue backingTag) {
+ if (backingTag == null) {
+ return;
+ }
+ DomainEntity domain = state.domain();
+ TagEntity tag = lockedBackingTag(state);
+ if (Objects.equals(domain.backingTagId(), tag.id())
+ && Objects.equals(domain.backingTagValue(), backingTag.value().orElse(null))) {
+ return;
+ }
+ checkBinding(domain, backingTag.value(), state);
}
/**
@@ -357,10 +417,17 @@ public class DomainManager implements DomainDispatcher {
@Nullable String parent,
String name,
@Nullable String comment,
- @Nullable Map<String, String> properties) {
+ @Nullable Map<String, String> properties,
+ TagValue backingTag,
+ boolean createBackingTag) {
+ Preconditions.checkArgument(
+ backingTag != null, "The backing tag of domain %s must not be null", name);
+ Preconditions.checkArgument(
+ !createBackingTag || !backingTag.value().isPresent(),
+ "The new backing tag %s of domain %s cannot have a value",
+ backingTag.name(),
+ name);
checkMetalake(NameIdentifierUtil.ofMetalake(metalake), entityStore);
- // TODO: The next PR of #13884 sets the backing tag here: it creates a new tag or binds an
- // existing (tag, value), in the same transaction as the domain, under the binding rules.
DomainEntity domain =
DomainEntity.builder()
.withId(idGenerator.nextId())
@@ -378,19 +445,29 @@ public class DomainManager implements DomainDispatcher {
.build();
try {
- // Return the parent's name as stored, read under its lock, rather than the requested one:
- // on MySQL, a name with trailing spaces finds the same parent row.
- String[] storedParent = new String[] {parent};
- domainOperations()
- .insertDomain(
- domain,
- state -> {
- checkNewDomain(state);
- state.parent().ifPresent(lockedParent -> storedParent[0] = lockedParent.name());
- });
- return Objects.equals(storedParent[0], parent)
- ? domain
- : domain.toBuilder().withParent(storedParent[0]).build();
+ // Return the domain as the check saw it, with its backing tag set, and with the parent's
+ // name as stored, read under its lock, rather than the requested one: on MySQL, a name with
+ // trailing spaces finds the same parent row.
+ DomainEntity[] inserted = new DomainEntity[1];
+ Consumer<LockedDomainState> check =
+ state -> {
+ checkNewDomain(state);
+ DomainEntity checked = state.domain();
+ inserted[0] =
+ state
+ .parent()
+ .map(
+ lockedParent -> checked.toBuilder().withParent(lockedParent.name()).build())
+ .orElse(checked);
+ };
+ if (createBackingTag) {
+ domainOperations()
+ .insertDomainWithNewBackingTag(
+ domain, newBackingTag(metalake, backingTag.name()), check);
+ } else {
+ domainOperations().insertDomainWithBackingTag(domain, backingTag, check);
+ }
+ return inserted[0];
} catch (EntityAlreadyExistsException e) {
throw new DomainAlreadyExistsException(
e, "Domain %s under metalake %s already exists", name, metalake);
@@ -436,6 +513,22 @@ public class DomainManager implements DomainDispatcher {
}
}
+ // A new backing tag allows no values, so it backs one domain only.
+ private TagEntity newBackingTag(String metalake, String tagName) {
+ return TagEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(tagName)
+ .withNamespace(NamespaceUtil.ofTag(metalake))
+ .withProperties(Collections.emptyMap())
+ .withAllowedValues(TagValueConstraint.noValue().allowedValues())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
+ }
+
private SupportsDomainOperations domainOperations() {
return entityStore.domainOperations();
}
@@ -496,6 +589,44 @@ public class DomainManager implements DomainDispatcher {
!Objects.equals(name, parent), "Domain %s cannot be its own parent", name);
}
+ // Checks that the locked backing tag allows the value and that no other domain has a binding of
+ // the tag that conflicts with it: a tag has either one binding without a value, or bindings with
+ // values where each value backs at most one domain.
+ private static void checkBinding(
+ DomainEntity domain, Optional<String> value, LockedDomainState state) {
+ TagEntity tag = lockedBackingTag(state);
+ tag.validateAllowedValue(
+ value.map(v -> TagValue.of(tag.name(), v)).orElseGet(() -> TagValue.noValue(tag.name())));
+
+ for (DomainEntity bound : state.backingTagBindings()) {
+ if (Objects.equals(bound.id(), domain.id())) {
+ continue;
+ }
+ if (bound.backingTagValue() == null) {
+ throw new BackingTagAlreadyBoundException(
+ "Tag %s already backs domain %s without a value, so it cannot back domain %s",
+ tag.name(), bound.name(), domain.name());
+ }
+ if (!value.isPresent()) {
+ throw new BackingTagAlreadyBoundException(
+ "Tag %s already backs domain %s with value %s, so it cannot back domain %s without a"
+ + " value",
+ tag.name(), bound.name(), bound.backingTagValue(), domain.name());
+ }
+ if (value.get().equals(bound.backingTagValue())) {
+ throw new BackingTagAlreadyBoundException(
+ "Tag %s with value %s already backs domain %s, so it cannot back domain %s",
+ tag.name(), value.get(), bound.name(), domain.name());
+ }
+ }
+ }
+
+ private static TagEntity lockedBackingTag(LockedDomainState state) {
+ return state
+ .backingTag()
+ .orElseThrow(() -> new IllegalStateException("A backing tag binding needs a tag"));
+ }
+
private static void checkParentIsTopLevel(DomainEntity domain, DomainEntity parent) {
Preconditions.checkArgument(
!parent.parent().isPresent(),
diff --git a/core/src/main/java/org/apache/gravitino/meta/TagEntity.java b/core/src/main/java/org/apache/gravitino/meta/TagEntity.java
index 7343875ec8..2dacee2ac7 100644
--- a/core/src/main/java/org/apache/gravitino/meta/TagEntity.java
+++ b/core/src/main/java/org/apache/gravitino/meta/TagEntity.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.meta;
+import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.util.Arrays;
import java.util.Collections;
@@ -35,6 +36,7 @@ import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.tag.Tag;
import org.apache.gravitino.tag.TagAssignment;
+import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.tag.TagValueConstraint;
public class TagEntity implements Tag, Entity, Auditable, HasIdentifier {
@@ -134,6 +136,55 @@ public class TagEntity implements Tag, Entity, Auditable, HasIdentifier {
return Optional.ofNullable(inherited);
}
+ /**
+ * Checks that this tag can be assigned with the given value. See {@link
+ * #validateAllowedValue(String[], TagValue)}.
+ *
+ * @param tagValue The tag value to assign.
+ * @throws IllegalArgumentException If this tag does not allow the value.
+ */
+ public void validateAllowedValue(TagValue tagValue) {
+ validateAllowedValue(allowedValues, tagValue);
+ }
+
+ /**
+ * Checks that a tag with the given allowed values can be assigned with a value: a tag with
+ * allowed values only with one of them, a tag that allows no values only without a value, and a
+ * tag without a constraint with or without any value.
+ *
+ * @param allowedValues The allowed values of the tag: null if the tag has no constraint, empty if
+ * it allows no values.
+ * @param tagValue The tag value to assign.
+ * @throws IllegalArgumentException If the tag does not allow the value.
+ */
+ public static void validateAllowedValue(@Nullable String[] allowedValues, TagValue tagValue) {
+ if (allowedValues == null) {
+ return;
+ }
+
+ if (!tagValue.value().isPresent()) {
+ Preconditions.checkArgument(
+ allowedValues.length == 0,
+ "Tag %s requires assignment values from allowed values %s",
+ tagValue.name(),
+ Arrays.toString(allowedValues));
+ return;
+ }
+
+ Preconditions.checkArgument(
+ allowedValues.length > 0, "Tag %s does not allow assignment values", tagValue.name());
+ String value = tagValue.value().get();
+ for (String allowedValue : allowedValues) {
+ if (value.equals(allowedValue)) {
+ return;
+ }
+ }
+ throw new IllegalArgumentException(
+ String.format(
+ "Tag %s value %s is not in allowed values %s",
+ tagValue.name(), value, Arrays.toString(allowedValues)));
+ }
+
@Override
public Audit auditInfo() {
return auditInfo;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index 39e7278ef4..3137ee6f33 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -34,6 +34,7 @@ import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
@@ -772,9 +773,28 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
}
@Override
- public void insertDomain(DomainEntity domain, Consumer<LockedDomainState> check)
+ public void insertDomainWithBackingTag(
+ DomainEntity domain, TagValue backingTag, Consumer<LockedDomainState> check)
throws IOException {
- DomainMetaService.getInstance().insertDomain(domain, check);
+ DomainMetaService.getInstance().insertDomainWithBackingTag(domain, backingTag, check);
+ }
+
+ @Override
+ public void insertDomainWithNewBackingTag(
+ DomainEntity domain, TagEntity backingTag, Consumer<LockedDomainState> check)
+ throws IOException {
+ DomainMetaService.getInstance().insertDomainWithNewBackingTag(domain, backingTag, check);
+ }
+
+ @Override
+ public DomainEntity updateDomainBackingTagAndGet(
+ NameIdentifier ident,
+ @Nullable TagValue backingTag,
+ AuditInfo auditInfo,
+ Consumer<LockedDomainState> check)
+ throws IOException {
+ return DomainMetaService.getInstance()
+ .updateDomainBackingTagAndGet(ident, backingTag, auditInfo, check);
}
@Override
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
index 64a35dc1e7..62a1b41a41 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
@@ -63,11 +63,13 @@ import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.EntityChangeLogMetricsSource;
import org.apache.gravitino.semantic.SemanticModelMetric;
import org.apache.gravitino.storage.relational.service.EntityIdService;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.utils.Executable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -453,16 +455,45 @@ public class RelationalEntityStore
}
@Override
- public void insertDomain(DomainEntity domain, Consumer<LockedDomainState> check)
+ public void insertDomainWithBackingTag(
+ DomainEntity domain, TagValue backingTag, Consumer<LockedDomainState> check)
throws IOException {
try {
- backend.insertDomain(domain, check);
+ backend.insertDomainWithBackingTag(domain, backingTag, check);
} catch (RuntimeException re) {
throw ExceptionUtils.lockWaitTimeoutAsConflict(
re, Entity.EntityType.DOMAIN, domain.nameIdentifier());
}
}
+ @Override
+ public void insertDomainWithNewBackingTag(
+ DomainEntity domain, TagEntity backingTag, Consumer<LockedDomainState> check)
+ throws IOException {
+ try {
+ backend.insertDomainWithNewBackingTag(domain, backingTag, check);
+ } catch (RuntimeException re) {
+ throw ExceptionUtils.lockWaitTimeoutAsConflict(
+ re, Entity.EntityType.DOMAIN, domain.nameIdentifier());
+ }
+ // Tags are cached; the new tag must not be shadowed by an entry cached for its name.
+ invalidateCache(backingTag.nameIdentifier(), Entity.EntityType.TAG);
+ }
+
+ @Override
+ public DomainEntity updateDomainBackingTagAndGet(
+ NameIdentifier ident,
+ @Nullable TagValue backingTag,
+ AuditInfo auditInfo,
+ Consumer<LockedDomainState> check)
+ throws IOException {
+ try {
+ return backend.updateDomainBackingTagAndGet(ident, backingTag, auditInfo, check);
+ } catch (RuntimeException re) {
+ throw ExceptionUtils.lockWaitTimeoutAsConflict(re, Entity.EntityType.DOMAIN, ident);
+ }
+ }
+
@Override
public DomainEntity setDomainParentAndGet(
NameIdentifier ident,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java
index daf3774f7f..59e86fdb39 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java
@@ -183,6 +183,17 @@ public interface DomainMetaMapper {
List<DomainPO> listDomainPOsByParentIdentifier(
@Param("metalakeName") String metalakeName, @Param("parentName") String parentName);
+ /**
+ * Lists the active domains backed by a tag, with or without a value.
+ *
+ * @param metalakeId The metalake ID.
+ * @param backingTagId The ID of the backing tag.
+ * @return The active domains backed by the tag.
+ */
+ @SelectProvider(type = DomainMetaSQLProviderFactory.class, method = "listDomainPOsByBackingTagId")
+ List<DomainPO> listDomainPOsByBackingTagId(
+ @Param("metalakeId") Long metalakeId, @Param("backingTagId") Long backingTagId);
+
/**
* Inserts a domain.
*
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java
index f9c9eb49cd..023a2ed0b0 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java
@@ -119,6 +119,12 @@ public class DomainMetaSQLProviderFactory {
return getProvider().listDomainPOsByParentIdentifier(metalakeName, parentName);
}
+ /** Delegates {@link DomainMetaBaseSQLProvider#listDomainPOsByBackingTagId}. */
+ public static String listDomainPOsByBackingTagId(
+ @Param("metalakeId") Long metalakeId, @Param("backingTagId") Long backingTagId) {
+ return getProvider().listDomainPOsByBackingTagId(metalakeId, backingTagId);
+ }
+
/** Delegates {@link DomainMetaBaseSQLProvider#insertDomainMeta}. */
public static String insertDomainMeta(@Param("domainMeta") DomainPO domainPO) {
return getProvider().insertDomainMeta(domainPO);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java
index 9dbf1358dc..bb9ce39d2a 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java
@@ -249,6 +249,24 @@ public class DomainMetaBaseSQLProvider {
+ " AND lp.deleted_at = 0";
}
+ /**
+ * Returns SQL that lists the active domains backed by a tag, using the index on {@code
+ * (metalake_id, backing_tag_id, backing_tag_value, deleted_at)}.
+ *
+ * @param metalakeId The metalake ID.
+ * @param backingTagId The ID of the backing tag.
+ * @return The SQL.
+ */
+ public String listDomainPOsByBackingTagId(
+ @Param("metalakeId") Long metalakeId, @Param("backingTagId") Long backingTagId) {
+ return "SELECT "
+ + DOMAIN_COLUMNS
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm WHERE dm.metalake_id = #{metalakeId} AND dm.backing_tag_id = #{backingTagId}"
+ + " AND dm.deleted_at = 0";
+ }
+
/**
* Returns SQL that inserts a domain.
*
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java
index a9acff58ee..c0e7263e41 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java
@@ -29,6 +29,8 @@ import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.tuple.Pair;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.HasIdentifier;
@@ -37,9 +39,12 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
import org.apache.gravitino.storage.relational.mapper.DomainRelMapper;
@@ -50,6 +55,8 @@ import org.apache.gravitino.storage.relational.po.DomainPO;
import org.apache.gravitino.storage.relational.po.MetalakePO;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.NamespaceUtil;
/** The service that stores domains in the {@code domain_meta} table. */
public class DomainMetaService {
@@ -128,9 +135,10 @@ public class DomainMetaService {
/**
* Inserts a top-level domain. A sub-domain, whose parent must be locked and checked, is inserted
- * with {@link #insertDomain(DomainEntity, Consumer)}. Replacing a domain keeps its status and its
- * parent: the status is changed only under the locks its rules need, by {@link
- * DomainRelService#updateDomainStatusAndGet}.
+ * with {@link #insertDomainWithBackingTag} or {@link #insertDomainWithNewBackingTag}. Replacing a
+ * domain keeps its status, its parent and its backing tag, which are changed only under the locks
+ * their rules need: the status by {@link DomainRelService#updateDomainStatusAndGet}, the backing
+ * tag by {@link #updateDomainBackingTagAndGet}.
*
* @param domainEntity The domain to insert.
* @param overwritten Whether to replace an active domain with the same name or ID.
@@ -138,7 +146,7 @@ public class DomainMetaService {
* @throws EntityAlreadyExistsException If a domain with the same name exists and {@code
* overwritten} is false.
* @throws IllegalArgumentException If the domain has a parent, or replaces a domain with another
- * status.
+ * status or another backing tag.
*/
@Monitored(
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
@@ -177,72 +185,182 @@ public class DomainMetaService {
}
/**
- * Inserts a new domain after a check of the locked state. If the domain has a parent, it is
- * inserted as a sub-domain of that parent, together with its parent edge, in one transaction.
+ * Inserts a new domain backed by an existing tag, after a check of the locked state. If the
+ * domain has a parent, it is inserted as a sub-domain of that parent, together with its parent
+ * edge, in one transaction.
*
- * <p>The metalake row is locked shared, then the parent row, if any, is locked shared, so the
- * parent cannot be attached elsewhere, deleted or have its status changed until the domain is
- * committed. The check gets the new domain, the parent with its own parent set, and no
- * sub-domains.
+ * <p>The metalake row is locked shared, then the parent row, if any, shared, so the parent cannot
+ * be attached elsewhere, deleted or have its status changed until the domain is committed. Then
+ * the tag is resolved by name and locked exclusively, so it cannot be deleted or bound by another
+ * domain meanwhile; every binding of a tag holds this lock. The domain is written next, so a
+ * missing parent or tag is reported before a duplicate domain name, and then the check runs. The
+ * check gets the new domain with its backing tag set, the parent with its own parent set, no
+ * sub-domains, the tag, and the domains the tag already backs.
*
* <p>This operation must own its transaction so a failed check rolls back the inserted domain. It
* cannot run inside another transaction.
*
* @param domainEntity The domain to insert; its parent, if set, is the parent to insert it under.
+ * @param backingTag The existing tag, with an optional value, that backs the domain.
* @param check The check of the locked state; nothing is inserted if it throws.
* @throws IOException If the domain cannot be stored.
* @throws EntityAlreadyExistsException If a domain with the same name exists.
* @throws NoSuchEntityException If the metalake or the parent does not exist.
* @throws IllegalStateException If it is called inside a transaction.
+ * @throws NoSuchTagException If the tag does not exist.
*/
@Monitored(
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
- baseMetricName = "insertDomainWithCheck")
- public void insertDomain(DomainEntity domainEntity, Consumer<LockedDomainState> check)
+ baseMetricName = "insertDomainWithBackingTag")
+ public void insertDomainWithBackingTag(
+ DomainEntity domainEntity, TagValue backingTag, Consumer<LockedDomainState> check)
throws IOException {
- Preconditions.checkState(
- !SessionUtils.isInTransaction(),
- "The domain %s cannot be inserted with a check inside another transaction",
- domainEntity.nameIdentifier());
- Namespace ns = domainEntity.namespace();
- String metalakeName = ns.level(0);
+ insertBackedDomain(
+ domainEntity,
+ backingTag.value().orElse(null),
+ metalakePO -> {
+ Namespace tagNamespace = NamespaceUtil.ofTag(metalakePO.getMetalakeName());
+ TagEntity tag =
+ TagMetaService.getInstance()
+ .lockAndGetTagForDomainBinding(
+ metalakePO.getMetalakeId(), tagNamespace, backingTag.name());
+ return Pair.of(
+ tag,
+ listDomainsByBackingTagId(
+ metalakePO.getMetalakeId(), tag.id(), domainEntity.namespace()));
+ },
+ check,
+ null);
+ }
- try {
- MetalakePO metalakePO = getMetalakePO(metalakeName);
- DomainPO domainPO = DomainPO.initializeDomainPO(domainEntity, metalakePO.getMetalakeId());
+ /**
+ * Inserts a new domain together with a new tag that backs it without a value, after a check of
+ * the locked state. If the domain has a parent, it is inserted as a sub-domain of that parent,
+ * together with its parent edge. The tag, the domain and the edge are written in one transaction.
+ *
+ * <p>The metalake row is locked shared, then the parent row, if any, shared. The new tag has no
+ * row to lock; the unique key on the tag name fails the insert if a tag with the same name exists
+ * or is created at the same time. The check gets the new domain with its backing tag set, the
+ * parent with its own parent set, no sub-domains, the new tag, and no other domains.
+ *
+ * @param domainEntity The domain to insert; its parent, if set, is the parent to insert it under.
+ * @param backingTag The new tag that backs the domain.
+ * @param check The check of the locked state; nothing is inserted if it throws.
+ * @throws IOException If the domain cannot be stored.
+ * @throws EntityAlreadyExistsException If a domain with the same name exists.
+ * @throws NoSuchEntityException If the metalake or the parent does not exist.
+ * @throws TagAlreadyExistsException If a tag with the same name exists.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "insertDomainWithNewBackingTag")
+ public void insertDomainWithNewBackingTag(
+ DomainEntity domainEntity, TagEntity backingTag, Consumer<LockedDomainState> check)
+ throws IOException {
+ insertBackedDomain(
+ domainEntity,
+ null,
+ metalakePO -> Pair.of(backingTag, Collections.emptyList()),
+ check,
+ backingTag);
+ }
+ /**
+ * Sets or removes the backing tag of a domain, after a check of the locked state. Setting the
+ * current backing tag writes nothing.
+ *
+ * <p>The metalake row is locked shared, then the domain row exclusively, then the new tag, if
+ * any, exclusively, so the tag cannot be deleted or bound by another domain until the change
+ * commits. The check gets the domain with its current parent and backing tag set, no parent and
+ * no sub-domains, the new tag, and the domains the tag already backs, which include this domain
+ * if the tag already backs it.
+ *
+ * @param identifier The identifier of the domain.
+ * @param backingTag The existing tag, with an optional value, that backs the domain, or null to
+ * remove the backing tag.
+ * @param auditInfo The audit info of the change; the domain keeps its creator and takes its last
+ * modifier.
+ * @param check The check of the locked state; nothing is written if it throws.
+ * @return The domain after the change.
+ * @throws IOException If the domain cannot be stored.
+ * @throws NoSuchEntityException If the domain does not exist.
+ * @throws NoSuchTagException If the tag does not exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "updateDomainBackingTagAndGet")
+ public DomainEntity updateDomainBackingTagAndGet(
+ NameIdentifier identifier,
+ @Nullable TagValue backingTag,
+ AuditInfo auditInfo,
+ Consumer<LockedDomainState> check)
+ throws IOException {
+ Namespace namespace = identifier.namespace();
+ String metalakeName = namespace.level(0);
+ DomainEntity[] updated = new DomainEntity[1];
+ try {
+ DomainPO observedPO = getDomainPOByMetalakeAndName(metalakeName, identifier.name());
SessionUtils.doMultipleWithCommit(
- () ->
- lockMetalakeForDomainWrite(metalakePO.getMetalakeName(), metalakePO.getMetalakeId()),
() -> {
- DomainEntity parent =
- domainEntity
- .parent()
- .map(
- parentName ->
- DomainRelService.getInstance()
- .lockAndGetParentOfNewSubDomain(NameIdentifier.of(ns, parentName)))
- .orElse(null);
- // The domain is written before the check, so that a duplicate name fails as such.
- insertNewDomainWithoutCommit(domainPO);
- check.accept(new LockedDomainState(domainEntity, parent, Collections.emptyList()));
- if (parent != null) {
- DomainRelService.getInstance()
- .insertDomainRelOfNewSubDomain(
- metalakePO.getMetalakeId(),
- parent.id(),
- domainPO.domainId(),
- AuditInfo.builder()
- .withCreator(domainEntity.auditInfo().creator())
- .withCreateTime(domainEntity.auditInfo().createTime())
- .build());
+ DomainPO lockedPO =
+ DomainRelService.getInstance().lockAndGetDomainForChange(identifier, observedPO);
+ DomainEntity domain =
+ DomainRelService.getInstance().toEntityWithParent(lockedPO, namespace);
+ TagEntity tag = null;
+ List<DomainEntity> bindings = Collections.emptyList();
+ if (backingTag != null) {
+ tag =
+ TagMetaService.getInstance()
+ .lockAndGetTagForDomainBinding(
+ lockedPO.metalakeId(),
+ NamespaceUtil.ofTag(metalakeName),
+ backingTag.name());
+ bindings = listDomainsByBackingTagId(lockedPO.metalakeId(), tag.id(), namespace);
}
+ check.accept(
+ new LockedDomainState(domain, null, Collections.emptyList(), tag, bindings));
+
+ Long newTagId = tag == null ? null : tag.id();
+ String newValue = backingTag == null ? null : backingTag.value().orElse(null);
+ if (Objects.equals(lockedPO.backingTagId(), newTagId)
+ && Objects.equals(lockedPO.backingTagValue(), newValue)) {
+ // The locked domain row does not include the backing tag name.
+ updated[0] =
+ tag == null ? domain : domain.toBuilder().withBackingTagName(tag.name()).build();
+ return;
+ }
+
+ DomainEntity newDomain =
+ domain.toBuilder()
+ .withBackingTagId(newTagId)
+ .withBackingTagName(tag == null ? null : tag.name())
+ .withBackingTagValue(newValue)
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(domain.auditInfo().creator())
+ .withCreateTime(domain.auditInfo().createTime())
+ .withLastModifier(auditInfo.lastModifier())
+ .withLastModifiedTime(auditInfo.lastModifiedTime())
+ .build())
+ .build();
+ DomainPO newPO = DomainPO.updateDomainPO(lockedPO, newDomain);
+ OccWriteSupport.updateWithVersion(
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class, mapper -> mapper.updateDomainMeta(newPO, lockedPO)),
+ () -> ExceptionUtils.concurrentModification(Entity.EntityType.DOMAIN, identifier));
+ updated[0] =
+ fromDomainPOWithParent(
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaById(lockedPO.domainId())),
+ namespace);
});
} catch (RuntimeException e) {
- ExceptionUtils.checkSQLException(
- e, Entity.EntityType.DOMAIN, domainEntity.nameIdentifier().toString());
+ ExceptionUtils.checkSQLException(e, Entity.EntityType.DOMAIN, identifier.toString());
throw e;
}
+ return updated[0];
}
/**
@@ -258,10 +376,11 @@ public class DomainMetaService {
* created with the same name in between, this call reports the domain as missing instead of
* changing the new domain; a later call with the name acts on the new domain.
*
- * <p>The returned domain is read back in the same transaction, so its backing tag name comes from
- * the tag it is now bound to rather than from the updater's entity. The parent and the status
- * cannot be changed by an update, an updater that changes either is rejected; {@link
- * DomainRelService} changes them under the locks their rules need.
+ * <p>The returned domain is read back in the same transaction, so its backing tag name is the
+ * tag's current name rather than the one the updater's entity carries. The parent, the status and
+ * the backing tag cannot be changed by an update, an updater that changes any of them is
+ * rejected; {@link DomainRelService} and {@link #updateDomainBackingTagAndGet} change them under
+ * the locks their rules need.
*
* @param identifier The domain identifier.
* @param updater The function that returns the updated domain.
@@ -308,6 +427,11 @@ public class DomainMetaService {
"The status of domain %s cannot be changed by an update, use"
+ " DomainRelService#updateDomainStatusAndGet",
identifier);
+ Preconditions.checkArgument(
+ sameBackingTag(oldDomainEntity, updatedDomainEntity),
+ "The backing tag of domain %s cannot be changed by an update, use"
+ + " updateDomainBackingTagAndGet",
+ identifier);
DomainPO newDomainPO = DomainPO.updateDomainPO(lockedDomainPO, updatedDomainEntity);
updateDomainWithVersion(identifier, mapper, lockedDomainPO, newDomainPO);
@@ -448,6 +572,100 @@ public class DomainMetaService {
return true;
}
+ /**
+ * Inserts a new domain, and a new backing tag if one is given, in one transaction: locks the
+ * metalake shared, then the parent, if any, shared, then gets the backing tag and its bindings
+ * from {@code backingTagLocker}, writes the domain and the new tag, runs the check, and writes
+ * the parent edge.
+ */
+ private void insertBackedDomain(
+ DomainEntity domainEntity,
+ @Nullable String backingTagValue,
+ Function<MetalakePO, Pair<TagEntity, List<DomainEntity>>> backingTagLocker,
+ Consumer<LockedDomainState> check,
+ @Nullable TagEntity newBackingTag)
+ throws IOException {
+ Preconditions.checkState(
+ !SessionUtils.isInTransaction(),
+ "The domain %s cannot be inserted with a check inside another transaction",
+ domainEntity.nameIdentifier());
+ Namespace ns = domainEntity.namespace();
+ String metalakeName = ns.level(0);
+
+ try {
+ MetalakePO metalakePO = getMetalakePO(metalakeName);
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ lockMetalakeForDomainWrite(metalakePO.getMetalakeName(), metalakePO.getMetalakeId()),
+ () -> {
+ DomainEntity parent =
+ domainEntity
+ .parent()
+ .map(
+ parentName ->
+ DomainRelService.getInstance()
+ .lockAndGetParentOfNewSubDomain(NameIdentifier.of(ns, parentName)))
+ .orElse(null);
+ Pair<TagEntity, List<DomainEntity>> backingTag = backingTagLocker.apply(metalakePO);
+ DomainEntity domain =
+ domainEntity.toBuilder()
+ .withBackingTagId(backingTag.getLeft().id())
+ .withBackingTagName(backingTag.getLeft().name())
+ .withBackingTagValue(backingTagValue)
+ .build();
+ DomainPO domainPO = DomainPO.initializeDomainPO(domain, metalakePO.getMetalakeId());
+ // The domain is written before the check, so that a duplicate name fails as such.
+ insertNewDomainWithoutCommit(domainPO);
+ if (newBackingTag != null) {
+ TagMetaService.getInstance()
+ .insertTagOfNewDomain(newBackingTag, metalakePO.getMetalakeId());
+ }
+ check.accept(
+ new LockedDomainState(
+ domain,
+ parent,
+ Collections.emptyList(),
+ backingTag.getLeft(),
+ backingTag.getRight()));
+ if (parent != null) {
+ DomainRelService.getInstance()
+ .insertDomainRelOfNewSubDomain(
+ metalakePO.getMetalakeId(),
+ parent.id(),
+ domainPO.domainId(),
+ AuditInfo.builder()
+ .withCreator(domain.auditInfo().creator())
+ .withCreateTime(domain.auditInfo().createTime())
+ .build());
+ }
+ });
+ } catch (TagAlreadyExistsException e) {
+ // Its cause is the duplicate key of the tag, which must not be reported as the domain's.
+ throw e;
+ } catch (RuntimeException e) {
+ ExceptionUtils.checkSQLException(
+ e, Entity.EntityType.DOMAIN, domainEntity.nameIdentifier().toString());
+ throw e;
+ }
+ }
+
+ // Whether two domains are bound to the same backing tag ID and value.
+ private static boolean sameBackingTag(DomainEntity domain, DomainEntity other) {
+ return Objects.equals(domain.backingTagId(), other.backingTagId())
+ && Objects.equals(domain.backingTagValue(), other.backingTagValue());
+ }
+
+ // Lists the domains backed by a tag, read in the caller's transaction under the lock on the tag.
+ private List<DomainEntity> listDomainsByBackingTagId(
+ Long metalakeId, Long backingTagId, Namespace namespace) {
+ return SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.listDomainPOsByBackingTagId(metalakeId, backingTagId))
+ .stream()
+ .map(po -> DomainPO.fromDomainPO(po, namespace))
+ .collect(Collectors.toList());
+ }
+
/**
* Holds the parent metalake row for the rest of the transaction, so a domain cannot be created,
* altered or deleted while the metalake is being dropped. The lock is shared, so domains under
@@ -496,6 +714,11 @@ public class DomainMetaService {
Objects.equals(existingDomainPO.status(), domainEntity.status().name()),
"The status of domain %s cannot be changed by replacing it",
domainEntity.nameIdentifier());
+ Preconditions.checkArgument(
+ Objects.equals(existingDomainPO.backingTagId(), domainEntity.backingTagId())
+ && Objects.equals(existingDomainPO.backingTagValue(), domainEntity.backingTagValue()),
+ "The backing tag of domain %s cannot be changed by replacing it",
+ domainEntity.nameIdentifier());
DomainPO replacementDomainPO = DomainPO.updateDomainPO(existingDomainPO, domainEntity);
NameIdentifier observedIdentifier =
NameIdentifier.of(domainEntity.namespace(), existingDomainPO.domainName());
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainRelService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainRelService.java
index bc0fdc0cca..71fc6adb32 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainRelService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainRelService.java
@@ -493,6 +493,26 @@ public class DomainRelService {
return toEntityWithParent(lockedParentPO, parentIdent.namespace());
}
+ /**
+ * Locks the metalake shared and a domain exclusively, in the caller's transaction, for a change
+ * of the domain row that involves no other domain, and returns the domain row as it is under the
+ * lock.
+ *
+ * @param identifier The identifier of the domain.
+ * @param observedPO The domain row the caller read before locking.
+ * @return The locked domain row.
+ * @throws NoSuchEntityException If the domain was deleted or renamed after it was read.
+ */
+ DomainPO lockAndGetDomainForChange(NameIdentifier identifier, DomainPO observedPO) {
+ return lockMetalakeAndDomains(identifier, observedPO, null).getLeft();
+ }
+
+ // The parent name is read under the lock on the domain, which every writer of its edge holds.
+ DomainEntity toEntityWithParent(DomainPO domainPO, Namespace namespace) {
+ return DomainPO.fromDomainPO(
+ domainPO, namespace, getParentDomainName(domainPO.domainId()).orElse(null));
+ }
+
/**
* Inserts the parent edge of a new sub-domain, in the caller's transaction. The caller holds the
* shared lock on the parent from {@link #lockAndGetParentOfNewSubDomain(NameIdentifier)}.
@@ -582,12 +602,6 @@ public class DomainRelService {
DomainMetaMapper.class, mapper -> mapper.selectDomainMetaByIdForShare(domainId));
}
- // The parent name is read under the lock on the domain, which every writer of its edge holds.
- private DomainEntity toEntityWithParent(DomainPO domainPO, Namespace namespace) {
- return DomainPO.fromDomainPO(
- domainPO, namespace, getParentDomainName(domainPO.domainId()).orElse(null));
- }
-
private List<DomainEntity> listSubDomainsOf(DomainPO domainPO, Namespace namespace) {
return SessionUtils.getWithoutCommit(
DomainMetaMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
index 3e02b3df50..e1eba45cc6 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TagMetaService.java
@@ -51,6 +51,7 @@ import org.apache.gravitino.RelationalEntity;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
@@ -795,33 +796,11 @@ public class TagMetaService {
}
static void validateAllowedValue(TagPO tagPO, TagValue tagValue) throws JsonProcessingException {
- if (tagPO.getAllowedValues() == null) {
- return;
- }
-
- String[] allowedValues =
- JsonUtils.anyFieldMapper().readValue(tagPO.getAllowedValues(), String[].class);
- // Treat JSON null like SQL NULL, consistent with POConverters.
- if (allowedValues == null) {
- return;
- }
- if (!tagValue.value().isPresent()) {
- Preconditions.checkArgument(
- allowedValues.length == 0,
- "Tag %s requires assignment values from allowed values %s",
- tagValue.name(),
- Arrays.toString(allowedValues));
- return;
- }
-
- Preconditions.checkArgument(
- allowedValues.length > 0, "Tag %s does not allow assignment values", tagValue.name());
- Preconditions.checkArgument(
- Arrays.asList(allowedValues).contains(tagValue.value().get()),
- "Tag %s value %s is not in allowed values %s",
- tagValue.name(),
- tagValue.value().get(),
- Arrays.toString(allowedValues));
+ TagEntity.validateAllowedValue(
+ tagPO.getAllowedValues() == null
+ ? null
+ : JsonUtils.anyFieldMapper().readValue(tagPO.getAllowedValues(), String[].class),
+ tagValue);
}
/**
@@ -1014,6 +993,65 @@ public class TagMetaService {
return lockedTagPOs;
}
+ /**
+ * Resolves a tag by name and locks it exclusively, in the caller's transaction, for a domain to
+ * bind it as its backing tag. The tag is re-checked after it is locked, so a tag dropped or
+ * renamed after it was resolved is reported as missing. The session cache is cleared before the
+ * tag is resolved, so neither the tag nor the reads that follow the lock are served from earlier
+ * reads in the session, such as those of a caller's outer transaction.
+ *
+ * @param metalakeId The metalake ID.
+ * @param namespace The tag namespace of the metalake.
+ * @param tagName The tag name.
+ * @return The locked tag.
+ * @throws NoSuchTagException If the tag does not exist.
+ */
+ TagEntity lockAndGetTagForDomainBinding(Long metalakeId, Namespace namespace, String tagName) {
+ // Earlier reads in the session, such as those of a caller's outer transaction, may be cached:
+ // the tag, which may since have been dropped and created again under a new ID, and the domains
+ // bound to it, which the caller reads after the lock. Both must be read as they are now.
+ SessionUtils.clearSessionCache();
+ TagPO observedTagPO =
+ SessionUtils.getWithoutCommit(
+ TagMetaMapper.class,
+ mapper -> mapper.selectTagMetaByMetalakeIdAndName(metalakeId, tagName));
+ List<TagPO> lockedTagPOs =
+ observedTagPO == null
+ ? Collections.emptyList()
+ : lockTagsForAssignment(Collections.singletonList(observedTagPO));
+ if (lockedTagPOs.isEmpty()) {
+ throw new NoSuchTagException(
+ "Tag with name %s under metalake %s does not exist", tagName, namespace.level(0));
+ }
+ return POConverters.fromTagPO(lockedTagPOs.get(0), namespace);
+ }
+
+ /**
+ * Inserts the new backing tag of a new domain, in the caller's transaction. The caller holds the
+ * shared lock on the metalake.
+ *
+ * @param tagEntity The new tag.
+ * @param metalakeId The metalake ID.
+ * @throws TagAlreadyExistsException If a tag with the same name exists.
+ */
+ void insertTagOfNewDomain(TagEntity tagEntity, Long metalakeId) {
+ TagPO tagPO =
+ POConverters.initializeTagPOWithVersion(
+ tagEntity, TagPO.builder().withMetalakeId(metalakeId));
+ try {
+ insertNewTagWithoutCommit(tagPO);
+ } catch (RuntimeException e) {
+ if (ExceptionUtils.isDuplicateKey(e)) {
+ throw new TagAlreadyExistsException(
+ e,
+ "Tag with name %s under metalake %s already exists",
+ tagEntity.name(),
+ tagEntity.namespace().level(0));
+ }
+ throw e;
+ }
+ }
+
private TagPO getTagPOByMetalakeAndName(String metalakeName, String tagName) {
TagPO tagPO =
SessionUtils.getWithoutCommit(
diff --git a/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java b/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
index 7a0463ef82..c304bc2220 100644
--- a/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
+++ b/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
@@ -57,24 +57,32 @@ import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.EntityStoreFactory;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchDomainException;
import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NonEmptyDomainException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.tag.TagValueConstraint;
import org.apache.gravitino.utils.MetadataObjectUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
@@ -127,7 +135,7 @@ public class TestDomainManager {
}
@AfterEach
- public void cleanUp() {
+ public void cleanUp() throws IOException {
DomainEntity[] domains = domainManager.listDomainInfos(METALAKE);
// Sub-domains first, since a domain with sub-domains cannot be deleted.
Arrays.stream(domains)
@@ -136,23 +144,31 @@ public class TestDomainManager {
Arrays.stream(domains)
.filter(domain -> !domain.parent().isPresent())
.forEach(domain -> domainManager.deleteDomain(METALAKE, domain.name()));
+ for (TagEntity tag :
+ entityStore.list(NamespaceUtil.ofTag(METALAKE), TagEntity.class, Entity.EntityType.TAG)) {
+ entityStore.delete(tag.nameIdentifier(), Entity.EntityType.TAG);
+ }
}
@Test
public void testCreateGetAndListDomains() {
Map<String, String> properties = ImmutableMap.of("k1", "v1");
- DomainEntity finance = domainManager.createDomain(METALAKE, "Finance", "comment", properties);
+ DomainEntity finance =
+ domainManager.createDomain(
+ METALAKE, "Finance", "comment", properties, TagValue.noValue("Finance"), true);
Assertions.assertEquals("Finance", finance.name());
Assertions.assertEquals(NamespaceUtil.ofDomain(METALAKE), finance.namespace());
Assertions.assertEquals("comment", finance.comment());
Assertions.assertEquals(properties, finance.properties());
Assertions.assertEquals(Domain.Status.DRAFT, finance.status());
Assertions.assertFalse(finance.parent().isPresent());
- Assertions.assertFalse(finance.backingTag().isPresent());
+ Assertions.assertEquals(TagValue.noValue("Finance"), finance.backingTag().orElse(null));
Assertions.assertNotNull(finance.auditInfo().creator());
Assertions.assertEquals(finance, domainManager.getDomain(METALAKE, "Finance"));
- DomainEntity markets = domainManager.createDomain(METALAKE, "Markets", null, null);
+ DomainEntity markets =
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.noValue("Markets"), true);
Assertions.assertNull(markets.comment());
Assertions.assertTrue(markets.properties().isEmpty());
@@ -165,21 +181,26 @@ public class TestDomainManager {
Assertions.assertThrows(
DomainAlreadyExistsException.class,
- () -> domainManager.createDomain(METALAKE, "Finance", null, null));
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("Finance2"), true));
Assertions.assertThrows(
NoSuchDomainException.class, () -> domainManager.getDomain(METALAKE, "missing"));
Assertions.assertThrows(
NoSuchMetalakeException.class,
- () -> domainManager.createDomain("missing_metalake", "Finance", null, null));
+ () ->
+ domainManager.createDomain(
+ "missing_metalake", "Finance", null, null, TagValue.noValue("Finance"), true));
Assertions.assertThrows(
NoSuchMetalakeException.class, () -> domainManager.listDomains("missing_metalake"));
}
@Test
public void testCreateSubdomain() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
DomainEntity trading =
- domainManager.createSubdomain(METALAKE, "Finance", "Trading", "comment", null);
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", "comment", null, TagValue.noValue("Trading"), true);
Assertions.assertEquals("Finance", trading.parent().get());
Assertions.assertEquals(Domain.Status.DRAFT, trading.status());
Assertions.assertEquals(trading, domainManager.getDomain(METALAKE, "Trading"));
@@ -193,30 +214,45 @@ public class TestDomainManager {
IllegalArgumentException e =
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> domainManager.createSubdomain(METALAKE, "Trading", "Desk", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Trading", "Desk", null, null, TagValue.noValue("Desk"), true));
Assertions.assertTrue(e.getMessage().contains("itself a sub-domain"), e.getMessage());
Assertions.assertThrows(
NoSuchDomainException.class, () -> domainManager.getDomain(METALAKE, "Desk"));
Assertions.assertThrows(
NoSuchDomainException.class,
- () -> domainManager.createSubdomain(METALAKE, "missing", "Desk", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "missing", "Desk", null, null, TagValue.noValue("Desk"), true));
// A domain cannot be its own parent.
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> domainManager.createSubdomain(METALAKE, "Finance", "Finance", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Finance", null, null, TagValue.noValue("Finance2"), true));
Assertions.assertThrows(
DomainAlreadyExistsException.class,
- () -> domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("Trading2"), true));
Assertions.assertThrows(
NoSuchDomainException.class, () -> domainManager.listSubdomains(METALAKE, "missing"));
}
@Test
public void testAlterDomain() {
- domainManager.createDomain(METALAKE, "Finance", "comment", ImmutableMap.of("k1", "v1"));
- domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null);
- domainManager.createDomain(METALAKE, "Markets", null, null);
+ domainManager.createDomain(
+ METALAKE,
+ "Finance",
+ "comment",
+ ImmutableMap.of("k1", "v1"),
+ TagValue.noValue("Finance"),
+ true);
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("Trading"), true);
+ domainManager.createDomain(METALAKE, "Markets", null, null, TagValue.noValue("Markets"), true);
DomainEntity altered =
domainManager.alterDomain(
@@ -254,8 +290,9 @@ public class TestDomainManager {
@Test
public void testDeleteDomain() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
- domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("Trading"), true);
Assertions.assertThrows(
NonEmptyDomainException.class, () -> domainManager.deleteDomain(METALAKE, "Finance"));
@@ -270,8 +307,9 @@ public class TestDomainManager {
@Test
public void testPublishAndUnpublish() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
- domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("Trading"), true);
// A sub-domain needs a published parent.
Assertions.assertThrows(
@@ -311,9 +349,9 @@ public class TestDomainManager {
@Test
public void testAttachMoveAndDetach() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
- domainManager.createDomain(METALAKE, "Markets", null, null);
- domainManager.createDomain(METALAKE, "Trading", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
+ domainManager.createDomain(METALAKE, "Markets", null, null, TagValue.noValue("Markets"), true);
+ domainManager.createDomain(METALAKE, "Trading", null, null, TagValue.noValue("Trading"), true);
DomainEntity attached = domainManager.attachDomain(METALAKE, "Trading", "Finance");
Assertions.assertEquals("Finance", attached.parent().get());
@@ -345,7 +383,8 @@ public class TestDomainManager {
Assertions.assertTrue(e.getMessage().contains("[Trading]"), e.getMessage());
Assertions.assertFalse(domainManager.getDomain(METALAKE, "Markets").parent().isPresent());
// A sub-domain cannot be moved under another sub-domain.
- domainManager.createSubdomain(METALAKE, "Finance", "Desk", null, null);
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Desk", null, null, TagValue.noValue("Desk"), true);
Assertions.assertThrows(
IllegalArgumentException.class,
() -> domainManager.attachDomain(METALAKE, "Trading", "Desk"));
@@ -369,8 +408,8 @@ public class TestDomainManager {
@Test
public void testAttachChecksStatus() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
- domainManager.createDomain(METALAKE, "Trading", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
+ domainManager.createDomain(METALAKE, "Trading", null, null, TagValue.noValue("Trading"), true);
domainManager.publishDomain(METALAKE, "Trading");
// A published domain needs a published parent.
@@ -384,8 +423,8 @@ public class TestDomainManager {
"Finance", domainManager.attachDomain(METALAKE, "Trading", "Finance").parent().get());
// A draft domain can be attached under a draft or a published parent.
- domainManager.createDomain(METALAKE, "Draft", null, null);
- domainManager.createDomain(METALAKE, "Desk", null, null);
+ domainManager.createDomain(METALAKE, "Draft", null, null, TagValue.noValue("Draft"), true);
+ domainManager.createDomain(METALAKE, "Desk", null, null, TagValue.noValue("Desk"), true);
Assertions.assertEquals(
"Draft", domainManager.attachDomain(METALAKE, "Desk", "Draft").parent().get());
Assertions.assertEquals(
@@ -455,9 +494,254 @@ public class TestDomainManager {
domain("Finance", null, Domain.Status.PUBLISHED), null, publishedSubDomains)));
}
+ @Test
+ public void testCreateWithNewBackingTag() throws IOException {
+ DomainEntity finance =
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("finance_tag"), true);
+ Assertions.assertEquals(TagValue.noValue("finance_tag"), finance.backingTag().orElse(null));
+ TagEntity tag =
+ entityStore.get(
+ NameIdentifierUtil.ofTag(METALAKE, "finance_tag"),
+ Entity.EntityType.TAG,
+ TagEntity.class);
+ Assertions.assertEquals(finance.backingTagId(), tag.id());
+ Assertions.assertEquals(TagValueConstraint.noValue(), tag.valueConstraint());
+ Assertions.assertNotNull(tag.auditInfo().creator());
+
+ // A new tag cannot have a value, and a backing tag is required.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("markets_tag", "v"), true));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domainManager.createDomain(METALAKE, "Markets", null, null, null, true));
+
+ // An existing tag is never adopted, and nothing is created.
+ Assertions.assertThrows(
+ TagAlreadyExistsException.class,
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("finance_tag"), true));
+ Assertions.assertThrows(
+ NoSuchDomainException.class, () -> domainManager.getDomain(METALAKE, "Trading"));
+
+ // A create that fails after the new tag is written leaves no tag behind: here the check
+ // refuses a parent that is itself a sub-domain.
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("trading_tag"), true);
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Trading", "Desk", null, null, TagValue.noValue("desk_tag"), true));
+ Assertions.assertFalse(
+ entityStore.exists(NameIdentifierUtil.ofTag(METALAKE, "desk_tag"), Entity.EntityType.TAG));
+ Assertions.assertThrows(
+ NoSuchDomainException.class, () -> domainManager.getDomain(METALAKE, "Desk"));
+
+ // A domain name in use fails before the new tag is written.
+ Assertions.assertThrows(
+ DomainAlreadyExistsException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("markets_tag"), true));
+ Assertions.assertFalse(
+ entityStore.exists(
+ NameIdentifierUtil.ofTag(METALAKE, "markets_tag"), Entity.EntityType.TAG));
+ }
+
+ @Test
+ public void testCreateWithExistingBackingTag() throws IOException {
+ createTag("dept", TagValueConstraint.ofAllowedValues("finance", "markets", "tax"));
+ createTag("plain", TagValueConstraint.noValue());
+ createTag("any", TagValueConstraint.anyValue());
+
+ DomainEntity finance =
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.of("dept", "finance"), false);
+ Assertions.assertEquals(TagValue.of("dept", "finance"), finance.backingTag().orElse(null));
+ Assertions.assertEquals(finance, domainManager.getDomain(METALAKE, "Finance"));
+ DomainEntity tax =
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Tax", null, null, TagValue.of("dept", "tax"), false);
+ Assertions.assertEquals("Finance", tax.parent().orElse(null));
+ Assertions.assertEquals(TagValue.of("dept", "tax"), tax.backingTag().orElse(null));
+
+ // The tag must exist and allow the value.
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.noValue("missing"), false));
+ // The tag is locked before the domain is written, so a missing tag is reported before a domain
+ // name in use, and a domain name in use before a value the tag does not allow.
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("missing"), false));
+ Assertions.assertThrows(
+ DomainAlreadyExistsException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.of("dept", "other"), false));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("dept", "other"), false));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.noValue("dept"), false));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("plain", "v"), false));
+
+ // A value backs one domain, and valued and valueless bindings of a tag are never mixed.
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("dept", "finance"), false));
+ domainManager.createDomain(METALAKE, "Plain", null, null, TagValue.noValue("plain"), false);
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.noValue("plain"), false));
+ domainManager.createDomain(METALAKE, "Any", null, null, TagValue.noValue("any"), false);
+ BackingTagAlreadyBoundException e =
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("any", "v"), false));
+ Assertions.assertTrue(e.getMessage().contains("without a value"), e.getMessage());
+ Assertions.assertThrows(
+ NoSuchDomainException.class, () -> domainManager.getDomain(METALAKE, "Markets"));
+
+ Assertions.assertEquals(
+ TagValue.of("dept", "markets"),
+ domainManager
+ .createDomain(METALAKE, "Markets", null, null, TagValue.of("dept", "markets"), false)
+ .backingTag()
+ .orElse(null));
+ }
+
+ @Test
+ public void testUpdateBackingTag() throws IOException {
+ createTag("dept", TagValueConstraint.ofAllowedValues("finance", "markets"));
+ createTag("region", TagValueConstraint.anyValue());
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.of("dept", "finance"), false);
+ domainManager.createDomain(
+ METALAKE, "Markets", null, null, TagValue.of("dept", "markets"), false);
+
+ DomainEntity updated =
+ domainManager.updateBackingTag(METALAKE, "Finance", TagValue.of("region", "emea"));
+ Assertions.assertEquals(TagValue.of("region", "emea"), updated.backingTag().orElse(null));
+ Assertions.assertNotNull(updated.auditInfo().lastModifier());
+ Assertions.assertEquals(updated, domainManager.getDomain(METALAKE, "Finance"));
+ // Setting the current backing tag changes nothing.
+ Assertions.assertEquals(
+ updated,
+ domainManager.updateBackingTag(METALAKE, "Finance", TagValue.of("region", "emea")));
+
+ // A domain may change the value of its own tag, but not take a value bound elsewhere.
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Finance", TagValue.of("dept", "markets")));
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Markets", TagValue.noValue("region")));
+ Assertions.assertEquals(
+ TagValue.of("dept", "finance"),
+ domainManager
+ .updateBackingTag(METALAKE, "Markets", TagValue.of("dept", "finance"))
+ .backingTag()
+ .orElse(null));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Finance", TagValue.of("dept", "other")));
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Finance", TagValue.noValue("missing")));
+ Assertions.assertEquals(
+ TagValue.of("region", "emea"),
+ domainManager.getDomain(METALAKE, "Finance").backingTag().orElse(null));
+
+ // Removing the backing tag leaves the domain without one, until a new one is set.
+ DomainEntity removed = domainManager.updateBackingTag(METALAKE, "Finance", null);
+ Assertions.assertFalse(removed.backingTag().isPresent());
+ Assertions.assertEquals(removed, domainManager.updateBackingTag(METALAKE, "Finance", null));
+ Assertions.assertEquals(
+ TagValue.of("region", "apac"),
+ domainManager
+ .updateBackingTag(METALAKE, "Finance", TagValue.of("region", "apac"))
+ .backingTag()
+ .orElse(null));
+
+ Assertions.assertThrows(
+ NoSuchDomainException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "missing", TagValue.noValue("region")));
+ }
+
+ @Test
+ public void testBackingTagChecks() {
+ TagEntity plain = tag("plain", new String[0]);
+ DomainEntity finance =
+ domain("Finance", null, Domain.Status.DRAFT).toBuilder()
+ .withBackingTagId(plain.id())
+ .build();
+
+ // Setting the current backing tag is not checked, even if the tag no longer allows it now.
+ DomainManager.checkBackingTagUpdate(
+ new LockedDomainState(
+ finance,
+ null,
+ Collections.emptyList(),
+ TagEntity.builder()
+ .withId(plain.id())
+ .withName("plain")
+ .withNamespace(plain.namespace())
+ .withAllowedValues(new String[] {"v"})
+ .withAuditInfo(plain.auditInfo())
+ .build(),
+ Collections.singletonList(finance)),
+ TagValue.noValue("plain"));
+ // Removing it is not checked either.
+ DomainManager.checkBackingTagUpdate(
+ new LockedDomainState(finance, null, Collections.emptyList()), null);
+
+ // The domain's own binding does not conflict with it.
+ DomainEntity markets = domain("Markets", null, Domain.Status.DRAFT);
+ DomainManager.checkBackingTagUpdate(
+ new LockedDomainState(
+ markets, null, Collections.emptyList(), plain, Collections.singletonList(markets)),
+ TagValue.noValue("plain"));
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ DomainManager.checkBackingTagUpdate(
+ new LockedDomainState(
+ markets,
+ null,
+ Collections.emptyList(),
+ plain,
+ Collections.singletonList(finance)),
+ TagValue.noValue("plain")));
+ }
+
@Test
public void testCheckDomainMetadataObject() {
- domainManager.createDomain(METALAKE, "Finance", null, null);
+ domainManager.createDomain(METALAKE, "Finance", null, null, TagValue.noValue("Finance"), true);
MetadataObjectUtil.checkMetadataObject(
METALAKE, MetadataObjects.of(null, "Finance", MetadataObject.Type.DOMAIN));
Assertions.assertThrows(
@@ -480,6 +764,27 @@ public class TestDomainManager {
.build();
}
+ private static TagEntity tag(String name, String[] allowedValues) {
+ return TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(METALAKE))
+ .withAllowedValues(allowedValues)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ private static void createTag(String name, TagValueConstraint constraint) throws IOException {
+ entityStore.put(
+ tag(
+ name,
+ constraint.type() == TagValueConstraint.Type.ANY_VALUE
+ ? null
+ : constraint.allowedValues()),
+ false /* overwritten */);
+ }
+
private static Config mockConfig() {
Config config = Mockito.mock(Config.class);
diff --git a/core/src/test/java/org/apache/gravitino/domain/TestDomainManagerWithMockStore.java b/core/src/test/java/org/apache/gravitino/domain/TestDomainManagerWithMockStore.java
index 56e8a179bd..df9d22376d 100644
--- a/core/src/test/java/org/apache/gravitino/domain/TestDomainManagerWithMockStore.java
+++ b/core/src/test/java/org/apache/gravitino/domain/TestDomainManagerWithMockStore.java
@@ -34,18 +34,24 @@ import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.SupportsDomainOperations;
import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchDomainException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.NonEmptyDomainException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.SchemaVersion;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.IdGenerator;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.tag.TagValueConstraint;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
@@ -64,6 +70,7 @@ public class TestDomainManagerWithMockStore {
private static final String METALAKE = "metalake";
private static final NameIdentifier FINANCE = NameIdentifierUtil.ofDomain(METALAKE, "Finance");
private static final NameIdentifier TRADING = NameIdentifierUtil.ofDomain(METALAKE, "Trading");
+ private static final TagValue BACKING_TAG = TagValue.of("dept", "finance");
private EntityStore entityStore;
private SupportsDomainOperations domainOperations;
@@ -88,6 +95,14 @@ public class TestDomainManagerWithMockStore {
BaseMetalake.class))
.thenReturn(metalake);
+ // Like the store, an insert runs its check, which the manager returns the domain from.
+ Mockito.doAnswer(TestDomainManagerWithMockStore::runTopLevelInsertCheck)
+ .when(domainOperations)
+ .insertDomainWithBackingTag(any(), any(), any());
+ Mockito.doAnswer(TestDomainManagerWithMockStore::runTopLevelInsertCheck)
+ .when(domainOperations)
+ .insertDomainWithNewBackingTag(any(), any(), any());
+
IdGenerator idGenerator = Mockito.mock(IdGenerator.class);
Mockito.when(idGenerator.nextId()).thenReturn(100L);
domainManager = new DomainManager(idGenerator, entityStore);
@@ -108,10 +123,12 @@ public class TestDomainManagerWithMockStore {
NoSuchMetalakeException.class, () -> domainManager.getDomain("missing", "Finance"));
Assertions.assertThrows(
NoSuchMetalakeException.class,
- () -> domainManager.createDomain("missing", "Finance", null, null));
+ () -> domainManager.createDomain("missing", "Finance", null, null, BACKING_TAG, false));
Assertions.assertThrows(
NoSuchMetalakeException.class,
- () -> domainManager.createSubdomain("missing", "Finance", "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ "missing", "Finance", "Trading", null, null, BACKING_TAG, false));
Assertions.assertThrows(
NoSuchMetalakeException.class,
() -> domainManager.alterDomain("missing", "Finance", DomainChange.updateComment("c")));
@@ -129,6 +146,9 @@ public class TestDomainManagerWithMockStore {
() -> domainManager.attachDomain("missing", "Trading", "Finance"));
Assertions.assertThrows(
NoSuchMetalakeException.class, () -> domainManager.detachDomain("missing", "Trading"));
+ Assertions.assertThrows(
+ NoSuchMetalakeException.class,
+ () -> domainManager.updateBackingTag("missing", "Finance", BACKING_TAG));
Mockito.verifyNoInteractions(domainOperations);
Mockito.verify(entityStore, Mockito.never()).update(any(), any(), any(), any());
Mockito.verify(entityStore, Mockito.never()).delete(any(), any());
@@ -155,8 +175,10 @@ public class TestDomainManagerWithMockStore {
public void testCreateDomain() throws IOException {
ArgumentCaptor<DomainEntity> domainCaptor = ArgumentCaptor.forClass(DomainEntity.class);
ArgumentCaptor<Consumer<LockedDomainState>> checkCaptor = checkCaptor();
- DomainEntity created = domainManager.createDomain(METALAKE, "Finance", "comment", null);
- Mockito.verify(domainOperations).insertDomain(domainCaptor.capture(), checkCaptor.capture());
+ DomainEntity created =
+ domainManager.createDomain(METALAKE, "Finance", "comment", null, BACKING_TAG, false);
+ Mockito.verify(domainOperations)
+ .insertDomainWithBackingTag(domainCaptor.capture(), eq(BACKING_TAG), checkCaptor.capture());
DomainEntity inserted = domainCaptor.getValue();
Assertions.assertSame(inserted, created);
@@ -170,31 +192,33 @@ public class TestDomainManagerWithMockStore {
Mockito.doThrow(new EntityAlreadyExistsException("exists"))
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
Assertions.assertThrows(
DomainAlreadyExistsException.class,
- () -> domainManager.createDomain(METALAKE, "Finance", null, null));
+ () -> domainManager.createDomain(METALAKE, "Finance", null, null, BACKING_TAG, false));
// The metalake was dropped after it was checked.
Mockito.doThrow(new NoSuchEntityException("missing"))
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
Assertions.assertThrows(
NoSuchMetalakeException.class,
- () -> domainManager.createDomain(METALAKE, "Finance", null, null));
+ () -> domainManager.createDomain(METALAKE, "Finance", null, null, BACKING_TAG, false));
Mockito.doThrow(new IOException("insert failed"))
.when(domainOperations)
- .insertDomain(any(), any());
- assertIOExceptionWrapped(() -> domainManager.createDomain(METALAKE, "Finance", null, null));
+ .insertDomainWithBackingTag(any(), any(), any());
+ assertIOExceptionWrapped(
+ () -> domainManager.createDomain(METALAKE, "Finance", null, null, BACKING_TAG, false));
}
@Test
public void testCreateSubdomain() throws IOException {
ArgumentCaptor<DomainEntity> domainCaptor = ArgumentCaptor.forClass(DomainEntity.class);
ArgumentCaptor<Consumer<LockedDomainState>> checkCaptor = checkCaptor();
- domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null);
- Mockito.verify(domainOperations).insertDomain(domainCaptor.capture(), checkCaptor.capture());
+ domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null, BACKING_TAG, false);
+ Mockito.verify(domainOperations)
+ .insertDomainWithBackingTag(domainCaptor.capture(), eq(BACKING_TAG), checkCaptor.capture());
Assertions.assertEquals(TRADING, domainCaptor.getValue().nameIdentifier());
Assertions.assertEquals("Finance", domainCaptor.getValue().parent().get());
assertIsNewDomainCheck(checkCaptor.getValue());
@@ -204,56 +228,140 @@ public class TestDomainManagerWithMockStore {
Mockito.doAnswer(
invocation -> {
DomainEntity newDomain = invocation.getArgument(0);
- Consumer<LockedDomainState> check = invocation.getArgument(1);
+ Consumer<LockedDomainState> check = invocation.getArgument(2);
DomainEntity storedParent = domain("Finance", null, Domain.Status.DRAFT);
- check.accept(state(newDomain, storedParent));
+ check.accept(boundState(newDomain, storedParent));
return null;
})
.when(domainOperations)
- .insertDomain(any(), any());
- DomainEntity desk = domainManager.createSubdomain(METALAKE, "Finance ", "Desk", null, null);
+ .insertDomainWithBackingTag(any(), any(), any());
+ DomainEntity desk =
+ domainManager.createSubdomain(METALAKE, "Finance ", "Desk", null, null, BACKING_TAG, false);
Assertions.assertEquals("Finance", desk.parent().get());
Assertions.assertEquals(NameIdentifierUtil.ofDomain(METALAKE, "Desk"), desk.nameIdentifier());
// A check that throws reaches the caller unchanged.
Mockito.doAnswer(TestDomainManagerWithMockStore::runInsertCheck)
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> domainManager.createSubdomain(METALAKE, "Trading", "Desk", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Trading", "Desk", null, null, BACKING_TAG, false));
Mockito.doThrow(new NoSuchEntityException("missing"))
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
Assertions.assertThrows(
NoSuchDomainException.class,
- () -> domainManager.createSubdomain(METALAKE, "missing", "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "missing", "Trading", null, null, BACKING_TAG, false));
Mockito.doThrow(new EntityAlreadyExistsException("exists"))
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
Assertions.assertThrows(
DomainAlreadyExistsException.class,
- () -> domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, BACKING_TAG, false));
Mockito.doThrow(new IOException("insert failed"))
.when(domainOperations)
- .insertDomain(any(), any());
+ .insertDomainWithBackingTag(any(), any(), any());
assertIOExceptionWrapped(
- () -> domainManager.createSubdomain(METALAKE, "Finance", "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, BACKING_TAG, false));
// A domain as its own parent, and a null parent, are refused before the store is called.
Mockito.clearInvocations(domainOperations);
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> domainManager.createSubdomain(METALAKE, "Finance", "Finance", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Finance", null, null, BACKING_TAG, false));
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> domainManager.createSubdomain(METALAKE, null, "Trading", null, null));
+ () ->
+ domainManager.createSubdomain(
+ METALAKE, null, "Trading", null, null, BACKING_TAG, false));
Mockito.verifyNoInteractions(domainOperations);
}
+ @Test
+ public void testCreateDomainWithNewBackingTag() throws IOException {
+ ArgumentCaptor<DomainEntity> domainCaptor = ArgumentCaptor.forClass(DomainEntity.class);
+ ArgumentCaptor<TagEntity> tagCaptor = ArgumentCaptor.forClass(TagEntity.class);
+ ArgumentCaptor<Consumer<LockedDomainState>> checkCaptor = checkCaptor();
+ domainManager.createSubdomain(
+ METALAKE, "Finance", "Trading", null, null, TagValue.noValue("trading_tag"), true);
+ Mockito.verify(domainOperations)
+ .insertDomainWithNewBackingTag(
+ domainCaptor.capture(), tagCaptor.capture(), checkCaptor.capture());
+ Assertions.assertEquals(TRADING, domainCaptor.getValue().nameIdentifier());
+ TagEntity tag = tagCaptor.getValue();
+ Assertions.assertEquals(
+ NameIdentifierUtil.ofTag(METALAKE, "trading_tag"), tag.nameIdentifier());
+ Assertions.assertEquals(100L, tag.id());
+ Assertions.assertEquals(TagValueConstraint.noValue(), tag.valueConstraint());
+ assertIsNewDomainCheck(checkCaptor.getValue());
+
+ // A tag name in use reaches the caller unchanged.
+ Mockito.doThrow(new TagAlreadyExistsException("exists"))
+ .when(domainOperations)
+ .insertDomainWithNewBackingTag(any(), any(), any());
+ Assertions.assertThrows(
+ TagAlreadyExistsException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("finance_tag"), true));
+
+ // A missing tag, a value for a new tag and a null tag are refused before the store is called.
+ Mockito.doThrow(new NoSuchTagException("missing"))
+ .when(domainOperations)
+ .insertDomainWithBackingTag(any(), any(), any());
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.noValue("missing"), false));
+ Mockito.clearInvocations(domainOperations);
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainManager.createDomain(
+ METALAKE, "Finance", null, null, TagValue.of("finance_tag", "v"), true));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domainManager.createDomain(METALAKE, "Finance", null, null, null, false));
+ Mockito.verifyNoInteractions(domainOperations);
+ }
+
+ @Test
+ public void testUpdateBackingTag() throws IOException {
+ ArgumentCaptor<Consumer<LockedDomainState>> checkCaptor = checkCaptor();
+ TagValue backingTag = TagValue.of("dept", "finance");
+ domainManager.updateBackingTag(METALAKE, "Finance", backingTag);
+ Mockito.verify(domainOperations)
+ .updateDomainBackingTagAndGet(eq(FINANCE), eq(backingTag), any(), checkCaptor.capture());
+ assertIsBackingTagUpdateCheck(checkCaptor.getValue());
+
+ Mockito.when(domainOperations.updateDomainBackingTagAndGet(eq(FINANCE), any(), any(), any()))
+ .thenThrow(new NoSuchEntityException("missing"))
+ .thenThrow(new NoSuchTagException("missing"))
+ .thenThrow(new IOException("update failed"));
+ Assertions.assertThrows(
+ NoSuchDomainException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Finance", null));
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () -> domainManager.updateBackingTag(METALAKE, "Finance", backingTag));
+ assertIOExceptionWrapped(() -> domainManager.updateBackingTag(METALAKE, "Finance", null));
+ }
+
@Test
public void testAlterDomain() throws IOException {
Mockito.when(entityStore.update(eq(FINANCE), eq(DomainEntity.class), any(), any()))
@@ -436,10 +544,29 @@ public class TestDomainManagerWithMockStore {
// The insert check refuses a parent that is itself a sub-domain.
private static void assertIsNewDomainCheck(Consumer<LockedDomainState> check) {
DomainEntity desk = domain("Desk", "Trading", Domain.Status.DRAFT);
- check.accept(state(desk, domain("Trading", null, Domain.Status.DRAFT)));
+ check.accept(boundState(desk, domain("Trading", null, Domain.Status.DRAFT)));
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> check.accept(state(desk, domain("Trading", "Finance", Domain.Status.DRAFT))));
+ () -> check.accept(boundState(desk, domain("Trading", "Finance", Domain.Status.DRAFT))));
+ }
+
+ // The backing tag update check refuses a value bound to another domain.
+ private static void assertIsBackingTagUpdateCheck(Consumer<LockedDomainState> check) {
+ DomainEntity finance = domain("Finance", null, Domain.Status.DRAFT);
+ DomainEntity markets =
+ domain("Markets", null, Domain.Status.DRAFT).toBuilder()
+ .withBackingTagId(tag("dept").id())
+ .withBackingTagValue("finance")
+ .build();
+ check.accept(
+ new LockedDomainState(
+ finance, null, Collections.emptyList(), tag("dept"), Collections.emptyList()));
+ Assertions.assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ check.accept(
+ new LockedDomainState(
+ finance, null, Collections.emptyList(), tag("dept"), List.of(markets))));
}
// The publish check refuses a draft parent, which the unpublish check would accept.
@@ -480,11 +607,22 @@ public class TestDomainManagerWithMockStore {
trading, finance, List.of(domain("Desk", "Trading", Domain.Status.DRAFT)))));
}
+ // Runs the check of an insert as the store would for a top-level domain bound to a tag that
+ // allows
+ // any value and backs no other domain.
+ private static Object runTopLevelInsertCheck(InvocationOnMock invocation) {
+ DomainEntity domain = invocation.getArgument(0);
+ Consumer<LockedDomainState> check = invocation.getArgument(2);
+ check.accept(boundState(domain, null));
+ return null;
+ }
+
private static Object runInsertCheck(InvocationOnMock invocation) {
DomainEntity domain = invocation.getArgument(0);
- Consumer<LockedDomainState> check = invocation.getArgument(1);
+ Consumer<LockedDomainState> check = invocation.getArgument(2);
// The parent of the new domain is itself a sub-domain.
- check.accept(state(domain, domain(domain.parent().get(), "Finance", Domain.Status.PUBLISHED)));
+ check.accept(
+ boundState(domain, domain(domain.parent().get(), "Finance", Domain.Status.PUBLISHED)));
return null;
}
@@ -502,6 +640,21 @@ public class TestDomainManagerWithMockStore {
return new LockedDomainState(domain, parent, Collections.emptyList());
}
+ // The locked state of a new domain bound to a tag that backs no other domain.
+ private static LockedDomainState boundState(DomainEntity domain, DomainEntity parent) {
+ return new LockedDomainState(
+ domain, parent, Collections.emptyList(), tag("dept"), Collections.emptyList());
+ }
+
+ private static TagEntity tag(String name) {
+ return TagEntity.builder()
+ .withId((long) name.hashCode())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(METALAKE))
+ .withAuditInfo(auditInfo())
+ .build();
+ }
+
private static DomainEntity domain(String name, String parent, Domain.Status status) {
return DomainEntity.builder()
.withId((long) name.hashCode())
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
index b1cb6dde30..0286c13622 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
@@ -22,7 +22,9 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import java.io.IOException;
+import java.time.Instant;
import java.util.List;
+import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
@@ -33,14 +35,21 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.RelationEdgeTarget;
import org.apache.gravitino.RelationQuery;
import org.apache.gravitino.RelationUpdate;
+import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.cache.BaseEntityCache;
import org.apache.gravitino.cache.Coherence;
import org.apache.gravitino.cache.EntityCache;
import org.apache.gravitino.cache.NoOpsCache;
+import org.apache.gravitino.domain.Domain;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.TopicEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,6 +58,9 @@ import org.mockito.Mockito;
public class TestRelationalEntityStore {
+ private static final AuditInfo AUDIT_INFO =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
private RelationalEntityStore store;
private RelationalBackend backend;
@@ -149,6 +161,54 @@ public class TestRelationalEntityStore {
inOrder.verify(cache).invalidate(ident, Entity.EntityType.CATALOG);
}
+ @Test
+ void testInsertDomainWithNewBackingTagInvalidatesTagAfterBackendInsert()
+ throws IOException, IllegalAccessException {
+ DomainEntity domain =
+ DomainEntity.builder()
+ .withId(1L)
+ .withName("Finance")
+ .withNamespace(NamespaceUtil.ofDomain("metalake"))
+ .withStatus(Domain.Status.DRAFT)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TagEntity tag =
+ TagEntity.builder()
+ .withId(2L)
+ .withName("finance_tag")
+ .withNamespace(NamespaceUtil.ofTag("metalake"))
+ .withAllowedValues(new String[0])
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ NameIdentifier tagIdent = tag.nameIdentifier();
+ Consumer<LockedDomainState> check = state -> {};
+ NoOpsCache cache = (NoOpsCache) FieldUtils.readField(store, "cache", true);
+
+ Mockito.doAnswer(
+ invocation -> {
+ Mockito.verify(cache, Mockito.never()).invalidate(tagIdent, Entity.EntityType.TAG);
+ return null;
+ })
+ .when(backend)
+ .insertDomainWithNewBackingTag(domain, tag, check);
+
+ store.insertDomainWithNewBackingTag(domain, tag, check);
+
+ InOrder inOrder = Mockito.inOrder(backend, cache);
+ inOrder.verify(backend).insertDomainWithNewBackingTag(domain, tag, check);
+ inOrder.verify(cache).invalidate(tagIdent, Entity.EntityType.TAG);
+
+ // A failed insert leaves no new tag, so nothing is invalidated.
+ Mockito.clearInvocations(cache);
+ Mockito.doThrow(new TagAlreadyExistsException("Tag finance_tag already exists"))
+ .when(backend)
+ .insertDomainWithNewBackingTag(domain, tag, check);
+ Assertions.assertThrows(
+ TagAlreadyExistsException.class,
+ () -> store.insertDomainWithNewBackingTag(domain, tag, check));
+ Mockito.verify(cache, Mockito.never()).invalidate(any(), any());
+ }
+
@Test
void testInsertRelationInvalidatesCacheAfterBackendInsert()
throws IOException, IllegalAccessException {
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
index 006acc1fbd..663c46f502 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
@@ -55,6 +55,7 @@ import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.tag.TagValue;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.ibatis.exceptions.PersistenceException;
@@ -351,7 +352,18 @@ public class TestRelationalEntityStoreLockWaitTimeout {
"batchDelete",
() -> store.batchDelete(List.of(Pair.of(TABLE_IDENT, Entity.EntityType.TABLE)), false)),
Pair.of("batchPut", () -> store.batchPut(List.of(table), true)),
- Pair.of("insertDomain", () -> store.insertDomain(domain(), state -> {})),
+ Pair.of(
+ "insertDomainWithBackingTag",
+ () ->
+ store.insertDomainWithBackingTag(domain(), TagValue.of("tag1", "v1"), state -> {})),
+ Pair.of(
+ "insertDomainWithNewBackingTag",
+ () -> store.insertDomainWithNewBackingTag(domain(), backingTag(), state -> {})),
+ Pair.of(
+ "updateDomainBackingTagAndGet",
+ () ->
+ store.updateDomainBackingTagAndGet(
+ DOMAIN_IDENT, TagValue.noValue("tag1"), AUDIT_INFO, state -> {})),
Pair.of(
"setDomainParentAndGet",
() ->
@@ -381,6 +393,16 @@ public class TestRelationalEntityStoreLockWaitTimeout {
.build();
}
+ private static TagEntity backingTag() {
+ return TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("tag1")
+ .withNamespace(NamespaceUtil.ofTag(METALAKE))
+ .withAllowedValues(new String[0])
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
private List<TagEntity> associateTags(NameIdentifier[] tags) throws IOException {
return store.updateEntityRelations(
SupportsRelationOperations.Type.TAG_METADATA_OBJECT_REL,
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java
index 62169aea59..2514d93dbc 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.storage.relational.service;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.IOException;
@@ -26,6 +27,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@@ -34,14 +36,18 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.SupportsDomainOperations.LockedDomainState;
import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.domain.Domain;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.DomainEntity;
@@ -58,6 +64,7 @@ import org.apache.gravitino.storage.relational.po.MetalakePO;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.tag.TagValueConstraint;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.ibatis.session.SqlSession;
@@ -576,44 +583,49 @@ public class TestDomainMetaService extends TestJDBCBackend {
Assertions.assertEquals(dept.id(), orphaned.backingTagId());
Assertions.assertEquals("trading", orphaned.backingTagValue());
- // An update writes the binding: replace it, then remove it.
+ // Neither an update nor a replacement can change the binding; it is changed under the binding
+ // rules by updateDomainBackingTagAndGet.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.updateDomain(
+ trading.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder()
+ .withBackingTagId(finance.id())
+ .withBackingTagValue(null)
+ .build()));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.updateDomain(
+ trading.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity).toBuilder().withBackingTagValue("other").build()));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.insertDomain(
+ financeDomain.toBuilder().withBackingTagValue("other").build(), true));
+ Assertions.assertEquals(
+ orphaned, domainMetaService.getDomainByIdentifier(trading.nameIdentifier()));
+
+ // Rebinding away from a deleted tag returns the new tag's name, then the binding is removed.
+ TagEntity region = newTag("region");
+ backend.insert(region, false);
DomainEntity rebound =
- domainMetaService.updateDomain(
- trading.nameIdentifier(),
- entity ->
- ((DomainEntity) entity)
- .toBuilder().withBackingTagId(finance.id()).withBackingTagValue(null).build());
- Assertions.assertEquals(finance.id(), rebound.backingTagId());
- Assertions.assertEquals(TagValue.noValue("Finance"), rebound.backingTag().orElse(null));
+ domainMetaService.updateDomainBackingTagAndGet(
+ trading.nameIdentifier(), TagValue.of("region", "apac"), AUDIT_INFO, s -> {});
+ Assertions.assertEquals(TagValue.of("region", "apac"), rebound.backingTag().orElse(null));
Assertions.assertEquals(
- TagValue.noValue("Finance"),
- domainMetaService
- .getDomainByIdentifier(trading.nameIdentifier())
- .backingTag()
- .orElse(null));
+ rebound, domainMetaService.getDomainByIdentifier(trading.nameIdentifier()));
- domainMetaService.updateDomain(
- trading.nameIdentifier(),
- entity ->
- ((DomainEntity) entity)
- .toBuilder().withBackingTagId(null).withBackingTagValue(null).build());
+ domainMetaService.updateDomainBackingTagAndGet(
+ trading.nameIdentifier(), null, AUDIT_INFO, s -> {});
DomainEntity unbound = domainMetaService.getDomainByIdentifier(trading.nameIdentifier());
Assertions.assertFalse(unbound.backingTag().isPresent());
Assertions.assertNull(unbound.backingTagId());
-
- // Rebinding away from a live tag returns the new tag's name, not the one the updater's entity
- // still carries.
- TagEntity region = newTag("region");
- backend.insert(region, false);
- DomainEntity switched =
- domainMetaService.updateDomain(
- financeDomain.nameIdentifier(),
- entity ->
- ((DomainEntity) entity)
- .toBuilder().withBackingTagId(region.id()).withBackingTagValue("apac").build());
- Assertions.assertEquals(TagValue.of("region", "apac"), switched.backingTag().orElse(null));
- Assertions.assertEquals(
- switched, domainMetaService.getDomainByIdentifier(financeDomain.nameIdentifier()));
}
@TestTemplate
@@ -684,7 +696,8 @@ public class TestDomainMetaService extends TestJDBCBackend {
DomainMetaService domainMetaService = DomainMetaService.getInstance();
TagEntity tag = newTag("Finance");
backend.insert(tag, false);
- DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ DomainEntity finance =
+ newDomain(METALAKE_NAME, "Finance", null).toBuilder().withBackingTagId(tag.id()).build();
domainMetaService.insertDomain(finance, false);
CountDownLatch domainLocked = new CountDownLatch(1);
@@ -703,8 +716,7 @@ public class TestDomainMetaService extends TestJDBCBackend {
SessionUtils.getWithoutCommit(
TagMetaMapper.class,
mapper -> mapper.selectTagByTagIdForUpdate(tag.id()));
- return ((DomainEntity) entity)
- .toBuilder().withBackingTagId(tag.id()).build();
+ return ((DomainEntity) entity).toBuilder().withComment("updated").build();
}));
Assertions.assertTrue(domainLocked.await(30, TimeUnit.SECONDS));
@@ -943,6 +955,493 @@ public class TestDomainMetaService extends TestJDBCBackend {
}
}
+ @TestTemplate
+ public void testInsertDomainWithBackingTag() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ backend.insert(dept, false);
+ List<LockedDomainState> states = new ArrayList<>();
+
+ domainMetaService.insertDomainWithBackingTag(
+ newDomain(METALAKE_NAME, "Finance", null), TagValue.of("dept", "finance"), states::add);
+ LockedDomainState state = states.get(0);
+ DomainEntity finance = state.domain();
+ Assertions.assertEquals(TagValue.of("dept", "finance"), finance.backingTag().orElse(null));
+ Assertions.assertEquals(dept.id(), finance.backingTagId());
+ Assertions.assertEquals(
+ finance, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ Assertions.assertEquals(dept.id(), state.backingTag().get().id());
+ Assertions.assertTrue(state.backingTagBindings().isEmpty());
+
+ // A sub-domain is inserted with its edge, and the check sees the domains the tag backs.
+ states.clear();
+ domainMetaService.insertDomainWithBackingTag(
+ newDomain(METALAKE_NAME, "Tax", null).toBuilder().withParent("Finance").build(),
+ TagValue.noValue("dept"),
+ states::add);
+ DomainEntity tax = states.get(0).domain();
+ Assertions.assertEquals(tax, domainMetaService.getDomainByIdentifier(tax.nameIdentifier()));
+ Assertions.assertEquals("Finance", tax.parent().orElse(null));
+ Assertions.assertEquals(TagValue.noValue("dept"), tax.backingTag().orElse(null));
+ state = states.get(0);
+ Assertions.assertEquals(finance.id(), state.parent().get().id());
+ Assertions.assertEquals(1, state.backingTagBindings().size());
+ Assertions.assertEquals(finance.id(), state.backingTagBindings().get(0).id());
+ Assertions.assertEquals("finance", state.backingTagBindings().get(0).backingTagValue());
+
+ // A missing tag or a failing check inserts nothing.
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () ->
+ domainMetaService.insertDomainWithBackingTag(
+ markets, TagValue.noValue("missing"), s -> {}));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.insertDomainWithBackingTag(
+ markets,
+ TagValue.noValue("dept"),
+ s -> {
+ throw new IllegalArgumentException("rejected");
+ }));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+ }
+
+ @TestTemplate
+ public void testInsertDomainWithNewBackingTag() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagMetaService tagMetaService = TagMetaService.getInstance();
+ TagEntity financeTag = newValuelessTag("Finance");
+ List<LockedDomainState> states = new ArrayList<>();
+
+ domainMetaService.insertDomainWithNewBackingTag(
+ newDomain(METALAKE_NAME, "Finance", null), financeTag, states::add);
+ DomainEntity finance = states.get(0).domain();
+ Assertions.assertEquals(TagValue.noValue("Finance"), finance.backingTag().orElse(null));
+ Assertions.assertEquals(
+ finance, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ TagEntity storedTag = tagMetaService.getTagByIdentifier(financeTag.nameIdentifier());
+ Assertions.assertEquals(financeTag.id(), storedTag.id());
+ Assertions.assertEquals(TagValueConstraint.noValue(), storedTag.valueConstraint());
+ Assertions.assertEquals(financeTag, states.get(0).backingTag().orElse(null));
+ Assertions.assertTrue(states.get(0).backingTagBindings().isEmpty());
+
+ // A tag name in use fails the insert, and the domain is not inserted.
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ Assertions.assertThrows(
+ TagAlreadyExistsException.class,
+ () ->
+ domainMetaService.insertDomainWithNewBackingTag(
+ markets, newValuelessTag("Finance"), s -> {}));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+
+ // A domain name in use fails the insert before the new tag is written.
+ TagEntity marketsTag = newValuelessTag("Markets");
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () ->
+ domainMetaService.insertDomainWithNewBackingTag(
+ newDomain(METALAKE_NAME, "Finance", null), marketsTag, s -> {}));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> tagMetaService.getTagByIdentifier(marketsTag.nameIdentifier()));
+
+ // A failing check, which runs after the domain and the tag are written, rolls both back.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.insertDomainWithNewBackingTag(
+ markets,
+ marketsTag,
+ s -> {
+ throw new IllegalArgumentException("rejected");
+ }));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> tagMetaService.getTagByIdentifier(marketsTag.nameIdentifier()));
+ }
+
+ @TestTemplate
+ public void testUpdateSubDomainBackingTagPreservesParentInCheck() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ backend.insert(dept, false);
+ domainMetaService.insertDomainWithBackingTag(
+ newDomain(METALAKE_NAME, "Finance", null), TagValue.of("dept", "finance"), s -> {});
+ DomainEntity tax =
+ newDomain(METALAKE_NAME, "Tax", null).toBuilder().withParent("Finance").build();
+ domainMetaService.insertDomainWithBackingTag(tax, TagValue.of("dept", "tax"), s -> {});
+
+ // Changing, retaining and removing the binding all expose the current parent to the check.
+ for (TagValue backingTag :
+ new TagValue[] {TagValue.of("dept", "other"), TagValue.of("dept", "other"), null}) {
+ List<LockedDomainState> states = new ArrayList<>();
+ DomainEntity updated =
+ domainMetaService.updateDomainBackingTagAndGet(
+ tax.nameIdentifier(), backingTag, AUDIT_INFO, states::add);
+ Assertions.assertEquals(1, states.size());
+ Assertions.assertEquals("Finance", states.get(0).domain().parent().orElse(null));
+ // The parent entity is not locked or included for a backing tag update.
+ Assertions.assertFalse(states.get(0).parent().isPresent());
+ Assertions.assertEquals("Finance", updated.parent().orElse(null));
+ Assertions.assertEquals(
+ "Finance",
+ domainMetaService.getDomainByIdentifier(tax.nameIdentifier()).parent().orElse(null));
+ }
+ }
+
+ @TestTemplate
+ public void testUpdateDomainBackingTag() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ TagEntity region = newTag("region");
+ backend.insert(dept, false);
+ backend.insert(region, false);
+ List<LockedDomainState> inserts = new ArrayList<>();
+ domainMetaService.insertDomainWithBackingTag(
+ newDomain(METALAKE_NAME, "Finance", null), TagValue.of("dept", "finance"), inserts::add);
+ domainMetaService.insertDomainWithBackingTag(
+ newDomain(METALAKE_NAME, "Markets", null), TagValue.of("dept", "markets"), inserts::add);
+ DomainEntity finance = inserts.get(0).domain();
+ DomainEntity markets = inserts.get(1).domain();
+ AuditInfo modified =
+ AuditInfo.builder()
+ .withCreator("modifier")
+ .withCreateTime(Instant.now())
+ .withLastModifier("modifier")
+ .withLastModifiedTime(Instant.now())
+ .build();
+ List<LockedDomainState> states = new ArrayList<>();
+
+ // The check sees the domain as it is, with the new tag, which backs no domain yet.
+ DomainEntity updated =
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(), TagValue.noValue("region"), modified, states::add);
+ Assertions.assertEquals(TagValue.noValue("region"), updated.backingTag().orElse(null));
+ Assertions.assertEquals(
+ updated, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ Assertions.assertEquals(finance.auditInfo().creator(), updated.auditInfo().creator());
+ Assertions.assertEquals("modifier", updated.auditInfo().lastModifier());
+ LockedDomainState state = states.get(0);
+ Assertions.assertEquals(dept.id(), state.domain().backingTagId());
+ Assertions.assertEquals("finance", state.domain().backingTagValue());
+ Assertions.assertEquals(region.id(), state.backingTag().get().id());
+ Assertions.assertTrue(state.backingTagBindings().isEmpty());
+
+ // The bindings of the tag include the domain itself when the tag already backs it.
+ states.clear();
+ domainMetaService.updateDomainBackingTagAndGet(
+ markets.nameIdentifier(), TagValue.of("dept", "other"), modified, states::add);
+ Assertions.assertEquals(
+ Lists.newArrayList(markets.id()),
+ states.get(0).backingTagBindings().stream()
+ .map(DomainEntity::id)
+ .collect(Collectors.toList()));
+
+ // Setting the current backing tag writes nothing.
+ long version = selectDomainPO(markets.id()).currentVersion();
+ TagValue current = TagValue.of("dept", "other");
+ DomainEntity unchanged =
+ domainMetaService.updateDomainBackingTagAndGet(
+ markets.nameIdentifier(), current, modified, s -> {});
+ Assertions.assertEquals(current, unchanged.backingTag().orElse(null));
+ Assertions.assertEquals(version, selectDomainPO(markets.id()).currentVersion());
+
+ // Removing the backing tag locks no tag.
+ states.clear();
+ DomainEntity removed =
+ domainMetaService.updateDomainBackingTagAndGet(
+ markets.nameIdentifier(), null, modified, states::add);
+ Assertions.assertFalse(removed.backingTag().isPresent());
+ Assertions.assertNull(removed.backingTagId());
+ Assertions.assertFalse(states.get(0).backingTag().isPresent());
+
+ version = selectDomainPO(markets.id()).currentVersion();
+ Assertions.assertEquals(
+ removed,
+ domainMetaService.updateDomainBackingTagAndGet(
+ markets.nameIdentifier(), null, modified, s -> {}));
+ Assertions.assertEquals(version, selectDomainPO(markets.id()).currentVersion());
+
+ // A missing tag or a failing check changes nothing.
+ Assertions.assertThrows(
+ NoSuchTagException.class,
+ () ->
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(), TagValue.noValue("missing"), modified, s -> {}));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(),
+ TagValue.of("dept", "finance"),
+ modified,
+ s -> {
+ throw new IllegalArgumentException("rejected");
+ }));
+ Assertions.assertEquals(
+ TagValue.noValue("region"),
+ domainMetaService
+ .getDomainByIdentifier(finance.nameIdentifier())
+ .backingTag()
+ .orElse(null));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ domainMetaService.updateDomainBackingTagAndGet(
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "missing"), null, modified, s -> {}));
+ }
+
+ @TestTemplate
+ public void testBindingWaitsForConcurrentBinding() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ backend.insert(newTag("dept"), false);
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+
+ CountDownLatch bound = new CountDownLatch(1);
+ CountDownLatch allowCommit = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ Future<Throwable> updateResult =
+ executor.submit(
+ () -> {
+ try {
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(),
+ TagValue.of("dept", "x"),
+ AUDIT_INFO,
+ s -> {
+ bound.countDown();
+ await(allowCommit);
+ });
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+
+ try {
+ Assertions.assertTrue(bound.await(30, TimeUnit.SECONDS));
+ Future<Throwable> insertResult =
+ executor.submit(
+ () -> {
+ try {
+ domainMetaService.insertDomainWithBackingTag(
+ markets,
+ TagValue.of("dept", "x"),
+ s ->
+ Preconditions.checkArgument(
+ s.backingTagBindings().isEmpty(), "The tag is already bound"));
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+ // The update holds the tag row, so the insert waits and then sees the new binding.
+ Assertions.assertThrows(
+ TimeoutException.class, () -> insertResult.get(500, TimeUnit.MILLISECONDS));
+
+ allowCommit.countDown();
+ Assertions.assertNull(updateResult.get(30, TimeUnit.SECONDS));
+ Throwable insertFailure = insertResult.get(30, TimeUnit.SECONDS);
+ Assertions.assertTrue(
+ insertFailure instanceof IllegalArgumentException, String.valueOf(insertFailure));
+ } finally {
+ allowCommit.countDown();
+ executor.shutdownNow();
+ }
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+ }
+
+ @TestTemplate
+ public void testConcurrentNewBackingTagsWithTheSameName() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagMetaService tagMetaService = TagMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ TagEntity financeTag = newValuelessTag("shared_tag");
+ TagEntity marketsTag = newValuelessTag("shared_tag");
+
+ CountDownLatch written = new CountDownLatch(1);
+ CountDownLatch allowCommit = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ Future<Throwable> financeResult =
+ executor.submit(
+ () -> {
+ try {
+ domainMetaService.insertDomainWithNewBackingTag(
+ finance,
+ financeTag,
+ s -> {
+ written.countDown();
+ await(allowCommit);
+ });
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+
+ try {
+ Assertions.assertTrue(written.await(30, TimeUnit.SECONDS));
+ Future<Throwable> marketsResult =
+ executor.submit(
+ () -> {
+ try {
+ domainMetaService.insertDomainWithNewBackingTag(markets, marketsTag, s -> {});
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+ // The first insert holds the new tag name, so the second one waits for it and then fails.
+ Assertions.assertThrows(
+ TimeoutException.class, () -> marketsResult.get(500, TimeUnit.MILLISECONDS));
+
+ allowCommit.countDown();
+ Assertions.assertNull(financeResult.get(30, TimeUnit.SECONDS));
+ Throwable marketsFailure = marketsResult.get(30, TimeUnit.SECONDS);
+ Assertions.assertTrue(
+ marketsFailure instanceof TagAlreadyExistsException, String.valueOf(marketsFailure));
+ } finally {
+ allowCommit.countDown();
+ executor.shutdownNow();
+ }
+
+ // The tag is the first one's, and the second domain is rolled back with its tag.
+ Assertions.assertEquals(
+ financeTag.id(), tagMetaService.getTagByIdentifier(financeTag.nameIdentifier()).id());
+ Assertions.assertEquals(
+ financeTag.id(),
+ domainMetaService.getDomainByIdentifier(finance.nameIdentifier()).backingTagId());
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+ }
+
+ @TestTemplate
+ public void testBindingsAreReadUnderTheTagLock() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ backend.insert(dept, false);
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ domainMetaService.insertDomain(markets, false);
+ long metalakeId = MetalakeMetaService.getInstance().getMetalakeIdByName(METALAKE_NAME);
+ List<LockedDomainState> states = new ArrayList<>();
+
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () -> {
+ // An earlier read in the same session caches the bindings of the tag.
+ Assertions.assertTrue(
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.listDomainPOsByBackingTagId(metalakeId, dept.id()))
+ .isEmpty());
+ try {
+ Assertions.assertNotNull(
+ executor
+ .submit(
+ () ->
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(),
+ TagValue.of("dept", "x"),
+ AUDIT_INFO,
+ s -> {}))
+ .get(30, TimeUnit.SECONDS));
+ domainMetaService.updateDomainBackingTagAndGet(
+ markets.nameIdentifier(), TagValue.of("dept", "y"), AUDIT_INFO, states::add);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } finally {
+ executor.shutdownNow();
+ }
+
+ // The bindings read under the lock include the one committed after the cached read.
+ Assertions.assertEquals(
+ Lists.newArrayList(finance.id()),
+ states.get(0).backingTagBindings().stream()
+ .map(DomainEntity::id)
+ .collect(Collectors.toList()));
+ }
+
+ @TestTemplate
+ public void testBackingTagIsResolvedPastTheSessionCache() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ backend.insert(dept, false);
+ TagEntity recreated = newTag("dept");
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ long metalakeId = MetalakeMetaService.getInstance().getMetalakeIdByName(METALAKE_NAME);
+ List<LockedDomainState> states = new ArrayList<>();
+
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () -> {
+ // An earlier read in the same session caches the tag.
+ Assertions.assertEquals(
+ dept.id(),
+ SessionUtils.getWithoutCommit(
+ TagMetaMapper.class,
+ mapper -> mapper.selectTagMetaByMetalakeIdAndName(metalakeId, "dept"))
+ .getTagId());
+ try {
+ // The tag is dropped and created again under a new ID.
+ executor
+ .submit(
+ () -> {
+ Assertions.assertTrue(
+ TagMetaService.getInstance().deleteTag(dept.nameIdentifier()));
+ backend.insert(recreated, false);
+ return null;
+ })
+ .get(30, TimeUnit.SECONDS);
+ domainMetaService.updateDomainBackingTagAndGet(
+ finance.nameIdentifier(), TagValue.noValue("dept"), AUDIT_INFO, states::add);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ } finally {
+ executor.shutdownNow();
+ }
+
+ // The domain is bound to the tag that has the name now, not to the cached one.
+ Assertions.assertEquals(recreated.id(), states.get(0).backingTag().get().id());
+ Assertions.assertEquals(
+ recreated.id(),
+ domainMetaService
+ .getDomainByIdentifier(NameIdentifierUtil.ofDomain(METALAKE_NAME, "Finance"))
+ .backingTagId());
+ }
+
private DomainEntity newDomain(String metalake, String name, String comment) {
return DomainEntity.builder()
.withId(RandomIdGenerator.INSTANCE.nextId())
@@ -964,6 +1463,16 @@ public class TestDomainMetaService extends TestJDBCBackend {
.build();
}
+ private TagEntity newValuelessTag(String name) {
+ return TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME))
+ .withAllowedValues(new String[0])
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
private void insertPrivilegeOnDomain(long domainId) {
try (SqlSession sqlSession =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainRelService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainRelService.java
index 3e0bcca213..d5627babe9 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainRelService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainRelService.java
@@ -56,6 +56,7 @@ import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
@@ -812,20 +813,20 @@ public class TestDomainRelService extends TestJDBCBackend {
DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
List<LockedDomainState> states = new ArrayList<>();
- domainMetaService.insertDomain(finance, states::add);
+ DomainEntity inserted = insertDomainWithCheck(finance, states::add);
Assertions.assertEquals(
- finance, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ inserted, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
Assertions.assertEquals(1, states.size());
- Assertions.assertEquals(finance, states.get(0).domain());
+ Assertions.assertEquals(inserted, states.get(0).domain());
Assertions.assertFalse(states.get(0).parent().isPresent());
Assertions.assertTrue(states.get(0).subDomains().isEmpty());
// A domain with a parent is inserted together with its edge, and the check sees the parent.
DomainEntity trading = newDomain(METALAKE_NAME, "Trading", "Finance");
states.clear();
- domainMetaService.insertDomain(trading, states::add);
+ inserted = insertDomainWithCheck(trading, states::add);
Assertions.assertEquals(
- trading, domainMetaService.getDomainByIdentifier(trading.nameIdentifier()));
+ inserted, domainMetaService.getDomainByIdentifier(trading.nameIdentifier()));
Assertions.assertEquals(finance.id(), selectDomainRel(trading.id()).parentId());
LockedDomainState state = states.get(0);
Assertions.assertEquals(finance.id(), state.parent().get().id());
@@ -834,7 +835,7 @@ public class TestDomainRelService extends TestJDBCBackend {
// The check sees that the parent is itself a sub-domain.
DomainEntity desk = newDomain(METALAKE_NAME, "Desk", "Trading");
states.clear();
- domainMetaService.insertDomain(desk, states::add);
+ insertDomainWithCheck(desk, states::add);
Assertions.assertEquals("Finance", states.get(0).parent().get().parent().get());
// A failing check inserts neither the domain nor its edge.
@@ -842,7 +843,7 @@ public class TestDomainRelService extends TestJDBCBackend {
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
- domainMetaService.insertDomain(
+ insertDomainWithCheck(
rejected,
s -> {
throw new IllegalArgumentException("rejected");
@@ -854,17 +855,17 @@ public class TestDomainRelService extends TestJDBCBackend {
DomainEntity orphan = newDomain(METALAKE_NAME, "Orphan", "missing");
Assertions.assertThrows(
- NoSuchEntityException.class, () -> domainMetaService.insertDomain(orphan, s -> {}));
+ NoSuchEntityException.class, () -> insertDomainWithCheck(orphan, s -> {}));
Assertions.assertThrows(
NoSuchEntityException.class,
() -> domainMetaService.getDomainByIdentifier(orphan.nameIdentifier()));
Assertions.assertThrows(
EntityAlreadyExistsException.class,
- () -> domainMetaService.insertDomain(newDomain(METALAKE_NAME, "Finance", null), s -> {}));
+ () -> insertDomainWithCheck(newDomain(METALAKE_NAME, "Finance", null), s -> {}));
Assertions.assertThrows(
NoSuchEntityException.class,
- () -> domainMetaService.insertDomain(newDomain("missing_metalake", "X", null), s -> {}));
+ () -> insertDomainWithCheck(newDomain("missing_metalake", "X", null), s -> {}));
}
@TestTemplate
@@ -879,7 +880,7 @@ public class TestDomainRelService extends TestJDBCBackend {
Assertions.assertThrows(
IllegalStateException.class,
() ->
- domainMetaService.insertDomain(
+ insertDomainWithCheck(
rejected,
state -> {
throw new IllegalArgumentException("rejected");
@@ -1272,7 +1273,7 @@ public class TestDomainRelService extends TestJDBCBackend {
assertWaitsForDomainRow(
finance.id(),
() -> {
- domainMetaService.insertDomain(newDomain(METALAKE_NAME, "Tax", "Finance"), s -> {});
+ insertDomainWithCheck(newDomain(METALAKE_NAME, "Tax", "Finance"), s -> {});
return null;
});
assertWaitsForDomainRow(
@@ -1491,6 +1492,29 @@ public class TestDomainRelService extends TestJDBCBackend {
.build();
}
+ // Inserts a domain with a new backing tag named after its ID, and returns the domain as the check
+ // saw it, with its backing tag set.
+ private DomainEntity insertDomainWithCheck(DomainEntity domain, Consumer<LockedDomainState> check)
+ throws IOException {
+ TagEntity backingTag =
+ TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("tag_" + domain.id())
+ .withNamespace(NamespaceUtil.ofTag(domain.namespace().level(0)))
+ .withAllowedValues(new String[0])
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ DomainEntity[] checked = new DomainEntity[1];
+ domainMetaService.insertDomainWithNewBackingTag(
+ domain,
+ backingTag,
+ state -> {
+ check.accept(state);
+ checked[0] = state.domain();
+ });
+ return checked[0];
+ }
+
private void moveDomainRel(DomainEntity child, DomainEntity newParent) throws IOException {
domainRelService.updateDomainRel(
child.nameIdentifier(), newParent.nameIdentifier(), AUDIT_INFO);