laserninja commented on code in PR #12900:
URL: https://github.com/apache/gravitino/pull/12900#discussion_r4261158751


##########
web-v2/web/src/lib/store/metalakes/index.js:
##########
@@ -2333,6 +2376,142 @@ export const deleteView = createAsyncThunk(
   }
 )
 
+export const fetchSemanticModels = createAsyncThunk(
+  'appMetalakes/fetchSemanticModels',
+  async ({ init, metalake, catalog, schema }, { getState, dispatch }) => {
+    const [err, res] = await to(getSemanticModelsApi({ metalake, catalog, 
schema }, { errorMessageMode: 'none' }))
+
+    if (err) {
+      // The catalog doesn't support semantic models (405), or the server 
predates the endpoint and
+      // has no route for it (404). Both mean "this schema has none" - return 
empty silently rather
+      // than failing every schema page against an older server.
+      if ([404, 405].includes(err?.response?.status)) {
+        return { semanticModels: [], init }
+      }
+      throw err instanceof Error ? err : new Error(err?.message ?? String(err))
+    }
+
+    if (!res) {
+      throw new Error('Semantic Model list returned an empty response')
+    }
+
+    const { identifiers = [] } = res || {}
+
+    const semanticModels = identifiers.map(semanticModelItem => {
+      return {
+        ...semanticModelItem,
+        node: 'semanticModel',
+        id: semanticModelNodeKey({ metalake, catalog, schema, semanticModel: 
semanticModelItem.name }),
+        key: semanticModelNodeKey({ metalake, catalog, schema, semanticModel: 
semanticModelItem.name }),
+        path: `?${new URLSearchParams({
+          metalake,
+          catalog,
+          catalogType: 'relational',
+          schema,
+          semanticModel: semanticModelItem.name
+        }).toString()}`,
+        name: semanticModelItem.name,
+        title: semanticModelItem.name,
+        isLeaf: true,
+        children: []
+      }
+    })
+
+    if (
+      init &&
+      
getState().metalakes.loadedNodes.includes(`{{${metalake}}}{{${catalog}}}{{${'relational'}}}{{${schema}}}`)
+    ) {
+      const schemaKey = 
`{{${metalake}}}{{${catalog}}}{{${'relational'}}}{{${schema}}}`
+      dispatch(
+        setIntoTreeNodes({
+          key: schemaKey,
+          data: mergeWithSemanticModelNodes({
+            tree: getState().metalakes.metalakeTree,
+            key: schemaKey,
+            entities: semanticModels
+          })
+        })
+      )
+    }
+
+    return { semanticModels, init }
+  }
+)
+
+export const getSemanticModelDetails = createAsyncThunk(
+  'appMetalakes/getSemanticModelDetails',
+  async ({ init, metalake, catalog, schema, semanticModel }) => {
+    const [err, res] = await to(
+      getSemanticModelDetailsApi({ metalake, catalog, schema, semanticModel }, 
{ errorMessageMode: 'none' })
+    )
+
+    if (err) {
+      // Catalog doesn't support semantic models (HTTP 405) - return empty 
result silently
+      if (err?.response?.status === 405) {
+        return { semanticModel: null, init }
+      }
+      throw err instanceof Error ? err : new Error(err?.message ?? String(err))
+    }
+
+    if (!res) {
+      throw new Error('Semantic Model details returned an empty response')
+    }
+
+    return { semanticModel: res.semanticModel || res, init }
+  }
+)
+
+export const createSemanticModel = createAsyncThunk(
+  'appMetalakes/createSemanticModel',
+  async ({ data, metalake, catalog, schema }, { dispatch }) => {
+    await dispatch(setTableLoading(true))
+    const [err, res] = await to(createSemanticModelApi({ data, metalake, 
catalog, schema }))
+    await dispatch(setTableLoading(false))
+
+    if (err || !res) {
+      return { err: true }
+    }
+
+    await dispatch(fetchSemanticModels({ metalake, catalog, schema, init: true 
}))
+
+    return res.semanticModel
+  }
+)
+
+export const updateSemanticModel = createAsyncThunk(
+  'appMetalakes/updateSemanticModel',
+  async ({ metalake, catalog, schema, semanticModel, data }, { dispatch }) => {
+    await dispatch(setTableLoading(true))
+    const [err, res] = await to(updateSemanticModelApi({ metalake, catalog, 
schema, semanticModel, data }))
+    await dispatch(setTableLoading(false))
+
+    if (err || !res) {
+      return { err: true }
+    }
+
+    await dispatch(fetchSemanticModels({ metalake, catalog, schema, init: true 
}))
+
+    return res.semanticModel
+  }
+)
+
+export const deleteSemanticModel = createAsyncThunk(
+  'appMetalakes/deleteSemanticModel',
+  async ({ metalake, catalog, schema, semanticModel }, { dispatch }) => {
+    await dispatch(setTableLoading(true))
+    const [err, res] = await to(deleteSemanticModelApi({ metalake, catalog, 
schema, semanticModel }))
+    await dispatch(setTableLoading(false))
+
+    if (err || !res) {
+      throw new Error(err)
+    }

Review Comment:
   Fixed in 2461081a2. Deletion preserves an existing Error or uses the 
rejected object's message, and an empty response gets an explicit error. Tests 
cover both error forms and empty responses; Chromium also verifies that a 
failed deletion shows the server message without `[object Object]`.



##########
web-v2/web/src/lib/utils/semanticModel.js:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.
+ */
+
+import { isEqual, isPlainObject } from 'lodash-es'
+
+const SOURCE_NAMESPACE_LENGTH = 2
+const DEFINITION_INDENT = 2
+
+const isNonBlankString = value => typeof value === 'string' && value.trim() 
!== ''
+
+const duplicatesOf = names => {
+  const seen = new Set()
+  const duplicates = new Set()
+
+  names.forEach(name => {
+    if (seen.has(name)) {
+      duplicates.add(name)
+    }
+    seen.add(name)
+  })
+
+  return [...duplicates]
+}
+
+const validateSource = (dataset, errors) => {
+  const { name, source } = dataset
+
+  if (!isPlainObject(source)) {
+    errors.push(`Dataset "${name}" must have a source with a namespace and a 
name.`)
+
+    return
+  }
+
+  const { namespace } = source
+
+  if (!Array.isArray(namespace) || namespace.length !== 
SOURCE_NAMESPACE_LENGTH || !namespace.every(isNonBlankString)) {
+    errors.push(`Dataset "${name}" must have a source namespace of exactly 
[catalog, schema].`)
+  }
+
+  if (!isNonBlankString(source.name)) {
+    errors.push(`Dataset "${name}" must have a source with a non-empty name.`)
+  }
+}
+
+const validateDatasets = (datasets, errors) => {
+  datasets.forEach((dataset, index) => {
+    if (!isPlainObject(dataset) || !isNonBlankString(dataset.name)) {
+      errors.push(`datasets[${index}] must have a non-empty name.`)
+
+      return
+    }
+
+    validateSource(dataset, errors)
+
+    const fields = dataset.fields
+    if (fields !== undefined && !Array.isArray(fields)) {
+      errors.push(`Dataset "${dataset.name}" must declare fields as an array.`)
+
+      return
+    }
+
+    ;(fields || []).forEach((field, fieldIndex) => {
+      if (!isPlainObject(field) || !isNonBlankString(field.name)) {
+        errors.push(`datasets[${index}].fields[${fieldIndex}] must have a 
non-empty name.`)
+      }
+    })
+
+    const duplicateFields = duplicatesOf((fields || []).map(field => 
field?.name).filter(isNonBlankString))
+    if (duplicateFields.length) {
+      errors.push(`Field names must be unique within dataset 
"${dataset.name}": ${duplicateFields.join(', ')}.`)
+    }
+  })
+
+  const duplicateDatasets = duplicatesOf(datasets.map(dataset => 
dataset?.name).filter(isNonBlankString))
+  if (duplicateDatasets.length) {
+    errors.push(`Dataset names must be unique within the semantic model: 
${duplicateDatasets.join(', ')}.`)
+  }
+}
+
+const validateRelationships = (relationships, datasetNames, errors) => {
+  relationships.forEach((relationship, index) => {
+    if (!isPlainObject(relationship) || !isNonBlankString(relationship.name)) {
+      errors.push(`relationships[${index}] must have a non-empty name.`)
+
+      return
+    }
+
+    const { name, from, to, fromColumns, toColumns } = relationship
+
+    ;[from, to].forEach(endpoint => {
+      if (!datasetNames.has(endpoint)) {
+        errors.push(`Relationship "${name}" references an unknown dataset 
"${endpoint}".`)
+      }
+    })
+
+    if (!Array.isArray(fromColumns) || !Array.isArray(toColumns) || 
!fromColumns.length || !toColumns.length) {
+      errors.push(`Relationship "${name}" must have non-empty fromColumns and 
toColumns.`)
+
+      return
+    }
+
+    if (fromColumns.length !== toColumns.length) {
+      errors.push(`Relationship "${name}" must have the same number of 
fromColumns and toColumns.`)
+    }
+  })
+
+  const duplicates = duplicatesOf(relationships.map(relationship => 
relationship?.name).filter(isNonBlankString))
+  if (duplicates.length) {
+    errors.push(`Relationship names must be unique within the semantic model: 
${duplicates.join(', ')}.`)
+  }
+}
+
+const validateMetrics = (metrics, errors) => {
+  metrics.forEach((metric, index) => {
+    if (!isPlainObject(metric) || !isNonBlankString(metric.name)) {
+      errors.push(`metrics[${index}] must have a non-empty name.`)
+    }
+  })
+
+  const duplicates = duplicatesOf(metrics.map(metric => 
metric?.name).filter(isNonBlankString))
+  if (duplicates.length) {
+    errors.push(`Metric names must be unique within the semantic model: 
${duplicates.join(', ')}.`)
+  }
+}
+
+/**
+ * Checks the structural rules the server also enforces, so obvious mistakes 
are reported before the
+ * request is sent. The server stays the authority: it additionally resolves 
every dataset source
+ * and its columns against the catalog, which the browser cannot do.
+ *
+ * @param {unknown} definition The parsed semantic model definition.
+ * @returns {string[]} The problems found, empty when the definition looks 
well formed.
+ */
+export const validateSemanticModelDefinition = definition => {

Review Comment:
   Fixed in 2461081a2. Validation now checks required field/metric expression 
dialects, non-empty dialect names and expressions, duplicate dialects, 
relationship column entries, dataset keys, custom extensions, and AI context 
structure at every level. Optional null arrays remain allowed, matching the 
server contract. Added nested-contract tests and an editor test confirming 
invalid expressions block submission before a request is sent.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to