World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14142] feat(server): Add schema-level Semantic Model metric discovery (#14143)
mchades3d3730db5dcc
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.javaindex 9a31583fb8..ceaf23ad57 100644--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java@@ -41,6 +41,37 @@ public interface SemanticModelCatalog {*/NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException;+ /**+ * Lists metric identifiers across the Semantic Models in a schema.+ *+ * <p>Results are sorted by containing model identifier and then case-sensitive metric name.+ * Catalog-scoped clients accept a schema namespace and return identifiers with namespace {@code+ * [schema, semanticModel]}; server-side operations use full namespaces.+ *+ * @param namespace The schema namespace.+ * @return The metric identifiers, or an empty array if there are none.+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws UnsupportedOperationException If metric listing is not supported.+ */+ default NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ throw new UnsupportedOperationException("Metric listing is not supported");+ }++ /**+ * Lists complete metric definitions across the Semantic Models in a schema.+ *+ * <p>Namespaces and ordering follow {@link #listMetrics(Namespace)}. Each result contains the+ * definition from its model's current committed version.+ *+ * @param namespace The schema namespace.+ * @return The metrics and their namespaces, or an empty array if there are none.+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws UnsupportedOperationException If metric info listing is not supported.+ */+ default SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ throw new UnsupportedOperationException("Metric info listing is not supported");+ }+/*** Loads a Semantic Model by identifier.*diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelMetric.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelMetric.javanew file mode 100644index 0000000000..e919a3a033--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelMetric.java@@ -0,0 +1,41 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.Evolving;++/** A metric's namespace and complete definition returned by schema-level discovery. */+@Evolving+public interface SemanticModelMetric {++ /**+ * Returns the metric namespace, whose last level is the containing Semantic Model.+ *+ * @return The full namespace, or the catalog-relative namespace for catalog-scoped clients.+ */+ Namespace namespace();++ /**+ * Returns the complete metric definition, including its name.+ *+ * @return The metric definition.+ */+ Metric metric();+}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.javaindex 490ebcf3a3..42230ee19d 100644--- a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java@@ -31,6 +31,15 @@ import org.junit.jupiter.api.Test;public class TestSemanticModelCatalog {+ @Test+ public void testMetricDiscoveryIsUnsupportedByDefault() {+ SemanticModelCatalog catalog = new ExistsOnlySemanticModelCatalog();+ assertThrows(+ UnsupportedOperationException.class, () -> catalog.listMetrics(Namespace.of("schema")));+ assertThrows(+ UnsupportedOperationException.class, () -> catalog.listMetricInfos(Namespace.of("schema")));+ }+@Testpublic void testSemanticModelExists() {SemanticModelCatalog catalog = new ExistsOnlySemanticModelCatalog();diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/MetricInfoListResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/MetricInfoListResponse.javanew file mode 100644index 0000000000..2383cfdab5--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/responses/MetricInfoListResponse.java@@ -0,0 +1,66 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.responses;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.ToString;+import org.apache.gravitino.dto.semantic.SemanticModelMetricDTO;++/** Response containing complete metrics discovered in a schema. */+@EqualsAndHashCode(callSuper = true)+@ToString+public class MetricInfoListResponse extends BaseResponse {++ @JsonProperty("metrics")+ private SemanticModelMetricDTO[] metrics;++ private MetricInfoListResponse() {+ super();+ }++ /**+ * Creates a response containing metric definitions and their namespaces.+ *+ * @param metrics The metric discovery results.+ */+ public MetricInfoListResponse(SemanticModelMetricDTO[] metrics) {+ super(0);+ this.metrics = metrics == null ? null : metrics.clone();+ }++ /**+ * Returns the metric discovery results.+ *+ * @return A copy of the result array.+ */+ public SemanticModelMetricDTO[] getMetrics() {+ return metrics == null ? null : metrics.clone();+ }++ @Override+ public void validate() throws IllegalArgumentException {+ super.validate();+ Preconditions.checkArgument(metrics != null, "metrics must not be null");+ for (SemanticModelMetricDTO metric : metrics) {+ Preconditions.checkArgument(metric != null, "metrics must not contain null");+ }+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelMetricDTO.java b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelMetricDTO.javanew file mode 100644index 0000000000..ee0f5151a6--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelMetricDTO.java@@ -0,0 +1,76 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.semantic;++import com.fasterxml.jackson.annotation.JsonProperty;+import com.fasterxml.jackson.annotation.JsonPropertyOrder;+import com.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.ToString;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.semantic.Metric;+import org.apache.gravitino.semantic.SemanticModelMetric;++/** A metric's containing namespace and complete definition for discovery responses. */+@EqualsAndHashCode+@ToString+@JsonPropertyOrder({"namespace", "metric"})+public class SemanticModelMetricDTO implements SemanticModelMetric {++ @JsonProperty("namespace")+ private String[] namespace;++ @JsonProperty("metric")+ private MetricDTO metric;++ private SemanticModelMetricDTO() {}++ /**+ * Creates a metric discovery DTO.+ *+ * @param namespace The namespace ending with the containing model's name.+ * @param metric The complete metric DTO.+ */+ public SemanticModelMetricDTO(Namespace namespace, MetricDTO metric) {+ Preconditions.checkArgument(namespace != null, "namespace must not be null");+ Preconditions.checkArgument(metric != null, "metric must not be null");+ this.namespace = namespace.levels();+ this.metric = metric;+ }++ @Override+ public Namespace namespace() {+ return Namespace.of(namespace);+ }++ @Override+ public Metric metric() {+ return metric.toMetric();+ }++ /**+ * Converts a decoded discovery result to its REST representation.+ *+ * @param info The metric discovery result.+ * @return The metric discovery DTO.+ */+ public static SemanticModelMetricDTO fromSemanticModelMetric(SemanticModelMetric info) {+ return new SemanticModelMetricDTO(info.namespace(), MetricDTO.fromMetric(info.metric()));+ }+}diff --git a/common/src/test/java/org/apache/gravitino/dto/responses/TestMetricInfoListResponse.java b/common/src/test/java/org/apache/gravitino/dto/responses/TestMetricInfoListResponse.javanew file mode 100644index 0000000000..63b5ee5b40--- /dev/null+++ b/common/src/test/java/org/apache/gravitino/dto/responses/TestMetricInfoListResponse.java@@ -0,0 +1,87 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.responses;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;++import com.fasterxml.jackson.databind.JsonNode;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.semantic.MetricDTO;+import org.apache.gravitino.dto.semantic.SemanticModelMetricDTO;+import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.junit.jupiter.api.Test;++public class TestMetricInfoListResponse {+ @Test+ void testRoundTripPreservesCompleteMetricAndNamespace() throws Exception {+ String json =+ """+ {"name":"收入.total","expression":{"dialects":[{"dialect":"ansi","expression":"SUM(orders.amount)"}]},+ "description":"Revenue","datatype":"Float","aiContext":{"instructions":"Use for revenue","extra":[1,"two"]},+ "customExtensions":[{"vendorName":"vendor","data":"[1,2]"}]}+ """;+ MetricDTO metric = JsonUtils.objectMapper().readValue(json, MetricDTO.class);+ Namespace namespace = Namespace.of("lake", "catalog", "schema", "model");+ SemanticModelMetricDTO source = new SemanticModelMetricDTO(namespace, metric);+ SemanticModelMetricDTO converted = SemanticModelMetricDTO.fromSemanticModelMetric(source);+ assertEquals(source.metric(), converted.metric());+ SemanticModelMetricDTO[] array = {converted};+ MetricInfoListResponse response = new MetricInfoListResponse(array);+ array[0] = null;+ response.getMetrics()[0] = null;+ response.validate();+ String serialized = JsonUtils.objectMapper().writeValueAsString(response);+ JsonNode body = JsonUtils.objectMapper().readTree(serialized);+ JsonNode info = body.path("metrics").get(0);+ assertEquals(2, info.size());+ assertFalse(info.has("name"));+ assertFalse(info.has("metricId"));+ assertEquals(JsonUtils.objectMapper().readTree(json), info.path("metric"));+ assertEquals(0, body.path("code").asInt());+ MetricInfoListResponse decoded =+ JsonUtils.objectMapper().readValue(serialized, MetricInfoListResponse.class);+ decoded.validate();+ SemanticModelMetric result = decoded.getMetrics()[0];+ assertEquals(namespace, result.namespace());+ assertEquals(metric.toMetric(), result.metric());+ String[] levels = result.namespace().levels();+ levels[0] = "changed";+ assertEquals(namespace, result.namespace());+ }++ @Test+ void testEmptyAndInvalidResponses() throws Exception {+ MetricInfoListResponse empty = new MetricInfoListResponse(new SemanticModelMetricDTO[0]);+ empty.validate();+ JsonNode json = JsonUtils.objectMapper().valueToTree(empty);+ assertEquals(0, json.path("metrics").size());+ assertArrayEquals(new SemanticModelMetricDTO[0], empty.getMetrics());+ assertThrows(IllegalArgumentException.class, new MetricInfoListResponse(null)::validate);+ assertThrows(+ IllegalArgumentException.class,+ new MetricInfoListResponse(new SemanticModelMetricDTO[] {null})::validate);+ MetricInfoListResponse missing =+ JsonUtils.objectMapper().readValue("{\"code\":0}", MetricInfoListResponse.class);+ assertThrows(IllegalArgumentException.class, missing::validate);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/EntityStore.java b/core/src/main/java/org/apache/gravitino/EntityStore.javaindex 4ed86ff207..b6ec539096 100644--- a/core/src/main/java/org/apache/gravitino/EntityStore.java+++ b/core/src/main/java/org/apache/gravitino/EntityStore.java@@ -30,10 +30,39 @@ import org.apache.commons.lang3.tuple.Pair;import org.apache.gravitino.Entity.EntityType;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.utils.Executable;public interface EntityStore extends Closeable {+ /**+ * Reads metric identifiers in a schema without loading complete Semantic Models.+ *+ * @param namespace The full schema namespace.+ * @return Metric identifiers from one consistent statement or read snapshot.+ * @throws NoSuchEntityException If the schema does not exist.+ * @throws IOException If the read fails.+ * @throws UnsupportedOperationException If metric discovery is not supported.+ */+ default List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {+ throw new UnsupportedOperationException("Metric listing is not supported");+ }++ /**+ * Reads complete metrics in a schema without loading unrelated definition fields.+ *+ * @param namespace The full schema namespace.+ * @return Decoded metrics from one consistent statement or read snapshot, without authorization+ * filtering.+ * @throws NoSuchEntityException If the schema does not exist.+ * @throws IOException If the read fails.+ * @throws UnsupportedOperationException If metric discovery is not supported.+ */+ default List<SemanticModelMetric> listSemanticModelMetricInfos(Namespace namespace)+ throws IOException {+ throw new UnsupportedOperationException("Metric info listing is not supported");+ }+/*** Initialize the entity store.*diff --git a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java b/core/src/main/java/org/apache/gravitino/audit/AuditLog.javaindex 3f6097b320..5dbf1bd2d2 100644--- a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java+++ b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java@@ -123,6 +123,10 @@ import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelEventimport org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelFailureEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosFailureEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelFailureEvent;import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;@@ -535,6 +539,10 @@ public interface AuditLog {LOAD_SEMANTIC_MODEL,LIST_SEMANTIC_MODEL,+ /** List identifiers of metrics contained in Semantic Models. */+ LIST_SEMANTIC_MODEL_METRIC,+ /** List complete metrics contained in Semantic Models. */+ LIST_SEMANTIC_MODEL_METRIC_INFOS,/** Import a Semantic Model from an Ossie document. */IMPORT_SEMANTIC_MODEL,/** Export a Semantic Model as an Ossie document. */@@ -662,6 +670,12 @@ public interface AuditLog {} else if (event instanceof ListSemanticModelEvent|| event instanceof ListSemanticModelFailureEvent) {return LIST_SEMANTIC_MODEL;+ } else if (event instanceof ListSemanticModelMetricEvent+ || event instanceof ListSemanticModelMetricFailureEvent) {+ return LIST_SEMANTIC_MODEL_METRIC;+ } else if (event instanceof ListSemanticModelMetricInfosEvent+ || event instanceof ListSemanticModelMetricInfosFailureEvent) {+ return LIST_SEMANTIC_MODEL_METRIC_INFOS;} else if (event instanceof ImportSemanticModelEvent|| event instanceof ImportSemanticModelFailureEvent) {return IMPORT_SEMANTIC_MODEL;diff --git a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.javaindex 2255998d3e..6f70be2f43 100644--- a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java+++ b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java@@ -201,6 +201,10 @@ public class CompatibilityUtils {.put(OperationType.DROP_SEMANTIC_MODEL, Operation.DROP_SEMANTIC_MODEL).put(OperationType.LOAD_SEMANTIC_MODEL, Operation.LOAD_SEMANTIC_MODEL).put(OperationType.LIST_SEMANTIC_MODEL, Operation.LIST_SEMANTIC_MODEL)+ .put(OperationType.LIST_SEMANTIC_MODEL_METRIC, Operation.LIST_SEMANTIC_MODEL_METRIC)+ .put(+ OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS,+ Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS).put(OperationType.IMPORT_SEMANTIC_MODEL, Operation.IMPORT_SEMANTIC_MODEL).put(OperationType.EXPORT_SEMANTIC_MODEL, Operation.EXPORT_SEMANTIC_MODEL).put(OperationType.REGISTER_FUNCTION, Operation.REGISTER_FUNCTION)diff --git a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.javaindex cc331d737c..0ee792b161 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java@@ -21,6 +21,8 @@ package org.apache.gravitino.catalog;import com.google.common.base.Preconditions;import java.io.IOException;import java.time.Instant;+import java.util.Arrays;+import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -42,6 +44,7 @@ import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelCatalog;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.utils.PrincipalUtils;@@ -86,6 +89,40 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {}}+ @Override+ public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ try {+ return store.listSemanticModelMetrics(namespace).stream()+ .sorted(+ Comparator.comparing(+ (NameIdentifier ident) -> ident.namespace().levels(), Arrays::compare)+ .thenComparing(NameIdentifier::name))+ .toArray(NameIdentifier[]::new);+ } catch (NoSuchEntityException e) {+ throw new NoSuchSchemaException(e, "Schema %s does not exist", namespace);+ } catch (IOException e) {+ throw new RuntimeException(+ "Failed to list Semantic Model metrics in namespace " + namespace, e);+ }+ }++ @Override+ public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ try {+ return store.listSemanticModelMetricInfos(namespace).stream()+ .sorted(+ Comparator.comparing(+ (SemanticModelMetric info) -> info.namespace().levels(), Arrays::compare)+ .thenComparing(info -> info.metric().name()))+ .toArray(SemanticModelMetric[]::new);+ } catch (NoSuchEntityException e) {+ throw new NoSuchSchemaException(e, "Schema %s does not exist", namespace);+ } catch (IOException e) {+ throw new RuntimeException(+ "Failed to list Semantic Model metrics in namespace " + namespace, e);+ }+ }+@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {try {diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.javaindex 6e3dee8adb..70f35bba18 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java@@ -35,6 +35,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;/** Dispatches schema-scoped Semantic Model operations through the server pipeline. */public interface SemanticModelDispatcher {@@ -48,6 +49,24 @@ public interface SemanticModelDispatcher {*/NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException;+ /**+ * Lists metric identifiers across the live Semantic Models in a schema.+ *+ * @param namespace The full schema namespace.+ * @return Metric identifiers, ordered by model identifier and case-sensitive metric name.+ * @throws NoSuchSchemaException If the schema does not exist.+ */+ NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException;++ /**+ * Lists complete metrics across the live Semantic Models in a schema.+ *+ * @param namespace The full schema namespace.+ * @return Decoded metrics, ordered by model identifier and case-sensitive metric name.+ * @throws NoSuchSchemaException If the schema does not exist.+ */+ SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException;+/*** Loads a Semantic Model by identifier.*diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.javaindex e9df9ba6da..efad41cba1 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java@@ -39,6 +39,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;/** Normalizes Semantic Model parents while retaining Gravitino-owned model naming rules. */public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher {@@ -63,6 +64,16 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcherreturn dispatcher.listSemanticModels(normalizeParentForLookup(namespace));}+ @Override+ public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ return dispatcher.listMetrics(normalizeParentForLookup(namespace));+ }++ @Override+ public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ return dispatcher.listMetricInfos(normalizeParentForLookup(namespace));+ }+@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {return dispatcher.loadSemanticModel(normalizeForLookup(ident));diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.javaindex 07fe80c3f2..1457751a06 100644--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java@@ -41,6 +41,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.semantic.SemanticModelPropertiesMetadata;import org.apache.gravitino.storage.IdGenerator;@@ -88,6 +89,20 @@ public class SemanticModelOperationDispatcher extends OperationDispatcherreturn managedOperations.listSemanticModels(namespace);}+ @Override+ public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ checkRelationalCatalog(namespace);+ schemaDispatcher.loadSchema(NameIdentifier.of(namespace.levels()));+ return managedOperations.listMetrics(namespace);+ }++ @Override+ public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ checkRelationalCatalog(namespace);+ schemaDispatcher.loadSchema(NameIdentifier.of(namespace.levels()));+ return managedOperations.listMetricInfos(namespace);+ }+@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {checkRelationalCatalog(ident.namespace());diff --git a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.javaindex f8f4249cf7..7cc805b223 100644--- a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java@@ -38,6 +38,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.PrincipalUtils;@@ -68,6 +69,16 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {return dispatcher.listSemanticModels(namespace);}+ @Override+ public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ return dispatcher.listMetrics(namespace);+ }++ @Override+ public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ return dispatcher.listMetricInfos(namespace);+ }+@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {return dispatcher.loadSemanticModel(ident);diff --git a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.javaindex fa4a344425..71caf9c974 100644--- a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java@@ -47,6 +47,12 @@ import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelFailuimport org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelPreEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosPreEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricPreEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelPreEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelFailureEvent;@@ -57,6 +63,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.utils.PrincipalUtils;/**@@ -96,6 +103,37 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {}}+ @Override+ public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {+ String user = PrincipalUtils.getCurrentUserName();+ eventBus.dispatchEvent(new ListSemanticModelMetricPreEvent(user, namespace));+ try {+ NameIdentifier[] metrics = dispatcher.listMetrics(namespace);+ eventBus.dispatchEvent(+ new ListSemanticModelMetricEvent(user, namespace, metrics != null ? metrics.length : -1));+ return metrics;+ } catch (Exception e) {+ eventBus.dispatchEvent(new ListSemanticModelMetricFailureEvent(user, namespace, e));+ throw e;+ }+ }++ @Override+ public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {+ String user = PrincipalUtils.getCurrentUserName();+ eventBus.dispatchEvent(new ListSemanticModelMetricInfosPreEvent(user, namespace));+ try {+ SemanticModelMetric[] metrics = dispatcher.listMetricInfos(namespace);+ eventBus.dispatchEvent(+ new ListSemanticModelMetricInfosEvent(+ user, namespace, metrics != null ? metrics.length : -1));+ return metrics;+ } catch (Exception e) {+ eventBus.dispatchEvent(new ListSemanticModelMetricInfosFailureEvent(user, namespace, e));+ throw e;+ }+ }+@Overridepublic SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {String user = PrincipalUtils.getCurrentUserName();diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.javaindex 46017e4a8a..46f351919f 100644--- a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java@@ -216,6 +216,10 @@ public enum OperationType {DROP_SEMANTIC_MODEL,LOAD_SEMANTIC_MODEL,LIST_SEMANTIC_MODEL,+ /** List identifiers of metrics contained in Semantic Models. */+ LIST_SEMANTIC_MODEL_METRIC,+ /** List complete metrics contained in Semantic Models. */+ LIST_SEMANTIC_MODEL_METRIC_INFOS,/** Import a Semantic Model from an Ossie document. */IMPORT_SEMANTIC_MODEL,/** Export a Semantic Model as an Ossie document. */diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricEvent.javanew file mode 100644index 0000000000..92854fc1bb--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricEvent.java@@ -0,0 +1,70 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.ListEvent;+import org.apache.gravitino.listener.api.event.OperationType;++/**+ * Successful list-metrics event. Like {@link+ * org.apache.gravitino.listener.api.event.view.ListViewEvent}, listed identifiers are not stored on+ * the event.+ */+@DeveloperApi+public final class ListSemanticModelMetricEvent extends SemanticModelEvent implements ListEvent {+ private final Namespace namespace;+ private final int metricCount;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricEvent}.+ *+ * @param user The username of the individual who initiated the metric listing.+ * @param namespace The namespace from which Semantic Model metrics were listed.+ * @param metricCount The number of Semantic Model metrics returned by the list operation.+ */+ public ListSemanticModelMetricEvent(String user, Namespace namespace, int metricCount) {+ super(user, NameIdentifier.of(namespace.levels()));+ this.namespace = namespace;+ this.metricCount = metricCount;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ /** {@inheritDoc} */+ @Override+ public int resultCount() {+ return metricCount;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricFailureEvent.javanew file mode 100644index 0000000000..3b5020cb11--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricFailureEvent.java@@ -0,0 +1,58 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.OperationType;++/** Failure event for listing Semantic Model metrics. */+@DeveloperApi+public final class ListSemanticModelMetricFailureEvent extends SemanticModelFailureEvent {+ private final Namespace namespace;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricFailureEvent}.+ *+ * @param user The username of the individual who initiated the metric listing.+ * @param namespace The namespace from which Semantic Model metrics were listed.+ * @param exception The exception that caused the failure.+ */+ public ListSemanticModelMetricFailureEvent(+ String user, Namespace namespace, Exception exception) {+ super(user, NameIdentifier.of(namespace.levels()), exception);+ this.namespace = namespace;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosEvent.javanew file mode 100644index 0000000000..3f5ad973cf--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosEvent.java@@ -0,0 +1,72 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.ListEvent;+import org.apache.gravitino.listener.api.event.OperationType;++/**+ * Successful list-metrics event. Like {@link+ * org.apache.gravitino.listener.api.event.view.ListViewEvent}, listed identifiers are not stored on+ * the event.+ */+@DeveloperApi+public final class ListSemanticModelMetricInfosEvent extends SemanticModelEvent+ implements ListEvent {+ private final Namespace namespace;+ private final int metricCount;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricInfosEvent}.+ *+ * @param user The username of the individual who initiated the metric info listing.+ * @param namespace The namespace from which complete Semantic Model metrics were listed.+ * @param metricCount The number of complete Semantic Model metrics returned by the list+ * operation.+ */+ public ListSemanticModelMetricInfosEvent(String user, Namespace namespace, int metricCount) {+ super(user, NameIdentifier.of(namespace.levels()));+ this.namespace = namespace;+ this.metricCount = metricCount;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ /** {@inheritDoc} */+ @Override+ public int resultCount() {+ return metricCount;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosFailureEvent.javanew file mode 100644index 0000000000..b7857462fe--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosFailureEvent.java@@ -0,0 +1,58 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.OperationType;++/** Failure event for listing complete Semantic Model metrics. */+@DeveloperApi+public final class ListSemanticModelMetricInfosFailureEvent extends SemanticModelFailureEvent {+ private final Namespace namespace;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricInfosFailureEvent}.+ *+ * @param user The username of the individual who initiated the metric info listing.+ * @param namespace The namespace from which complete Semantic Model metrics were listed.+ * @param exception The exception that caused the failure.+ */+ public ListSemanticModelMetricInfosFailureEvent(+ String user, Namespace namespace, Exception exception) {+ super(user, NameIdentifier.of(namespace.levels()), exception);+ this.namespace = namespace;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosPreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosPreEvent.javanew file mode 100644index 0000000000..2ddfc0d2d4--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricInfosPreEvent.java@@ -0,0 +1,56 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.OperationType;++/** Pre-event before listing the complete Semantic Model metrics in a namespace. */+@DeveloperApi+public final class ListSemanticModelMetricInfosPreEvent extends SemanticModelPreEvent {+ private final Namespace namespace;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricInfosPreEvent}.+ *+ * @param user The username of the individual who initiated the metric info listing.+ * @param namespace The namespace from which complete Semantic Model metrics are listed.+ */+ public ListSemanticModelMetricInfosPreEvent(String user, Namespace namespace) {+ super(user, NameIdentifier.of(namespace.levels()));+ this.namespace = namespace;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricPreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricPreEvent.javanew file mode 100644index 0000000000..d74fe88371--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelMetricPreEvent.java@@ -0,0 +1,56 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.listener.api.event.semantic;++import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.DeveloperApi;+import org.apache.gravitino.listener.api.event.OperationType;++/** Pre-event before listing the Semantic Model metrics in a namespace. */+@DeveloperApi+public final class ListSemanticModelMetricPreEvent extends SemanticModelPreEvent {+ private final Namespace namespace;++ /**+ * Constructs an instance of {@code ListSemanticModelMetricPreEvent}.+ *+ * @param user The username of the individual who initiated the metric listing.+ * @param namespace The namespace from which Semantic Model metrics are listed.+ */+ public ListSemanticModelMetricPreEvent(String user, Namespace namespace) {+ super(user, NameIdentifier.of(namespace.levels()));+ this.namespace = namespace;+ }++ /**+ * Returns the namespace associated with this event.+ *+ * @return The namespace.+ */+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public OperationType operationType() {+ return OperationType.LIST_SEMANTIC_MODEL_METRIC;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/semantic/ImmutableSemanticModelMetric.java b/core/src/main/java/org/apache/gravitino/semantic/ImmutableSemanticModelMetric.javanew file mode 100644index 0000000000..1a6d7856e4--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/semantic/ImmutableSemanticModelMetric.java@@ -0,0 +1,49 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import java.util.Objects;+import org.apache.gravitino.Namespace;++/** An immutable, decoded metric discovery result. */+public final class ImmutableSemanticModelMetric implements SemanticModelMetric {+ private final Namespace namespace;+ private final Metric metric;++ /**+ * Creates a metric discovery result.+ *+ * @param namespace The namespace ending with the containing model's name.+ * @param metric The complete metric definition.+ */+ public ImmutableSemanticModelMetric(Namespace namespace, Metric metric) {+ this.namespace = Objects.requireNonNull(namespace, "namespace must not be null");+ this.metric = Objects.requireNonNull(metric, "metric must not be null");+ }++ @Override+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public Metric metric() {+ return metric;+ }+}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.javaindex e25d804426..e7f8a1b48a 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@@ -71,6 +71,7 @@ import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterFactory;import org.apache.gravitino.storage.relational.database.H2Database;import org.apache.gravitino.storage.relational.po.cache.OperateType;@@ -90,6 +91,7 @@ import org.apache.gravitino.storage.relational.service.PolicyTagRelService;import org.apache.gravitino.storage.relational.service.RoleMetaService;import org.apache.gravitino.storage.relational.service.SchemaMetaService;import org.apache.gravitino.storage.relational.service.SemanticModelMetaService;+import org.apache.gravitino.storage.relational.service.SemanticModelMetricService;import org.apache.gravitino.storage.relational.service.StatisticMetaService;import org.apache.gravitino.storage.relational.service.TableColumnMetaService;import org.apache.gravitino.storage.relational.service.TableMetaService;@@ -127,6 +129,17 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationCSQLExceptionConverterFactory.initConverter(config);}+ @Override+ public List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {+ return SemanticModelMetricService.getInstance().listMetrics(namespace);+ }++ @Override+ public List<SemanticModelMetric> listSemanticModelMetricInfos(Namespace namespace)+ throws IOException {+ return SemanticModelMetricService.getInstance().listMetricInfos(namespace);+ }+@Overridepublic <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Entity.EntityType entityType, boolean allFields) throws IOException {diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.javaindex fa64b409dc..f9eab1cd8f 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java@@ -35,10 +35,39 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.SupportsRelationOperations;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.semantic.SemanticModelMetric;/** Interface defining the operations for a Relation Backend. */public interface RelationalBackend extends Closeable, SupportsRelationOperations {+ /**+ * Reads metric identifiers in a schema without loading complete Semantic Models.+ *+ * @param namespace The full schema namespace.+ * @return Metric identifiers from one consistent statement or read snapshot.+ * @throws NoSuchEntityException If the schema does not exist.+ * @throws IOException If the read fails.+ * @throws UnsupportedOperationException If metric discovery is not supported.+ */+ default List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {+ throw new UnsupportedOperationException("Metric listing is not supported");+ }++ /**+ * Reads complete metrics in a schema without loading unrelated definition fields.+ *+ * @param namespace The full schema namespace.+ * @return Decoded metrics from one consistent statement or read snapshot, without authorization+ * filtering.+ * @throws NoSuchEntityException If the schema does not exist.+ * @throws IOException If the read fails.+ * @throws UnsupportedOperationException If metric discovery is not supported.+ */+ default List<SemanticModelMetric> listSemanticModelMetricInfos(Namespace namespace)+ throws IOException {+ throw new UnsupportedOperationException("Metric info listing is not supported");+ }+/*** Initializes the Relational Backend environment with the provided configuration.*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.javaindex 2a596f8f54..3844759c8a 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@@ -61,6 +61,7 @@ import org.apache.gravitino.exceptions.OptimisticLockException;import org.apache.gravitino.meta.SchemaEntity;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.utils.Executable;@@ -207,6 +208,17 @@ public class RelationalEntityStore}}+ @Override+ public List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {+ return backend.listSemanticModelMetrics(namespace);+ }++ @Override+ public List<SemanticModelMetric> listSemanticModelMetricInfos(Namespace namespace)+ throws IOException {+ return backend.listSemanticModelMetricInfos(namespace);+ }+@Overridepublic <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Class<E> type, Entity.EntityType entityType) throws IOException {diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.javaindex 3bf1319c92..549172b535 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java@@ -19,6 +19,7 @@package org.apache.gravitino.storage.relational.mapper;import java.util.List;+import org.apache.gravitino.storage.relational.po.SemanticModelMetricListingPO;import org.apache.gravitino.storage.relational.po.SemanticModelMetricPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;@@ -31,6 +32,22 @@ public interface SemanticModelMetricMapper {/** The metric identity table name. */String TABLE_NAME = "semantic_model_metric_meta";+ /** Lists live metric and model names in one statement without reading snapshots. */+ @SelectProvider(type = SemanticModelMetricSQLProviderFactory.class, method = "listMetricNames")+ List<SemanticModelMetricListingPO> listMetricNames(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName);++ /** Lists model names and current metric arrays in one statement without reading identities. */+ @SelectProvider(+ type = SemanticModelMetricSQLProviderFactory.class,+ method = "listMetricSnapshots")+ List<SemanticModelMetricListingPO> listMetricSnapshots(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName);+/** Inserts new metric identities in one statement. */@InsertProvider(type = SemanticModelMetricSQLProviderFactory.class,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.javaindex 4649b0bcfd..17052032a7 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java@@ -46,6 +46,22 @@ public class SemanticModelMetricSQLProviderFactory {return PROVIDERS.get(JDBCBackendType.fromString(databaseId));}+ /** Lists live metric and model names in one statement without reading snapshots. */+ public static String listMetricNames(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName) {+ return getProvider().listMetricNames(metalakeName, catalogName, schemaName);+ }++ /** Lists model names and current metric arrays in one statement without reading identities. */+ public static String listMetricSnapshots(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName) {+ return getProvider().listMetricSnapshots(metalakeName, catalogName, schemaName);+ }+/** Returns SQL for inserting new metric identities in one statement. */public static String insertSemanticModelMetrics(@Param("metrics") List<SemanticModelMetricPO> metricPOs) {diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.javaindex f424a31fb9..6267b2f78d 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java@@ -21,12 +21,43 @@ package org.apache.gravitino.storage.relational.mapper.provider.base;import static org.apache.gravitino.storage.relational.mapper.SemanticModelMetricMapper.TABLE_NAME;import java.util.List;+import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;+import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;import org.apache.gravitino.storage.relational.po.SemanticModelMetricPO;import org.apache.ibatis.annotations.Param;/** Provides MySQL-compatible SQL for Semantic Model metric identities. */public class SemanticModelMetricBaseSQLProvider {+ /** Returns a single statement selecting live metric names and their current model names. */+ public String listMetricNames(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName) {+ return discoverySelect(+ "metric.metric_name AS metricName",+ "LEFT JOIN "+ + TABLE_NAME+ + " metric"+ + " ON model.semantic_model_id = metric.semantic_model_id AND metric.deleted_at = 0");+ }++ /** Returns a single statement selecting only metrics from each current model snapshot. */+ public String listMetricSnapshots(+ @Param("metalakeName") String metalakeName,+ @Param("catalogName") String catalogName,+ @Param("schemaName") String schemaName) {+ return discoverySelect(+ "snapshot.version, snapshot.metrics",+ "LEFT JOIN "+ + SemanticModelMetaMapper.VERSION_TABLE_NAME+ + " snapshot"+ + " ON model.semantic_model_id = snapshot.semantic_model_id"+ + " AND model.current_version = snapshot.version AND snapshot.deleted_at = 0");+ }+/** Returns SQL for inserting new identities in one statement. */public String insertSemanticModelMetrics(@Param("metrics") List<SemanticModelMetricPO> metricPOs) {@@ -102,6 +133,31 @@ public class SemanticModelMetricBaseSQLProvider {+ " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000";}+ private String discoverySelect(String projection, String metricJoin) {+ // Left joins distinguish an empty schema from a missing schema. They also keep a live model+ // whose current snapshot is missing, so detailed discovery fails instead of silently omitting+ // it.+ return """+ SELECT schema_meta.schema_id AS schemaId, model.semantic_model_id AS semanticModelId,+ model.semantic_model_name AS semanticModelName, %s+ FROM %s metalake+ INNER JOIN %s catalog ON metalake.metalake_id = catalog.metalake_id+ AND catalog.catalog_name = #{catalogName} AND catalog.deleted_at = 0+ LEFT JOIN %s schema_meta ON catalog.catalog_id = schema_meta.catalog_id+ AND schema_meta.schema_name = #{schemaName} AND schema_meta.deleted_at = 0+ LEFT JOIN %s model ON schema_meta.schema_id = model.schema_id AND model.deleted_at = 0+ %s+ WHERE metalake.metalake_name = #{metalakeName} AND metalake.deleted_at = 0+ """+ .formatted(+ projection,+ MetalakeMetaMapper.TABLE_NAME,+ CatalogMetaMapper.TABLE_NAME,+ SchemaMetaMapper.TABLE_NAME,+ SemanticModelMetaMapper.TABLE_NAME,+ metricJoin);+ }+private String softDeleteBy(String condition) {return "UPDATE "+ TABLE_NAMEdiff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.javanew file mode 100644index 0000000000..c75086233f--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java@@ -0,0 +1,36 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.storage.relational.po;++import javax.annotation.Nullable;+import lombok.Getter;++/** A projection for schema-level metric discovery without unrelated definition fields. */+@Getter+public class SemanticModelMetricListingPO {+ @Nullable private Long schemaId;+ @Nullable private Long semanticModelId;+ @Nullable private String semanticModelName;+ @Nullable private String metricName;+ @Nullable private Integer version;+ @Nullable private String metrics;++ /** Creates an empty projection for MyBatis. */+ public SemanticModelMetricListingPO() {}+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.javanew file mode 100644index 0000000000..ad3d342c57--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java@@ -0,0 +1,136 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.storage.relational.service;++import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.List;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.semantic.MetricDTO;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.metrics.Monitored;+import org.apache.gravitino.semantic.ImmutableSemanticModelMetric;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetricMapper;+import org.apache.gravitino.storage.relational.po.SemanticModelMetricListingPO;+import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;+import org.apache.gravitino.utils.NamespaceUtil;++/** Reads schema-level metrics from committed relational state without loading complete models. */+public class SemanticModelMetricService {+ private static final SemanticModelMetricService INSTANCE = new SemanticModelMetricService();++ private SemanticModelMetricService() {}++ /** Returns the metric discovery service. */+ public static SemanticModelMetricService getInstance() {+ return INSTANCE;+ }++ /**+ * Lists live metric identifiers without reading definition snapshots.+ *+ * @param namespace The full schema namespace.+ * @return Metric identifiers with the containing model as the last namespace level.+ * @throws NoSuchEntityException If the schema or an ancestor does not exist.+ */+ @Monitored(+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,+ baseMetricName = "listSemanticModelMetrics")+ public List<NameIdentifier> listMetrics(Namespace namespace) {+ return read(namespace, false).stream()+ .filter(po -> po.getMetricName() != null)+ .map(+ po ->+ NameIdentifier.of(+ metricNamespace(namespace, po.getSemanticModelName()), po.getMetricName()))+ .toList();+ }++ /**+ * Lists complete metrics from current snapshots, decoding every array before returning.+ *+ * @param namespace The full schema namespace.+ * @return Decoded metrics and their containing namespaces.+ * @throws NoSuchEntityException If the schema or an ancestor does not exist.+ * @throws IllegalStateException If a current snapshot is missing or metrics cannot be decoded.+ */+ @Monitored(+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,+ baseMetricName = "listSemanticModelMetricInfos")+ public List<SemanticModelMetric> listMetricInfos(Namespace namespace) {+ List<SemanticModelMetric> results = new ArrayList<>();+ for (SemanticModelMetricListingPO po : read(namespace, true)) {+ if (po.getSemanticModelId() == null) {+ continue;+ }+ Preconditions.checkState(+ po.getVersion() != null,+ "Missing current snapshot for Semantic Model %s",+ po.getSemanticModelId());+ if (po.getMetrics() == null) {+ continue;+ }+ Namespace metricNamespace = metricNamespace(namespace, po.getSemanticModelName());+ try {+ MetricDTO[] metrics =+ JsonUtils.anyFieldMapper().readValue(po.getMetrics(), MetricDTO[].class);+ Preconditions.checkArgument(metrics != null, "metrics JSON must be an array");+ for (MetricDTO metric : metrics) {+ Preconditions.checkArgument(metric != null, "metrics must not contain null");+ results.add(new ImmutableSemanticModelMetric(metricNamespace, metric.toMetric()));+ }+ } catch (JsonProcessingException | IllegalArgumentException e) {+ throw new IllegalStateException(+ "Failed to decode metrics for Semantic Model "+ + NameIdentifier.of(metricNamespace.levels()),+ e);+ }+ }+ return results;+ }++ private List<SemanticModelMetricListingPO> read(Namespace namespace, boolean details) {+ NamespaceUtil.checkSemanticModel(namespace);+ String schemaName =+ HierarchicalSchemaUtil.logicalToPhysical(+ namespace.level(2), HierarchicalSchemaUtil.schemaSeparator());+ List<SemanticModelMetricListingPO> rows =+ SessionUtils.getWithoutCommit(+ SemanticModelMetricMapper.class,+ mapper ->+ details+ ? mapper.listMetricSnapshots(namespace.level(0), namespace.level(1), schemaName)+ : mapper.listMetricNames(namespace.level(0), namespace.level(1), schemaName));+ if (rows.isEmpty() || rows.get(0) == null || rows.get(0).getSchemaId() == null) {+ throw new NoSuchEntityException("Schema %s does not exist", namespace);+ }+ return rows;+ }++ private Namespace metricNamespace(Namespace schema, String modelName) {+ return Namespace.of(schema.level(0), schema.level(1), schema.level(2), modelName);+ }+}diff --git a/core/src/test/java/org/apache/gravitino/audit/TestOperation.java b/core/src/test/java/org/apache/gravitino/audit/TestOperation.javaindex 12d61beedc..2847f23713 100644--- a/core/src/test/java/org/apache/gravitino/audit/TestOperation.java+++ b/core/src/test/java/org/apache/gravitino/audit/TestOperation.java@@ -122,6 +122,10 @@ import org.apache.gravitino.listener.api.event.semantic.DropSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.DropSemanticModelFailureEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosFailureEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelEvent;import org.apache.gravitino.listener.api.event.semantic.LoadSemanticModelFailureEvent;import org.apache.gravitino.listener.api.event.server.AuthorizationDenialFailureEvent;@@ -576,6 +580,34 @@ public class TestOperation {AuditLog.Operation.LIST_PARTITION, AuditLog.Operation.fromEvent(listPartitionFailureEvent));}+ /** Verifies audit operation mapping for successful and failed metric identifier listings. */+ @Test+ public void testListSemanticModelMetricOperation() {+ Namespace namespace = Namespace.of("metalake", "catalog", "schema");+ Event event = new ListSemanticModelMetricEvent(USER, namespace, 2);+ Assertions.assertEquals(+ AuditLog.Operation.LIST_SEMANTIC_MODEL_METRIC, AuditLog.Operation.fromEvent(event));++ Event failureEvent = new ListSemanticModelMetricFailureEvent(USER, namespace, new Exception());+ Assertions.assertEquals(+ AuditLog.Operation.LIST_SEMANTIC_MODEL_METRIC, AuditLog.Operation.fromEvent(failureEvent));+ }++ /** Verifies audit operation mapping for successful and failed complete metric listings. */+ @Test+ public void testListSemanticModelMetricInfosOperation() {+ Namespace namespace = Namespace.of("metalake", "catalog", "schema");+ Event event = new ListSemanticModelMetricInfosEvent(USER, namespace, 2);+ Assertions.assertEquals(+ AuditLog.Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS, AuditLog.Operation.fromEvent(event));++ Event failureEvent =+ new ListSemanticModelMetricInfosFailureEvent(USER, namespace, new Exception());+ Assertions.assertEquals(+ AuditLog.Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS,+ AuditLog.Operation.fromEvent(failureEvent));+ }+@Testpublic void testLoadOperation() {Event loadMetalakeEvent = new LoadMetalakeEvent(USER, metalakeIdentifier, metalakeInfo);diff --git a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.javaindex 3e23ce2be9..1ae072da2c 100644--- a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java+++ b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java@@ -204,6 +204,8 @@ public class TestCompatibilityUtils {{OperationType.DROP_SEMANTIC_MODEL, Operation.DROP_SEMANTIC_MODEL},{OperationType.LOAD_SEMANTIC_MODEL, Operation.LOAD_SEMANTIC_MODEL},{OperationType.LIST_SEMANTIC_MODEL, Operation.LIST_SEMANTIC_MODEL},+ {OperationType.LIST_SEMANTIC_MODEL_METRIC, Operation.LIST_SEMANTIC_MODEL_METRIC},+ {OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS, Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS},{OperationType.IMPORT_SEMANTIC_MODEL, Operation.IMPORT_SEMANTIC_MODEL},{OperationType.EXPORT_SEMANTIC_MODEL, Operation.EXPORT_SEMANTIC_MODEL},{OperationType.REGISTER_FUNCTION, Operation.REGISTER_FUNCTION},diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelMetricDispatchers.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelMetricDispatchers.javanew file mode 100644index 0000000000..8c4e50279b--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelMetricDispatchers.java@@ -0,0 +1,98 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.util.List;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.secret.SecretManager;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.junit.jupiter.api.Test;++public class TestSemanticModelMetricDispatchers {+ private static final Namespace NAMESPACE = Namespace.of("lake", "catalog", "schema");++ @Test+ void testStoreFailuresAreNotConvertedToEmptyResults() throws Exception {+ EntityStore store = mock(EntityStore.class);+ ManagedSemanticModelOperations operations =+ new ManagedSemanticModelOperations(+ store, RandomIdGenerator.INSTANCE, (ident, definition) -> {});+ when(store.listSemanticModelMetrics(NAMESPACE)).thenThrow(new NoSuchEntityException("missing"));+ when(store.listSemanticModelMetricInfos(NAMESPACE))+ .thenThrow(new NoSuchEntityException("missing"));+ assertThrows(NoSuchSchemaException.class, () -> operations.listMetrics(NAMESPACE));+ assertThrows(NoSuchSchemaException.class, () -> operations.listMetricInfos(NAMESPACE));+ IOException failure = new IOException("storage unavailable");+ doThrow(failure).when(store).listSemanticModelMetrics(NAMESPACE);+ doThrow(failure).when(store).listSemanticModelMetricInfos(NAMESPACE);+ assertSame(+ failure,+ assertThrows(RuntimeException.class, () -> operations.listMetrics(NAMESPACE)).getCause());+ assertSame(+ failure,+ assertThrows(RuntimeException.class, () -> operations.listMetricInfos(NAMESPACE))+ .getCause());+ }++ @Test+ void testOperationDispatcherChecksCatalogAndSchemaBeforeReading() throws Exception {+ EntityStore store = mock(EntityStore.class);+ CatalogManager catalogs = mock(CatalogManager.class);+ SchemaDispatcher schemas = mock(SchemaDispatcher.class);+ Catalog catalog = mock(Catalog.class);+ when(catalogs.loadCatalog(NameIdentifier.of("lake", "catalog"))).thenReturn(catalog);+ SemanticModelOperationDispatcher dispatcher =+ new SemanticModelOperationDispatcher(+ catalogs, schemas, store, RandomIdGenerator.INSTANCE, mock(SecretManager.class));+ when(catalog.type()).thenReturn(Catalog.Type.FILESET);+ assertThrows(UnsupportedOperationException.class, () -> dispatcher.listMetrics(NAMESPACE));+ assertThrows(UnsupportedOperationException.class, () -> dispatcher.listMetricInfos(NAMESPACE));+ verifyNoInteractions(store, schemas);+ when(catalog.type()).thenReturn(Catalog.Type.RELATIONAL);+ when(schemas.loadSchema(NameIdentifier.of(NAMESPACE.levels())))+ .thenThrow(new NoSuchSchemaException("missing"));+ assertThrows(NoSuchSchemaException.class, () -> dispatcher.listMetrics(NAMESPACE));+ assertThrows(NoSuchSchemaException.class, () -> dispatcher.listMetricInfos(NAMESPACE));+ verifyNoInteractions(store);+ doReturn(null).when(schemas).loadSchema(NameIdentifier.of(NAMESPACE.levels()));+ when(store.listSemanticModelMetrics(NAMESPACE)).thenReturn(List.of());+ when(store.listSemanticModelMetricInfos(NAMESPACE)).thenReturn(List.of());+ assertArrayEquals(new NameIdentifier[0], dispatcher.listMetrics(NAMESPACE));+ assertArrayEquals(new SemanticModelMetric[0], dispatcher.listMetricInfos(NAMESPACE));+ verify(store).listSemanticModelMetrics(NAMESPACE);+ verify(store).listSemanticModelMetricInfos(NAMESPACE);+ }+}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.javaindex 0f62ca6e09..911198b435 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java@@ -46,6 +46,7 @@ import org.apache.gravitino.semantic.OssieFormat;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;@@ -74,6 +75,21 @@ public class TestSemanticModelNormalizeDispatcher {dispatcher = new SemanticModelNormalizeDispatcher(delegate, catalogManager);}+ @Test+ public void testMetricDiscoveryNormalizesOnlyParents() {+ NameIdentifier[] names = {+ NameIdentifier.of(Namespace.of("metalake", "catalog", "MIXEDSCHEMA", "SalesModel"), "Revenue")+ };+ SemanticModelMetric[] infos = {mock(SemanticModelMetric.class)};+ when(delegate.listMetrics(NORMALIZED_NAMESPACE)).thenReturn(names);+ when(delegate.listMetricInfos(NORMALIZED_NAMESPACE)).thenReturn(infos);+ assertSame(names, dispatcher.listMetrics(INPUT_NAMESPACE));+ assertSame(infos, dispatcher.listMetricInfos(INPUT_NAMESPACE));+ verify(delegate).listMetrics(NORMALIZED_NAMESPACE);+ verify(delegate).listMetricInfos(NORMALIZED_NAMESPACE);+ verifyNoMoreInteractions(delegate);+ }+@Testpublic void testParentUsesCatalogCapabilityButModelUsesStableRules() {SemanticModelDefinition definition = definition();diff --git a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.javaindex 737bd1343a..4c33fe169f 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java@@ -46,6 +46,7 @@ import org.apache.gravitino.connector.capability.CapabilityResult;import org.apache.gravitino.semantic.SemanticModel;import org.apache.gravitino.semantic.SemanticModelChange;import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;import org.mockito.InOrder;@@ -57,6 +58,29 @@ public class TestSemanticModelHookDispatcher {private static final NameIdentifier IDENT =NameIdentifier.of("metalake1", "catalog1", "schema1", "sales_model");+ @Test+ public void testMetricDiscoveryForwardsBothModes() {+ SemanticModelDispatcher delegate = Mockito.mock(SemanticModelDispatcher.class);+ SemanticModelHookDispatcher hook = new SemanticModelHookDispatcher(delegate, () -> null);+ NameIdentifier[] names = {+ NameIdentifier.of(+ Namespace.of(+ IDENT.namespace().level(0),+ IDENT.namespace().level(1),+ IDENT.namespace().level(2),+ IDENT.name()),+ "metric")+ };+ SemanticModelMetric[] infos = {Mockito.mock(SemanticModelMetric.class)};+ Mockito.when(delegate.listMetrics(IDENT.namespace())).thenReturn(names);+ Mockito.when(delegate.listMetricInfos(IDENT.namespace())).thenReturn(infos);+ assertSame(names, hook.listMetrics(IDENT.namespace()));+ assertSame(infos, hook.listMetricInfos(IDENT.namespace()));+ Mockito.verify(delegate).listMetrics(IDENT.namespace());+ Mockito.verify(delegate).listMetricInfos(IDENT.namespace());+ Mockito.verifyNoMoreInteractions(delegate);+ }+@Testpublic void testCreateSemanticModelSetsCreatorAsOwner() throws Exception {GravitinoEnv env = GravitinoEnv.getInstance();diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelMetricEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelMetricEvent.javanew file mode 100644index 0000000000..001fa64f1f--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelMetricEvent.java@@ -0,0 +1,142 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.listener.api.event;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.util.List;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.SemanticModelDispatcher;+import org.apache.gravitino.listener.EventBus;+import org.apache.gravitino.listener.SemanticModelEventDispatcher;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosFailureEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricInfosPreEvent;+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricPreEvent;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.utils.PrincipalUtils;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;+import org.mockito.MockedStatic;++public class TestSemanticModelMetricEvent {+ private static final Namespace NAMESPACE = Namespace.of("lake", "catalog", "schema");++ @ParameterizedTest+ @CsvSource({"false,-1", "false,0", "false,2", "true,-1", "true,0", "true,2"})+ void testSuccessEvents(boolean details, int count) {+ EventBus bus = mock(EventBus.class);+ SemanticModelDispatcher delegate = mock(SemanticModelDispatcher.class);+ SemanticModelEventDispatcher dispatcher = new SemanticModelEventDispatcher(bus, delegate);+ NameIdentifier[] names = count < 0 ? null : new NameIdentifier[count];+ SemanticModelMetric[] infos = count < 0 ? null : new SemanticModelMetric[count];+ when(delegate.listMetrics(NAMESPACE)).thenReturn(names);+ when(delegate.listMetricInfos(NAMESPACE)).thenReturn(infos);+ try (MockedStatic<PrincipalUtils> principal = mockStatic(PrincipalUtils.class)) {+ principal.when(PrincipalUtils::getCurrentUserName).thenReturn("initiator", "changed");+ if (details) assertSame(infos, dispatcher.listMetricInfos(NAMESPACE));+ else assertSame(names, dispatcher.listMetrics(NAMESPACE));+ principal.verify(PrincipalUtils::getCurrentUserName);+ }+ List<BaseEvent> events = events(bus, details);+ assertEquals(+ details ? ListSemanticModelMetricInfosEvent.class : ListSemanticModelMetricEvent.class,+ events.get(1).getClass());+ assertEquals(count, ((ListEvent) events.get(1)).resultCount());+ assertEquals(OperationStatus.SUCCESS, ((Event) events.get(1)).operationStatus());+ assertEquals(+ NAMESPACE,+ details+ ? ((ListSemanticModelMetricInfosEvent) events.get(1)).namespace()+ : ((ListSemanticModelMetricEvent) events.get(1)).namespace());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testFailuresAreReportedAndRethrown(boolean details) {+ EventBus bus = mock(EventBus.class);+ SemanticModelDispatcher delegate = mock(SemanticModelDispatcher.class);+ SemanticModelEventDispatcher dispatcher = new SemanticModelEventDispatcher(bus, delegate);+ IllegalStateException failure = new IllegalStateException("decode failed");+ when(delegate.listMetrics(NAMESPACE)).thenThrow(failure);+ when(delegate.listMetricInfos(NAMESPACE)).thenThrow(failure);+ try (MockedStatic<PrincipalUtils> principal = mockStatic(PrincipalUtils.class)) {+ principal.when(PrincipalUtils::getCurrentUserName).thenReturn("initiator");+ assertSame(+ failure,+ assertThrows(+ IllegalStateException.class,+ () -> {+ if (details) dispatcher.listMetricInfos(NAMESPACE);+ else dispatcher.listMetrics(NAMESPACE);+ }));+ }+ List<BaseEvent> events = events(bus, details);+ assertEquals(+ details+ ? ListSemanticModelMetricInfosFailureEvent.class+ : ListSemanticModelMetricFailureEvent.class,+ events.get(1).getClass());+ assertSame(failure, ((FailureEvent) events.get(1)).exception());+ assertEquals(OperationStatus.FAILURE, ((Event) events.get(1)).operationStatus());+ assertEquals(+ NAMESPACE,+ details+ ? ((ListSemanticModelMetricInfosFailureEvent) events.get(1)).namespace()+ : ((ListSemanticModelMetricFailureEvent) events.get(1)).namespace());+ }++ private List<BaseEvent> events(EventBus bus, boolean details) {+ ArgumentCaptor<BaseEvent> captor = ArgumentCaptor.forClass(BaseEvent.class);+ verify(bus, times(2)).dispatchEvent(captor.capture());+ List<BaseEvent> events = captor.getAllValues();+ assertEquals(+ details+ ? ListSemanticModelMetricInfosPreEvent.class+ : ListSemanticModelMetricPreEvent.class,+ events.get(0).getClass());+ assertEquals(+ NAMESPACE,+ details+ ? ((ListSemanticModelMetricInfosPreEvent) events.get(0)).namespace()+ : ((ListSemanticModelMetricPreEvent) events.get(0)).namespace());+ for (BaseEvent event : events) {+ assertEquals("initiator", event.user());+ assertEquals(NameIdentifier.of(NAMESPACE.levels()), event.identifier());+ assertEquals(+ details+ ? OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS+ : OperationType.LIST_SEMANTIC_MODEL_METRIC,+ event.operationType());+ }+ return events;+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.javanew file mode 100644index 0000000000..c6190e916a--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java@@ -0,0 +1,393 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.storage.relational.service;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.CALLS_REAL_METHODS;+import static org.mockito.Mockito.mockStatic;++import java.io.IOException;+import java.sql.PreparedStatement;+import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import javax.annotation.Nullable;+import org.apache.commons.lang3.reflect.FieldUtils;+import org.apache.gravitino.Entity;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.ManagedSemanticModelOperations;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.meta.SemanticModelEntity;+import org.apache.gravitino.semantic.AIContext;+import org.apache.gravitino.semantic.CustomExtension;+import org.apache.gravitino.semantic.DataType;+import org.apache.gravitino.semantic.Dataset;+import org.apache.gravitino.semantic.DialectExpression;+import org.apache.gravitino.semantic.Expression;+import org.apache.gravitino.semantic.Metric;+import org.apache.gravitino.semantic.SemanticModelDefinition;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.RelationalEntityStore;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.apache.gravitino.utils.HierarchicalSchemaUtil;+import org.apache.ibatis.session.SqlSession;+import org.junit.jupiter.api.TestTemplate;+import org.mockito.MockedStatic;++/** Verifies metric projections and committed read consistency on every supported database. */+public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {++ @TestTemplate+ void testEmptyMissingAndSchemaIsolation() throws Exception {+ Namespace namespace = parents();+ ManagedSemanticModelOperations operations = operations();+ assertEquals(0, operations.listMetrics(namespace).length);+ assertEquals(0, operations.listMetricInfos(namespace).length);+ backend.insert(model(namespace, "absent", (Metric[]) null), false);+ backend.insert(model(namespace, "empty"), false);+ backend.insert(model(parents(), "elsewhere", metric("revenue")), false);+ assertEquals(0, operations.listMetrics(namespace).length);+ assertEquals(0, operations.listMetricInfos(namespace).length);+ Namespace missing = Namespace.of(namespace.level(0), namespace.level(1), "missing");+ assertThrows(NoSuchSchemaException.class, () -> operations.listMetrics(missing));+ assertThrows(NoSuchSchemaException.class, () -> operations.listMetricInfos(missing));+ assertThrows(+ IllegalArgumentException.class,+ () -> backend.listSemanticModelMetrics(Namespace.of("invalid")));+ }++ @TestTemplate+ void testCompleteMetricsStructuredOrderingAndNames() throws Exception {+ Namespace namespace = parents();+ Metric[] metrics = {+ metric("z"), metric("revenue"), metric("Revenue"), metric("收入.'"), metric("x".repeat(300))+ };+ backend.insert(model(namespace, "a-b", metric("a")), false);+ backend.insert(model(namespace, "a", metrics), false);+ ManagedSemanticModelOperations operations = operations();+ NameIdentifier[] names = operations.listMetrics(namespace);+ List<String> sorted = Arrays.stream(metrics).map(Metric::name).sorted().toList();+ for (int i = 0; i < sorted.size(); i++) {+ assertEquals(identifier(namespace, "a", sorted.get(i)), names[i]);+ }+ assertEquals(identifier(namespace, "a-b", "a"), names[5]);+ SemanticModelMetric[] infos = operations.listMetricInfos(namespace);+ assertArrayEquals(names, identifiers(infos));+ for (SemanticModelMetric info : infos) {+ assertEquals(metric(info.metric().name()), info.metric());+ }+ }++ @TestTemplate+ void testHierarchicalSchemaPreservesLogicalNamespace() throws Exception {+ Namespace parent = parents();+ String schema = "outer" + HierarchicalSchemaUtil.schemaSeparator() + "inner";+ createAndInsertSchema(parent.level(0), parent.level(1), schema);+ Namespace namespace = Namespace.of(parent.level(0), parent.level(1), schema);+ backend.insert(model(namespace, "sales", metric("Revenue")), false);+ NameIdentifier expected = identifier(namespace, "sales", "Revenue");+ assertEquals(List.of(expected), backend.listSemanticModelMetrics(namespace));+ assertEquals(expected, identifiers(operations().listMetricInfos(namespace))[0]);+ }++ @TestTemplate+ void testRenameReplacementDropAndRecreationReadOnlyCurrentState() throws Exception {+ Namespace namespace = parents();+ SemanticModelEntity original = model(namespace, "before", metric("removed"), metric("kept"));+ backend.insert(original, false);+ SemanticModelEntity replacement = copy(original, "after", metric("added"), metric("kept"));+ backend.update(original.nameIdentifier(), original.type(), old -> replacement);+ ManagedSemanticModelOperations operations = operations();+ NameIdentifier[] expected = {+ identifier(namespace, "after", "added"), identifier(namespace, "after", "kept")+ };+ assertArrayEquals(expected, operations.listMetrics(namespace));+ assertArrayEquals(expected, identifiers(operations.listMetricInfos(namespace)));+ backend.delete(replacement.nameIdentifier(), replacement.type(), false);+ assertEquals(0, operations.listMetrics(namespace).length);+ assertEquals(0, operations.listMetricInfos(namespace).length);+ backend.insert(model(namespace, "after", metric("new")), false);+ backend.hardDeleteLegacyData(Entity.EntityType.SEMANTIC_MODEL, Long.MAX_VALUE);+ assertArrayEquals(+ new NameIdentifier[] {identifier(namespace, "after", "new")},+ operations.listMetrics(namespace));+ assertArrayEquals(+ operations.listMetrics(namespace), identifiers(operations.listMetricInfos(namespace)));+ }++ @TestTemplate+ void testDiscoveryDoesNotDecodeUnrelatedFields() throws Exception {+ Namespace namespace = parents();+ SemanticModelEntity model = model(namespace, "sales", metric("revenue"));+ backend.insert(model, false);+ execute(+ "UPDATE semantic_model_version_info SET datasets = ?, relationships = ?, ai_context = ?, custom_extensions = ? WHERE semantic_model_id = ?",+ "invalid",+ "invalid",+ "invalid",+ "invalid",+ model.id());+ assertThrows(RuntimeException.class, () -> backend.get(model.nameIdentifier(), model.type()));+ assertEquals(+ List.of(identifier(namespace, "sales", "revenue")),+ backend.listSemanticModelMetrics(namespace));+ assertEquals(+ metric("revenue"), backend.listSemanticModelMetricInfos(namespace).get(0).metric());+ }++ @TestTemplate+ void testNamesDoNotReadSnapshotsAndDetailsDoNotReadIdentities() throws Exception {+ Namespace namespace = parents();+ SemanticModelEntity model = model(namespace, "sales", metric("revenue"));+ backend.insert(model, false);+ execute("DELETE FROM semantic_model_metric_meta WHERE semantic_model_id = ?", model.id());+ assertTrue(backend.listSemanticModelMetrics(namespace).isEmpty());+ assertEquals(+ metric("revenue"), backend.listSemanticModelMetricInfos(namespace).get(0).metric());+ SemanticModelEntity independent = model(namespace, "names_only", metric("count"));+ backend.insert(independent, false);+ execute(+ "DELETE FROM semantic_model_version_info WHERE semantic_model_id = ?", independent.id());+ assertEquals(+ List.of(identifier(namespace, "names_only", "count")),+ backend.listSemanticModelMetrics(namespace));+ assertThrows(+ IllegalStateException.class, () -> backend.listSemanticModelMetricInfos(namespace));+ }++ @TestTemplate+ void testMalformedMetricsFailWholeDetailedRead() throws Exception {+ Namespace namespace = parents();+ backend.insert(model(namespace, "valid", metric("good")), false);+ SemanticModelEntity broken = model(namespace, "broken", metric("bad"));+ backend.insert(broken, false);+ for (String json : List.of("not-json", "null", "{}", "[null]", "[{\"name\":\"bad\"}]")) {+ execute(+ "UPDATE semantic_model_version_info SET metrics = ? WHERE semantic_model_id = ?",+ json,+ broken.id());+ assertEquals(2, backend.listSemanticModelMetrics(namespace).size());+ assertThrows(+ IllegalStateException.class, () -> backend.listSemanticModelMetricInfos(namespace), json);+ }+ }++ @TestTemplate+ void testParentDeletionDoesNotExposeRetiredMetrics() throws Exception {+ Namespace unrelated = parents();+ backend.insert(model(unrelated, "other", metric("live")), false);+ for (Entity.EntityType type :+ List.of(Entity.EntityType.SCHEMA, Entity.EntityType.CATALOG, Entity.EntityType.METALAKE)) {+ Namespace namespace = parents();+ backend.insert(model(namespace, "sales", metric("revenue")), false);+ NameIdentifier parent =+ type == Entity.EntityType.SCHEMA+ ? NameIdentifier.of(namespace.levels())+ : type == Entity.EntityType.CATALOG+ ? NameIdentifier.of(namespace.level(0), namespace.level(1))+ : NameIdentifier.of(namespace.level(0));+ backend.delete(parent, type, true);+ assertThrows(NoSuchEntityException.class, () -> backend.listSemanticModelMetrics(namespace));+ assertThrows(+ NoSuchEntityException.class, () -> backend.listSemanticModelMetricInfos(namespace));+ assertEquals(1, backend.listSemanticModelMetrics(unrelated).size());+ assertEquals(1, backend.listSemanticModelMetricInfos(unrelated).size());+ }+ }++ @TestTemplate+ void testReadsDuringReplaceAndRenameSeeOnlyCommittedState() throws Exception {+ for (boolean rollback : List.of(false, true)) {+ Namespace namespace = parents();+ SemanticModelEntity original = model(namespace, "before", metric("before"));+ backend.insert(original, false);+ SemanticModelEntity replacement = copy(original, "after", metric("after"));+ CountDownLatch staged = new CountDownLatch(1);+ CountDownLatch finish = new CountDownLatch(1);+ ExecutorService executor = Executors.newSingleThreadExecutor();+ try {+ Future<?> writer =+ executor.submit(+ () -> {+ try (MockedStatic<SessionUtils> sessions =+ mockStatic(SessionUtils.class, CALLS_REAL_METHODS)) {+ sessions+ .when(+ () ->+ SessionUtils.doWithoutCommit(+ eq(SemanticModelVersionInfoMapper.class), any()))+ .thenAnswer(+ invocation -> {+ staged.countDown();+ assertTrue(finish.await(30, TimeUnit.SECONDS));+ if (rollback) throw new IllegalStateException("Injected rollback");+ return invocation.callRealMethod();+ });+ if (rollback) {+ assertThrows(+ IllegalStateException.class,+ () ->+ backend.update(+ original.nameIdentifier(), original.type(), old -> replacement));+ } else {+ backend.update(+ original.nameIdentifier(), original.type(), old -> replacement);+ }+ }+ return null;+ });+ assertTrue(staged.await(30, TimeUnit.SECONDS));+ // The writer has updated the name, version pointer, and identities, but has not committed.+ assertArrayEquals(+ new NameIdentifier[] {identifier(namespace, "before", "before")},+ operations().listMetrics(namespace));+ assertArrayEquals(+ new NameIdentifier[] {identifier(namespace, "before", "before")},+ identifiers(operations().listMetricInfos(namespace)));+ finish.countDown();+ writer.get(30, TimeUnit.SECONDS);+ String committed = rollback ? "before" : "after";+ assertArrayEquals(+ new NameIdentifier[] {identifier(namespace, committed, committed)},+ operations().listMetrics(namespace));+ assertArrayEquals(+ new NameIdentifier[] {identifier(namespace, committed, committed)},+ identifiers(operations().listMetricInfos(namespace)));+ } finally {+ finish.countDown();+ executor.shutdownNow();+ assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));+ }+ }+ }++ private ManagedSemanticModelOperations operations() throws IllegalAccessException {+ RelationalEntityStore store = new RelationalEntityStore();+ FieldUtils.writeField(store, "backend", backend, true);+ return new ManagedSemanticModelOperations(+ store, RandomIdGenerator.INSTANCE, (ident, definition) -> {});+ }++ private Namespace parents() throws IOException {+ String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId());+ String metalake = "discovery_metalake_" + suffix;+ String catalog = "discovery_catalog_" + suffix;+ createAndInsertMakeLake(metalake);+ createAndInsertCatalog(metalake, catalog);+ createAndInsertSchema(metalake, catalog, "schema");+ return Namespace.of(metalake, catalog, "schema");+ }++ private static SemanticModelEntity model(+ Namespace namespace, String name, @Nullable Metric... metrics) {+ return SemanticModelEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName(name)+ .withNamespace(namespace)+ .withAuditInfo(AUDIT_INFO)+ .withProperties(Map.of())+ .withDefinition(+ SemanticModelDefinition.builder()+ .withDatasets(+ new Dataset[] {+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of("sales", "orders"))+ .build()+ })+ .withMetrics(metrics)+ .build())+ .build();+ }++ private static SemanticModelEntity copy(+ SemanticModelEntity original, String name, Metric... metrics) {+ return SemanticModelEntity.builder()+ .withId(original.id())+ .withName(name)+ .withNamespace(original.namespace())+ .withAuditInfo(AUDIT_INFO)+ .withProperties(Map.of())+ .withDefinition(+ SemanticModelDefinition.builder()+ .withDatasets(original.definition().datasets())+ .withMetrics(metrics)+ .build())+ .build();+ }++ private static Metric metric(String name) {+ return Metric.builder()+ .withName(name)+ .withDescription("A complete metric")+ .withExpression(+ Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder()+ .withDialect("ansi")+ .withExpression("SUM(orders.amount)")+ .build()+ })+ .build())+ .withDatatype(DataType.FLOAT)+ .withAIContext(AIContext.of("Use this metric"))+ .withCustomExtensions(+ new CustomExtension[] {+ CustomExtension.builder().withVendorName("vendor").withData("{\"key\":1}").build()+ })+ .build();+ }++ private static NameIdentifier identifier(Namespace namespace, String model, String metric) {+ return NameIdentifier.of(+ Namespace.of(namespace.level(0), namespace.level(1), namespace.level(2), model), metric);+ }++ private static NameIdentifier[] identifiers(SemanticModelMetric[] metrics) {+ return Arrays.stream(metrics)+ .map(info -> NameIdentifier.of(info.namespace(), info.metric().name()))+ .toArray(NameIdentifier[]::new);+ }++ private static void execute(String sql, Object... args) throws Exception {+ try (SqlSession session =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ PreparedStatement statement = session.getConnection().prepareStatement(sql)) {+ for (int i = 0; i < args.length; i++) statement.setObject(i + 1, args[i]);+ statement.executeUpdate();+ }+ }+}diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yamlindex fb426a9a8d..67bd9ee69d 100644--- a/docs/open-api/openapi.yaml+++ b/docs/open-api/openapi.yaml@@ -168,6 +168,9 @@ paths:/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/views/{view}:$ref: "./views.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1schemas~1%7Bschema%7D~1views~1%7Bview%7D"+ /metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-model-metrics:+ $ref: "./semantic-models.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1schemas~1%7Bschema%7D~1semantic-model-metrics"+/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models:$ref: "./semantic-models.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1schemas~1%7Bschema%7D~1semantic-models"diff --git a/docs/open-api/semantic-models.yaml b/docs/open-api/semantic-models.yamlindex 81b8eb0441..906716f5f8 100644--- a/docs/open-api/semantic-models.yaml+++ b/docs/open-api/semantic-models.yaml@@ -19,6 +19,48 @@paths:+ /metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-model-metrics:+ parameters:+ - $ref: "./openapi.yaml#/components/parameters/metalake"+ - $ref: "./openapi.yaml#/components/parameters/catalog"+ - $ref: "./openapi.yaml#/components/parameters/schema"+ get:+ tags:+ - semantic-model+ summary: List metrics across Semantic Models+ description: >-+ Lists metrics in the current committed definitions of live Semantic Models in a schema.+ Supported only for relational catalogs. With details=false (the default), returns metric+ identifiers; with details=true, returns complete metric definitions and their namespaces.+ Namespaces contain [metalake, catalog, schema, semanticModel]. Both modes require schema+ access and include only metrics whose containing model is visible under the existing+ Semantic Model listing rules. Results are sorted by structured model identifier and then+ case-sensitive metric name. Models without metrics contribute no entries. Empty results+ contain an empty identifiers or metrics array. Storage or metric decoding failures fail+ the entire request, including decoding failures in models that would be filtered out.+ operationId: listSemanticModelMetrics+ parameters:+ - name: details+ in: query+ required: false+ description: Whether to return complete metric definitions instead of identifiers+ schema:+ type: boolean+ default: false+ responses:+ "200":+ $ref: "#/components/responses/SemanticModelMetricListResponse"+ "400":+ $ref: "#/components/responses/SemanticModelBadRequestResponse"+ "403":+ $ref: "#/components/responses/SemanticModelForbiddenResponse"+ "404":+ $ref: "#/components/responses/SemanticModelParentNotFoundResponse"+ "501":+ $ref: "#/components/responses/SemanticModelUnsupportedCatalogResponse"+ "5XX":+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"+/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models:parameters:- $ref: "./openapi.yaml#/components/parameters/metalake"@@ -297,6 +339,60 @@ paths:components:schemas:+ SemanticModelMetric:+ type: object+ description: The namespace and complete definition of a discovered metric+ required:+ - namespace+ - metric+ properties:+ namespace:+ type: array+ description: Full namespace [metalake, catalog, schema, semanticModel]+ minItems: 4+ maxItems: 4+ items:+ type: string+ minLength: 1+ metric:+ $ref: "#/components/schemas/Metric"+ additionalProperties: false++ MetricIdentifierListResponse:+ type: object+ description: Metric identifiers returned when details is false+ required:+ - code+ - identifiers+ properties:+ code:+ type: integer+ format: int32+ enum: [0]+ identifiers:+ type: array+ description: Identifiers with namespace [metalake, catalog, schema, semanticModel]+ items:+ $ref: "./openapi.yaml#/components/schemas/NameIdentifier"+ additionalProperties: false++ MetricInfoListResponse:+ type: object+ description: Complete metrics returned when details is true+ required:+ - code+ - metrics+ properties:+ code:+ type: integer+ format: int32+ enum: [0]+ metrics:+ type: array+ items:+ $ref: "#/components/schemas/SemanticModelMetric"+ additionalProperties: false+AIContext:description: Additional context for AI tools, encoded as exactly one string or object valueoneOf:@@ -1094,6 +1190,35 @@ components:}responses:+ SemanticModelMetricListResponse:+ description: Metric identifiers or complete metric definitions, according to details+ content:+ application/vnd.gravitino.v1+json:+ schema:+ oneOf:+ - $ref: "#/components/schemas/MetricIdentifierListResponse"+ - $ref: "#/components/schemas/MetricInfoListResponse"+ examples:+ Identifiers:+ summary: details=false+ value:+ code: 0+ identifiers:+ - namespace: [lake, sales, mart, sales_model]+ name: total_revenue+ Definitions:+ summary: details=true+ value:+ code: 0+ metrics:+ - namespace: [lake, sales, mart, sales_model]+ metric:+ name: total_revenue+ expression:+ dialects:+ - dialect: ANSI_SQL+ expression: SUM(orders.amount)+SemanticModelListResponse:description: Returns the Semantic Model identifiers in the schemacontent:diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.javaindex e9d0395aff..3af44ce85b 100644--- a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java@@ -82,6 +82,7 @@ import org.apache.gravitino.server.web.rest.PolicyOperations;import org.apache.gravitino.server.web.rest.RoleOperations;import org.apache.gravitino.server.web.rest.SchemaOperations;import org.apache.gravitino.server.web.rest.SecretsProviderOperations;+import org.apache.gravitino.server.web.rest.SemanticModelMetricOperations;import org.apache.gravitino.server.web.rest.SemanticModelOperations;import org.apache.gravitino.server.web.rest.StatisticOperations;import org.apache.gravitino.server.web.rest.TableOperations;@@ -116,6 +117,7 @@ public class GravitinoInterceptionService implements InterceptionService {ModelOperations.class.getName(),FunctionOperations.class.getName(),SemanticModelOperations.class.getName(),+ SemanticModelMetricOperations.class.getName(),TopicOperations.class.getName(),FilesetOperations.class.getName(),BulkOperations.class.getName(),diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java b/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.javaindex 04f8e26de7..947aeaef5c 100644--- a/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java@@ -37,6 +37,8 @@ public enum OperationType {SET,REGISTER, // An operation to register a modelLIST_VERSIONS, // An operation to list versions of a model+ /** An operation to list metrics contained in Semantic Models. */+ LIST_SEMANTIC_MODEL_METRICS,LINK, // An operation to link a version to a modelRUN, // An operation to run a jobCANCEL, // An operation to cancel a jobdiff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelMetricOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelMetricOperations.javanew file mode 100644index 0000000000..6caecee5ae--- /dev/null+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelMetricOperations.java@@ -0,0 +1,157 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.server.web.rest;++import com.codahale.metrics.annotation.ResponseMetered;+import com.codahale.metrics.annotation.Timed;+import java.util.Arrays;+import java.util.HashSet;+import java.util.Set;+import javax.inject.Inject;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.DefaultValue;+import javax.ws.rs.GET;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.Response;+import org.apache.gravitino.Entity;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.SemanticModelDispatcher;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.MetricInfoListResponse;+import org.apache.gravitino.dto.semantic.SemanticModelMetricDTO;+import org.apache.gravitino.metrics.MetricNames;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;+import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;+import org.apache.gravitino.server.web.Utils;+import org.apache.gravitino.utils.NamespaceUtil;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/** REST discovery of metrics contained in the Semantic Models of a schema. */+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-model-metrics")+public class SemanticModelMetricOperations {+ private static final Logger LOG = LoggerFactory.getLogger(SemanticModelMetricOperations.class);++ private final SemanticModelDispatcher dispatcher;+ @Context private HttpServletRequest httpRequest;++ /**+ * Creates schema-level metric discovery operations.+ *+ * @param dispatcher The Semantic Model dispatcher.+ */+ @Inject+ public SemanticModelMetricOperations(SemanticModelDispatcher dispatcher) {+ this.dispatcher = dispatcher;+ }++ /**+ * Lists metric identifiers or complete definitions visible to the caller.+ *+ * @param metalake The metalake name.+ * @param catalog The catalog name.+ * @param schema The schema name.+ * @param details Whether to return complete metric definitions.+ * @return An identifier list or metric info list response.+ */+ @GET+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "list-semantic-model-metrics." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "list-semantic-model-metrics", absolute = true)+ @AuthorizationExpression(+ expression = AuthorizationExpressionConstants.LOAD_SCHEMA_AUTHORIZATION_EXPRESSION,+ accessMetadataType = MetadataObject.Type.SCHEMA)+ public Response listMetrics(+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)+ String metalake,+ @PathParam("catalog") @AuthorizationMetadata(type = Entity.EntityType.CATALOG) String catalog,+ @PathParam("schema") @AuthorizationMetadata(type = Entity.EntityType.SCHEMA) String schema,+ @QueryParam("details") @DefaultValue("false") boolean details) {+ LOG.info(+ "Received list Semantic Model metrics request for {}.{}.{}, details: {}",+ metalake,+ catalog,+ schema,+ details);+ try {+ return Utils.doAs(+ httpRequest,+ () -> {+ Namespace namespace = NamespaceUtil.ofSemanticModel(metalake, catalog, schema);+ if (!details) {+ NameIdentifier[] identifiers = dispatcher.listMetrics(namespace);+ identifiers = identifiers == null ? new NameIdentifier[0] : identifiers;+ Set<NameIdentifier> visibleModels =+ visibleModels(+ metalake,+ Arrays.stream(identifiers)+ .map(ident -> NameIdentifier.of(ident.namespace().levels()))+ .toArray(NameIdentifier[]::new));+ NameIdentifier[] visible =+ Arrays.stream(identifiers)+ .filter(+ ident ->+ visibleModels.contains(NameIdentifier.of(ident.namespace().levels())))+ .toArray(NameIdentifier[]::new);+ return Utils.ok(new EntityListResponse(visible));+ }++ SemanticModelMetric[] metrics = dispatcher.listMetricInfos(namespace);+ metrics = metrics == null ? new SemanticModelMetric[0] : metrics;+ Set<NameIdentifier> visibleModels =+ visibleModels(+ metalake,+ Arrays.stream(metrics)+ .map(info -> NameIdentifier.of(info.namespace().levels()))+ .toArray(NameIdentifier[]::new));+ SemanticModelMetricDTO[] visible =+ Arrays.stream(metrics)+ .filter(+ info ->+ visibleModels.contains(NameIdentifier.of(info.namespace().levels())))+ .map(SemanticModelMetricDTO::fromSemanticModelMetric)+ .toArray(SemanticModelMetricDTO[]::new);+ return Utils.ok(new MetricInfoListResponse(visible));+ });+ } catch (Exception e) {+ return ExceptionHandlers.handleSemanticModelException(+ OperationType.LIST_SEMANTIC_MODEL_METRICS, "", schema, e);+ }+ }++ private Set<NameIdentifier> visibleModels(String metalake, NameIdentifier[] models) {+ NameIdentifier[] distinct = Arrays.stream(models).distinct().toArray(NameIdentifier[]::new);+ return new HashSet<>(+ Arrays.asList(+ MetadataAuthzHelper.filterByExpression(+ metalake,+ AuthorizationExpressionConstants.FILTER_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION,+ Entity.EntityType.SEMANTIC_MODEL,+ distinct)));+ }+}diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.javaindex 8bc3aeab59..ba52025fa3 100644--- a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java@@ -98,6 +98,7 @@ import org.apache.gravitino.server.web.rest.CatalogOperations;import org.apache.gravitino.server.web.rest.MetadataObjectTagOperations;import org.apache.gravitino.server.web.rest.SchemaOperations;import org.apache.gravitino.server.web.rest.SecretsProviderOperations;+import org.apache.gravitino.server.web.rest.SemanticModelMetricOperations;import org.apache.gravitino.server.web.rest.SemanticModelOperations;import org.apache.gravitino.server.web.rest.TableOperations;import org.apache.gravitino.server.web.rest.ViewOperations;@@ -171,6 +172,14 @@ public class TestGravitinoInterceptionService {new GravitinoInterceptionService().getDescriptorFilter().matches(descriptor));}+ @Test+ public void testMetricOperationsIsRegisteredForInterception() {+ Descriptor descriptor = mock(Descriptor.class);+ when(descriptor.getImplementation()).thenReturn(SemanticModelMetricOperations.class.getName());+ Assertions.assertTrue(+ new GravitinoInterceptionService().getDescriptorFilter().matches(descriptor));+ }+@Testpublic void testSemanticModelEndpointAuthorization() throws Throwable {try (MockedStatic<PrincipalUtils> principalUtils = mockStatic(PrincipalUtils.class);@@ -229,11 +238,18 @@ public class TestGravitinoInterceptionService {String.class,String.class,String.class);- for (Method method : List.of(create, load, list, alter, drop, importOssie, exportOssie)) {+ Method metrics =+ SemanticModelMetricOperations.class.getMethod(+ "listMetrics", String.class, String.class, String.class, boolean.class);+ int metricMode = 0;+ for (Method method :+ List.of(create, load, list, alter, drop, importOssie, exportOssie, metrics, metrics)) {MethodInvocation invocation = mock(MethodInvocation.class);when(invocation.getMethod()).thenReturn(method);Object[] args;- if (method.equals(list)) {+ if (method.equals(metrics)) {+ args = new Object[] {"metalake", "catalog", "schema", metricMode++ == 1};+ } else if (method.equals(list)) {args = new Object[] {"metalake", "catalog", "schema"};} else if (method.equals(importOssie)) {args =diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelMetricOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelMetricOperations.javanew file mode 100644index 0000000000..8cd4939af2--- /dev/null+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelMetricOperations.java@@ -0,0 +1,347 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.server.web.rest;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.CALLS_REAL_METHODS;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;+import static org.mockito.Mockito.reset;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.util.Arrays;+import java.util.List;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.core.Application;+import javax.ws.rs.core.Response;+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.GravitinoEnv;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.UserPrincipal;+import org.apache.gravitino.authorization.GravitinoAuthorizer;+import org.apache.gravitino.catalog.SemanticModelDispatcher;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.ErrorResponse;+import org.apache.gravitino.dto.responses.MetricInfoListResponse;+import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.listener.EventBus;+import org.apache.gravitino.listener.SemanticModelEventDispatcher;+import org.apache.gravitino.rest.RESTUtils;+import org.apache.gravitino.semantic.DialectExpression;+import org.apache.gravitino.semantic.Expression;+import org.apache.gravitino.semantic.ImmutableSemanticModelMetric;+import org.apache.gravitino.semantic.Metric;+import org.apache.gravitino.semantic.SemanticModelMetric;+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;+import org.glassfish.jersey.internal.inject.AbstractBinder;+import org.glassfish.jersey.server.ResourceConfig;+import org.glassfish.jersey.test.TestProperties;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.MockedStatic;++/** Verifies both REST discovery modes, visibility filtering, and failure responses. */+public class TestSemanticModelMetricOperations extends BaseOperationsTest {+ private static final String MEDIA_TYPE = "application/vnd.gravitino.v1+json";+ private static final Namespace SCHEMA = Namespace.of("lake", "catalog", "schema");+ private static final String PATH =+ "metalakes/lake/catalogs/catalog/schemas/schema/semantic-model-metrics";+ private static final String FILTER =+ AuthorizationExpressionConstants.FILTER_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION;++ private final SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class);+ private final EventBus eventBus = mock(EventBus.class);++ private static class MockServletRequestFactory extends ServletRequestFactoryBase {+ @Override+ public HttpServletRequest get() {+ return mock(HttpServletRequest.class);+ }+ }++ @Override+ protected Application configure() {+ try {+ forceSet(+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ return new ResourceConfig()+ .register(SemanticModelMetricOperations.class)+ .register(+ new AbstractBinder() {+ @Override+ protected void configure() {+ bind(new SemanticModelEventDispatcher(eventBus, dispatcher))+ .to(SemanticModelDispatcher.class)+ .ranked(2);+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);+ }+ });+ }++ @BeforeEach+ void resetDispatcher() {+ reset(dispatcher, eventBus);+ }++ @Test+ void testDefaultAndExplicitIdentifierMode() {+ NameIdentifier[] names = {identifier("a", "revenue"), identifier("b", "revenue")};+ when(dispatcher.listMetrics(SCHEMA)).thenReturn(names);+ try (Response response = target(PATH).request(MEDIA_TYPE).get()) {+ assertEquals(200, response.getStatus());+ assertArrayEquals(names, response.readEntity(EntityListResponse.class).identifiers());+ }+ try (Response response = get(false)) {+ assertEquals(200, response.getStatus());+ assertArrayEquals(names, response.readEntity(EntityListResponse.class).identifiers());+ }+ verify(dispatcher, times(2)).listMetrics(SCHEMA);+ }++ @Test+ void testDetailsContainFullNamespaceAndMetricDefinition() {+ SemanticModelMetric first = info("a", "revenue");+ SemanticModelMetric second = info("b", "revenue");+ when(dispatcher.listMetricInfos(SCHEMA)).thenReturn(new SemanticModelMetric[] {first, second});+ try (Response response = get(true)) {+ assertEquals(200, response.getStatus());+ MetricInfoListResponse body = response.readEntity(MetricInfoListResponse.class);+ body.validate();+ assertEquals(0, body.getCode());+ assertEquals(2, body.getMetrics().length);+ assertEquals(first.namespace(), body.getMetrics()[0].namespace());+ assertEquals(first.metric(), body.getMetrics()[0].metric());+ assertEquals(second.namespace(), body.getMetrics()[1].namespace());+ }+ verify(dispatcher).listMetricInfos(SCHEMA);+ }++ @ParameterizedTest+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})+ void testEmptyResultsUseModeSpecificArrays(boolean details, boolean nullResult) {+ when(dispatcher.listMetrics(SCHEMA)).thenReturn(nullResult ? null : new NameIdentifier[0]);+ when(dispatcher.listMetricInfos(SCHEMA))+ .thenReturn(nullResult ? null : new SemanticModelMetric[0]);+ try (Response response = get(details)) {+ assertEquals(200, response.getStatus());+ if (details)+ assertEquals(0, response.readEntity(MetricInfoListResponse.class).getMetrics().length);+ else assertEquals(0, response.readEntity(EntityListResponse.class).identifiers().length);+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testErrorsNeverReturnPartialResults(boolean details) {+ List<RuntimeException> failures =+ List.of(+ new NoSuchSchemaException("missing"),+ new ForbiddenException("denied"),+ new UnsupportedOperationException("unsupported"),+ new IllegalStateException("invalid stored metrics"),+ new RuntimeException("storage failure"));+ int[] statuses = {404, 403, 501, 500, 500};+ for (int i = 0; i < failures.size(); i++) {+ if (details) doThrow(failures.get(i)).when(dispatcher).listMetricInfos(SCHEMA);+ else doThrow(failures.get(i)).when(dispatcher).listMetrics(SCHEMA);+ try (Response response = get(details)) {+ assertEquals(statuses[i], response.getStatus());+ ErrorResponse error = response.readEntity(ErrorResponse.class);+ assertEquals(+ i >= 3+ ? RuntimeException.class.getSimpleName()+ : failures.get(i).getClass().getSimpleName(),+ error.getType());+ assertTrue(error.getMessage().contains("operation [LIST_SEMANTIC_MODEL_METRICS]"));+ assertTrue(error.getMessage().contains(failures.get(i).getMessage()));+ }+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testVisibilityIsCheckedOncePerContainingModelBeforeDtoConversion(boolean details)+ throws Exception {+ NameIdentifier[] names = {+ identifier("visible", "a"), identifier("visible", "b"), identifier("hidden", "a")+ };+ SemanticModelMetric hidden = mock(SemanticModelMetric.class);+ when(hidden.namespace()).thenReturn(names[2].namespace());+ when(hidden.metric())+ .thenThrow(new AssertionError("Hidden result must not be converted to a DTO"));+ when(dispatcher.listMetrics(SCHEMA)).thenReturn(names);+ when(dispatcher.listMetricInfos(SCHEMA))+ .thenReturn(new SemanticModelMetric[] {info("visible", "a"), info("visible", "b"), hidden});+ NameIdentifier[] models = {+ NameIdentifier.of("lake", "catalog", "schema", "visible"),+ NameIdentifier.of("lake", "catalog", "schema", "hidden")+ };+ try (MockedStatic<MetadataAuthzHelper> helper = mockStatic(MetadataAuthzHelper.class)) {+ helper+ .when(+ () ->+ MetadataAuthzHelper.filterByExpression(+ "lake", FILTER, Entity.EntityType.SEMANTIC_MODEL, models))+ .thenReturn(new NameIdentifier[] {models[0]});+ try (Response response = operations().listMetrics("lake", "catalog", "schema", details)) {+ assertEquals(200, response.getStatus());+ if (details) {+ assertEquals(2, ((MetricInfoListResponse) response.getEntity()).getMetrics().length);+ } else {+ assertArrayEquals(+ Arrays.copyOf(names, 2), ((EntityListResponse) response.getEntity()).identifiers());+ }+ }+ helper.verify(+ () ->+ MetadataAuthzHelper.filterByExpression(+ "lake", FILTER, Entity.EntityType.SEMANTIC_MODEL, models));+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void testAuthorizationDenialsAndEvaluationFailuresExcludeWholeModels(boolean details)+ throws Exception {+ Config previous = GravitinoEnv.getInstance().config();+ Config config = new Config(false) {};+ config.set(Configs.ENABLE_AUTHORIZATION, true);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);+ when(authorizer.isOwner(any(), eq("lake"), any(), any()))+ .thenAnswer(+ call -> {+ MetadataObject object = call.getArgument(2);+ if (object.type() != MetadataObject.Type.SEMANTIC_MODEL) return false;+ if (object.name().equals("failed"))+ throw new IllegalStateException("authorization unavailable");+ return object.name().equals("visible");+ });+ NameIdentifier[] names = {+ identifier("visible", "a"), identifier("denied", "a"), identifier("failed", "a")+ };+ when(dispatcher.listMetrics(SCHEMA)).thenReturn(names);+ when(dispatcher.listMetricInfos(SCHEMA))+ .thenReturn(+ new SemanticModelMetric[] {+ info("visible", "a"), info("denied", "a"), info("failed", "a")+ });+ try (MockedStatic<MetadataAuthzHelper> helper =+ mockStatic(MetadataAuthzHelper.class, CALLS_REAL_METHODS)) {+ helper+ .when(+ () ->+ MetadataAuthzHelper.filterByExpression(+ eq("lake"),+ eq(FILTER),+ eq(Entity.EntityType.SEMANTIC_MODEL),+ any(NameIdentifier[].class)))+ .thenAnswer(+ call ->+ MetadataAuthzHelper.filterByExpression(+ "lake",+ FILTER,+ Entity.EntityType.SEMANTIC_MODEL,+ call.getArgument(3, NameIdentifier[].class),+ value -> value,+ new UserPrincipal("tester"),+ authorizer));+ try (Response response = operations().listMetrics("lake", "catalog", "schema", details)) {+ assertEquals(200, response.getStatus());+ if (details) {+ assertEquals(1, ((MetricInfoListResponse) response.getEntity()).getMetrics().length);+ assertEquals(+ names[0].namespace(),+ ((MetricInfoListResponse) response.getEntity()).getMetrics()[0].namespace());+ } else+ assertArrayEquals(+ new NameIdentifier[] {names[0]},+ ((EntityListResponse) response.getEntity()).identifiers());+ }+ } finally {+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previous, true);+ }+ }++ @Test+ void testDecodeFailurePrecedesVisibilityFiltering() throws Exception {+ doThrow(new IllegalStateException("invalid metrics in a hidden model"))+ .when(dispatcher)+ .listMetricInfos(SCHEMA);+ try (MockedStatic<MetadataAuthzHelper> helper = mockStatic(MetadataAuthzHelper.class);+ Response response = operations().listMetrics("lake", "catalog", "schema", true)) {+ assertEquals(500, response.getStatus());+ helper.verifyNoInteractions();+ }+ }++ private Response get(boolean details) {+ return target(PATH).queryParam("details", details).request(MEDIA_TYPE).get();+ }++ private SemanticModelMetricOperations operations() throws Exception {+ SemanticModelMetricOperations operations = new SemanticModelMetricOperations(dispatcher);+ FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);+ return operations;+ }++ private static NameIdentifier identifier(String model, String metric) {+ return NameIdentifier.of(Namespace.of("lake", "catalog", "schema", model), metric);+ }++ private static SemanticModelMetric info(String model, String name) {+ Metric metric =+ Metric.builder()+ .withName(name)+ .withDescription("Revenue")+ .withExpression(+ Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder()+ .withDialect("ansi")+ .withExpression("SUM(orders.amount)")+ .build()+ })+ .build())+ .build();+ return new ImmutableSemanticModelMetric(identifier(model, name).namespace(), metric);+ }+}