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


##########
web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+
+'use client'
+
+import React, { useEffect, useRef, useState } from 'react'
+import { Form, Input, Modal, Spin, Typography } from 'antd'
+import { useScrolling } from 'react-use'
+import RenderPropertiesFormItem from '@/components/EntityPropertiesFormItem'
+import { validateMessages, dialogContentMaxHeigth, mismatchName } from 
'@/config'
+import { nameRegex } from '@/lib/utils/regex'
+import { useResetFormOnCloseModal } from '@/lib/hooks/use-reset'
+import { cn } from '@/lib/utils/tailwind'
+import { useAppDispatch } from '@/lib/hooks/useStore'
+import {
+  formatSemanticModelDefinition,
+  genSemanticModelUpdates,
+  parseSemanticModelDefinition
+} from '@/lib/utils/semanticModel'
+import { createSemanticModel, updateSemanticModel, getSemanticModelDetails } 
from '@/lib/store/metalakes'
+
+const { Paragraph } = Typography
+const { TextArea } = Input
+
+const definitionPlaceholder = `{
+  "datasets": [
+    {
+      "name": "orders",
+      "source": { "namespace": ["sales", "mart"], "name": "orders" },
+      "fields": []
+    }
+  ]
+}`
+
+const defaultValues = {
+  name: '',
+  comment: '',
+  definition: '',
+  properties: []
+}
+
+export default function CreateSemanticModelDialog({ ...props }) {
+  const { open, setOpen, metalake, catalog, schema, editSemanticModel } = props
+  const [confirmLoading, setConfirmLoading] = useState(false)
+  const [isLoading, setIsLoading] = useState(false)
+  const [cacheData, setCacheData] = useState()
+  const scrollRef = useRef(null)
+  const loadedRef = useRef(false)
+  const scrolling = useScrolling(scrollRef)
+  const [bottomShadow, setBottomShadow] = useState(false)
+  const [topShadow, setTopShadow] = useState(false)
+  const [form] = Form.useForm()
+  const values = Form.useWatch([], form)
+  const dispatch = useAppDispatch()
+
+  useResetFormOnCloseModal({
+    form,
+    open
+  })
+
+  const handScroll = () => {
+    if (scrollRef.current) {
+      const { scrollTop, scrollHeight, clientHeight } = scrollRef.current
+      if (scrollHeight > clientHeight + scrollTop) {
+        setTopShadow(true)
+        setBottomShadow(scrollTop > 0)
+      } else if (scrollHeight === clientHeight + scrollTop) {
+        setTopShadow(false)
+        setBottomShadow(scrollTop > 0)
+      }
+    }
+  }
+
+  useEffect(() => {
+    scrollRef.current && handScroll()
+  }, [scrolling])
+
+  useEffect(() => {
+    if (open && editSemanticModel && !loadedRef.current) {
+      loadedRef.current = true
+
+      const initLoad = async () => {
+        setIsLoading(true)
+        try {
+          const { payload } = await dispatch(
+            getSemanticModelDetails({ metalake, catalog, schema, 
semanticModel: editSemanticModel })
+          )
+          const loaded = payload?.semanticModel
+          setCacheData(loaded)
+          form.setFieldValue('name', loaded?.name)
+          form.setFieldValue('comment', loaded?.comment)
+          form.setFieldValue('definition', 
formatSemanticModelDefinition(loaded?.definition))
+          let index = 0
+          Object.entries(loaded?.properties || {}).forEach(([key, value]) => {
+            form.setFieldValue(['properties', index, 'key'], key)
+            form.setFieldValue(['properties', index, 'value'], value)
+            index++
+          })
+          setIsLoading(false)
+        } catch (e) {
+          setIsLoading(false)
+        }
+      }
+      initLoad()
+    }
+
+    // Reset loadedRef when dialog closes
+    if (!open) {
+      loadedRef.current = false
+    }
+  }, [open, editSemanticModel, metalake, catalog, schema])
+
+  const validateDefinition = (rule, value) => {
+    const { errors } = parseSemanticModelDefinition(value)
+
+    return errors.length ? Promise.reject(new Error(errors.join(' '))) : 
Promise.resolve()
+  }
+
+  const handleSubmit = e => {
+    e.preventDefault()
+    form
+      .validateFields()
+      .then(async () => {
+        const { definition } = parseSemanticModelDefinition(values.definition)
+
+        setConfirmLoading(true)
+
+        const submitData = {
+          name: values.name.trim(),
+          comment: values.comment,
+          definition,
+          properties: (values.properties || []).reduce((acc, item) => {
+            acc[item.key] = values[item.key] || item.value
+
+            return acc
+          }, {})
+        }

Review Comment:
   submitData.properties` is built using `values[item.key]`, but `values` is 
the full form object (and property values live under 
`values.properties[i].value`). This can produce incorrect results (and `||` 
will also incorrectly drop valid falsy values like `0`, `false`, or `''`). 
Build the properties map from the `properties` list items themselves (e.g., `{ 
key, value }`) and use nullish-coalescing semantics rather than `||` if you 
need a fallback.



##########
web-v2/web/src/lib/store/metalakes/index.js:
##########
@@ -2332,6 +2374,136 @@ 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 || !res) {
+      // 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 }
+      }
+      if (init) {
+        throw new Error(err)
+      }

Review Comment:
   For non-404/405 failures when init is false, this thunk currently falls 
through and returns an empty list as a fulfilled action, which suppresses the 
existing rejected/toast path and can hide real server/network problems (e.g., 
500s). Also, `throw new Error(err)` will likely yield an unhelpful message 
("[object Object]"). Consider: (1) throwing/rejecting for non-404/405 errors 
regardless of `init` so the `rejected` case can toast, and (2) using 
`err?.message ?? String(err)` (or rethrowing `err`) so the error message is 
actionable.



##########
web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js:
##########
@@ -0,0 +1,266 @@
+/*
+ * 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.
+ */
+
+'use client'
+
+import React, { useEffect, useRef, useState } from 'react'
+import { Form, Input, Modal, Spin, Typography } from 'antd'
+import { useScrolling } from 'react-use'
+import RenderPropertiesFormItem from '@/components/EntityPropertiesFormItem'
+import { validateMessages, dialogContentMaxHeigth, mismatchName } from 
'@/config'
+import { nameRegex } from '@/lib/utils/regex'
+import { useResetFormOnCloseModal } from '@/lib/hooks/use-reset'
+import { cn } from '@/lib/utils/tailwind'
+import { useAppDispatch } from '@/lib/hooks/useStore'
+import {
+  formatSemanticModelDefinition,
+  genSemanticModelUpdates,
+  parseSemanticModelDefinition
+} from '@/lib/utils/semanticModel'
+import { createSemanticModel, updateSemanticModel, getSemanticModelDetails } 
from '@/lib/store/metalakes'
+
+const { Paragraph } = Typography
+const { TextArea } = Input
+
+const definitionPlaceholder = `{
+  "datasets": [
+    {
+      "name": "orders",
+      "source": { "namespace": ["sales", "mart"], "name": "orders" },
+      "fields": []
+    }
+  ]
+}`
+
+const defaultValues = {
+  name: '',
+  comment: '',
+  definition: '',
+  properties: []
+}
+
+export default function CreateSemanticModelDialog({ ...props }) {
+  const { open, setOpen, metalake, catalog, schema, editSemanticModel } = props
+  const [confirmLoading, setConfirmLoading] = useState(false)
+  const [isLoading, setIsLoading] = useState(false)
+  const [cacheData, setCacheData] = useState()
+  const scrollRef = useRef(null)
+  const loadedRef = useRef(false)
+  const scrolling = useScrolling(scrollRef)
+  const [bottomShadow, setBottomShadow] = useState(false)
+  const [topShadow, setTopShadow] = useState(false)
+  const [form] = Form.useForm()
+  const values = Form.useWatch([], form)
+  const dispatch = useAppDispatch()
+
+  useResetFormOnCloseModal({
+    form,
+    open
+  })
+
+  const handScroll = () => {
+    if (scrollRef.current) {
+      const { scrollTop, scrollHeight, clientHeight } = scrollRef.current
+      if (scrollHeight > clientHeight + scrollTop) {
+        setTopShadow(true)
+        setBottomShadow(scrollTop > 0)
+      } else if (scrollHeight === clientHeight + scrollTop) {
+        setTopShadow(false)
+        setBottomShadow(scrollTop > 0)
+      }
+    }
+  }
+
+  useEffect(() => {
+    scrollRef.current && handScroll()
+  }, [scrolling])
+
+  useEffect(() => {
+    if (open && editSemanticModel && !loadedRef.current) {
+      loadedRef.current = true
+
+      const initLoad = async () => {
+        setIsLoading(true)
+        try {
+          const { payload } = await dispatch(
+            getSemanticModelDetails({ metalake, catalog, schema, 
semanticModel: editSemanticModel })
+          )
+          const loaded = payload?.semanticModel
+          setCacheData(loaded)
+          form.setFieldValue('name', loaded?.name)
+          form.setFieldValue('comment', loaded?.comment)
+          form.setFieldValue('definition', 
formatSemanticModelDefinition(loaded?.definition))
+          let index = 0
+          Object.entries(loaded?.properties || {}).forEach(([key, value]) => {
+            form.setFieldValue(['properties', index, 'key'], key)
+            form.setFieldValue(['properties', index, 'value'], value)
+            index++
+          })
+          setIsLoading(false)
+        } catch (e) {
+          setIsLoading(false)
+        }
+      }
+      initLoad()
+    }
+
+    // Reset loadedRef when dialog closes
+    if (!open) {
+      loadedRef.current = false
+    }
+  }, [open, editSemanticModel, metalake, catalog, schema])
+
+  const validateDefinition = (rule, value) => {
+    const { errors } = parseSemanticModelDefinition(value)
+
+    return errors.length ? Promise.reject(new Error(errors.join(' '))) : 
Promise.resolve()

Review Comment:
   When multiple validation problems are returned, joining with a single space 
collapses the list into one hard-to-read sentence. Consider joining with `\\n` 
(or another clear delimiter) so the user can distinguish individual contract 
violations in the form validation message.



##########
web-v2/web/src/lib/utils/semanticModel.js:
##########
@@ -0,0 +1,259 @@
+/*
+ * 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
+    }
+
+    const duplicateFields = duplicatesOf((fields || []).map(field => 
field?.name))

Review Comment:
   Duplicate field detection currently includes non-string/blank names (e.g., 
`undefined`, `null`, empty strings) because it maps `field?.name` without 
filtering. This can lead to confusing messages like `...: undefined.` and also 
allows fields without a valid name to pass validation. Consider validating each 
field is an object with a non-empty `name`, and filtering to non-blank strings 
before calling `duplicatesOf`.



##########
web-v2/web/src/lib/store/metalakes/index.js:
##########
@@ -2332,6 +2374,136 @@ 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 || !res) {
+      // 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 }
+      }
+      if (init) {
+        throw new Error(err)
+      }
+    }
+
+    const { identifiers = [] } = res || {}
+
+    const semanticModels = identifiers.map(semanticModelItem => {
+      return {
+        ...semanticModelItem,
+        node: 'semanticModel',
+        id: 
`{{${metalake}}}{{${catalog}}}{{${'relational'}}}{{${schema}}}{{${semanticModelItem.name}}}`,
+        key: 
`{{${metalake}}}{{${catalog}}}{{${'relational'}}}{{${schema}}}{{${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 || !res) {
+      // Catalog doesn't support semantic models (HTTP 405) β€” return empty 
result silently
+      if (err?.response?.status === 405) {
+        return { semanticModel: null, init }
+      }
+      throw new Error(err)

Review Comment:
   Similar to `fetchSemanticModels`, `throw new Error(err)` is likely to 
produce a non-actionable message ("[object Object]") and can mask HTTP details. 
Prefer rethrowing the original error (if it’s already an Error) or constructing 
the Error from `err?.message ?? String(err)` so the UI toast and logs contain 
useful context.



-- 
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