World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12616] feat(web-v2): Add Semantic Model support to the Gravitino Web UI (#12900)
Akshay Thorat0f92ce43675f
diff --git a/web-v2/web/package.json b/web-v2/web/package.jsonindex 345aa53bb5..88cae80da4 100644--- a/web-v2/web/package.json+++ b/web-v2/web/package.json@@ -29,6 +29,7 @@"chroma-js": "^2.4.2","clsx": "^2.1.1","dayjs": "^1.11.11",+ "js-yaml": "4.1.1","lodash-es": "^4.18.0","lucide-react": "^0.552.0","next": "14.2.32",diff --git a/web-v2/web/pnpm-lock.yaml b/web-v2/web/pnpm-lock.yamlindex 7754a41789..98ce808b1f 100644--- a/web-v2/web/pnpm-lock.yaml+++ b/web-v2/web/pnpm-lock.yaml@@ -49,6 +49,9 @@ importers:dayjs:specifier: ^1.11.11version: 1.11.18+ js-yaml:+ specifier: 4.1.1+ version: 4.1.1lodash-es:specifier: ^4.18.0version: 4.18.1@@ -5316,7 +5319,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:@@ -5338,7 +5341,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.2([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3diff --git a/web-v2/web/src/app/catalogs/TreeComponent.js b/web-v2/web/src/app/catalogs/TreeComponent.jsindex 01ab6d4402..011050cc1f 100644--- a/web-v2/web/src/app/catalogs/TreeComponent.js+++ b/web-v2/web/src/app/catalogs/TreeComponent.js@@ -22,6 +22,7 @@import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'import { useRouter, useSearchParams } from 'next/navigation'+import { semanticModelNodeKey } from '@/lib/utils/semanticModel'import { Empty, Input, Spin, Tabs, Tooltip, Tree } from 'antd'@@ -324,6 +325,12 @@ export const TreeComponent = forwardRef(function TreeComponent(props, ref) {<Icons.iconify icon='ic:outline-table-view' className='my-icon-small' /></span>)+ case 'semanticModel':+ return (+ <span role='img' aria-label='semantic model' className='anticon anticon-frown'>+ <Icons.iconify icon='mdi:graph-outline' className='my-icon-small' />+ </span>+ )default:return <></>}@@ -350,7 +357,8 @@ export const TreeComponent = forwardRef(function TreeComponent(props, ref) {const topic = searchParams.get('topic')const model = searchParams.get('model')const func = searchParams.get('function')- const entity = table || view || fileset || topic || model || func+ const semanticModel = searchParams.get('semanticModel')+ const entity = table || view || semanticModel || fileset || topic || model || funcif (!metalake) {dispatch(setExpanded([]))@@ -374,7 +382,9 @@ export const TreeComponent = forwardRef(function TreeComponent(props, ref) {nextSelectedKey = schemaKeyif (entity) {- nextSelectedKey = `${schemaKey}{{${entity}}}`+ nextSelectedKey = semanticModel+ ? semanticModelNodeKey({ metalake, catalog, schema, semanticModel })+ : `${schemaKey}{{${entity}}}`}}}diff --git a/web-v2/web/src/app/catalogs/catalogTreeLoading.test.jsx b/web-v2/web/src/app/catalogs/catalogTreeLoading.test.jsxnew file mode 100644index 0000000000..24b39ae3d9--- /dev/null+++ b/web-v2/web/src/app/catalogs/catalogTreeLoading.test.jsx@@ -0,0 +1,114 @@+/*+ * 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 { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer from '@/lib/store/metalakes'+import CatalogsListPage from './page'++const navigation = vi.hoisted(() => ({ params: null, push: vi.fn() }))+vi.mock('next/navigation', () => ({ useSearchParams: () => navigation.params, useRouter: () => navigation }))+vi.mock('./rightContent/RightContent', () => ({ default: () => null }))+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++let store+let root+let container+beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ store = configureStore({ reducer: { metalakes: reducer } })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})+afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.unstubAllGlobals()+})++it.each([[[]], [['sales_model', 'other_model']]])(+ 'loads all tree siblings on a fresh route with models %j',+ async names => {+ const catalog = { name: 'sales', type: 'relational', provider: 'jdbc-mysql', properties: {}, audit: {} }+ navigation.params = new URLSearchParams({+ metalake: 'demo',+ catalog: 'sales',+ catalogType: 'relational',+ schema: 'mart',+ ...(names.length ? { semanticModel: 'sales_model' } : {})+ })+ defHttp.get.mockImplementation(({ url: requestUrl }) => {+ const url = requestUrl.split('?')[0]++ if (url.endsWith('/catalogs')) return Promise.resolve({ catalogs: [catalog] })+ if (url.endsWith('/schemas')) return Promise.resolve({ identifiers: [{ name: 'mart' }] })+ if (url.endsWith('/schemas/mart')) return Promise.resolve({ schema: { name: 'mart' } })+ if (url.endsWith('/semantic-models/sales_model'))+ return Promise.resolve({ semanticModel: { name: 'sales_model', definition: { datasets: [] } } })+ if (url.endsWith('/tags') || url.endsWith('/policies')) return Promise.resolve({ tags: [], policies: [] })++ const children = url.endsWith('/semantic-models')+ ? names+ : url.endsWith('/tables')+ ? ['orders', 'customers']+ : url.endsWith('/views')+ ? ['recent_orders']+ : ['revenue']++ return Promise.resolve({ identifiers: children.map(name => ({ name })) })+ })+ await act(async () =>+ root.render(+ <Provider store={store}>+ <CatalogsListPage />+ </Provider>+ )+ )++ // Let the existing URL expansion debounce run, then drain its async tree loads.+ await act(async () => new Promise(resolve => setTimeout(resolve, 1100)))+ const schema = store.getState().metalakes.metalakeTree[0].children[0]+ expect(schema.isLeaf).toBe(false)+ expect(schema.children.map(child => child.name).sort()).toEqual(+ ['orders', 'customers', 'recent_orders', 'revenue', ...names].sort()+ )+ for (const name of ['orders', 'customers', 'recent_orders', 'revenue', ...names])+ expect(container.textContent).toContain(name)+ expect(defHttp.get.mock.calls.some(([request]) => request.url.endsWith('/tables'))).toBe(true)+ }+)diff --git a/web-v2/web/src/app/catalogs/page.js b/web-v2/web/src/app/catalogs/page.jsindex 9aeecc3705..e7fcffa169 100644--- a/web-v2/web/src/app/catalogs/page.js+++ b/web-v2/web/src/app/catalogs/page.js@@ -22,6 +22,7 @@import { useEffect, createContext, useRef } from 'react'import RightContent from './rightContent/RightContent'+import { semanticModelNodeKey } from '@/lib/utils/semanticModel'import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'import { useSearchParams } from 'next/navigation'@@ -41,8 +42,10 @@ import {fetchModelVersions,fetchFunctions,fetchViews,+ fetchSemanticModels,getFunctionDetails,getViewDetails,+ getSemanticModelDetails,getMetalakeDetails,getCatalogDetails,getSchemaDetails,@@ -50,8 +53,8 @@ import {getFilesetDetails,getTopicDetails,getModelDetails,- getVersionDetails,setSelectedNodes,+ setActiveCatalogEntity,getCurrentEntityTags,getCurrentEntityPolicies,resetActivatedDetails,@@ -71,6 +74,10 @@ const CatalogsListPage = () => {const treeRef = useRef()const buildNodePath = routeParams => {+ if (routeParams.semanticModel) {+ return semanticModelNodeKey(routeParams)+ }+const keys = ['metalake','catalog',@@ -81,7 +88,8 @@ const CatalogsListPage = () => {'topic','model','function',- 'view'+ 'view',+ 'semanticModel']return keys.map(key => (routeParams[key] ? `{{${routeParams[key]}}}` : '')).join('')@@ -99,8 +107,21 @@ const CatalogsListPage = () => {model: searchParams.get('model'),function: searchParams.get('function'),view: searchParams.get('view'),+ semanticModel: searchParams.get('semanticModel'),version: searchParams.get('version')}+ let canceled = false+ const requests = new Set()++ const load = action => {+ if (canceled) return Promise.resolve({})+ const request = dispatch(action)+ if (request.abort) requests.add(request)++ return request+ }+ dispatch(setActiveCatalogEntity(routeParams))+ dispatch(setSelectedNodes(routeParams.catalog ? [buildNodePath(routeParams)] : []))async function fetchDependsData() {if ([...searchParams.keys()].length) {const {@@ -114,6 +135,7 @@ const CatalogsListPage = () => {model,function: func,view,+ semanticModel,version} = routeParams@@ -123,26 +145,26 @@ const CatalogsListPage = () => {}if (paramsSize === 2 && metalake) {- dispatch(fetchCatalogs({ init: true, page: 'metalakes', metalake }))- dispatch(getMetalakeDetails({ metalake }))+ load(fetchCatalogs({ init: true, page: 'metalakes', metalake }))+ load(getMetalakeDetails({ metalake }))}if (paramsSize === 3 && catalog) {if (catalogType) {const catalogKey = `{{${metalake}}}{{${catalog}}}{{${catalogType}}}`if (!store.loadedNodes.includes(catalogKey)) {- await dispatch(setLoadedNodes([...new Set([...store.loadedNodes, catalogKey])]))+ await load(setLoadedNodes([...new Set([...store.loadedNodes, catalogKey])]))}}if (!store.catalogs.length) {- await dispatch(fetchCatalogs({ metalake }))+ await load(fetchCatalogs({ metalake }))}- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getCatalogDetails({ init: true, metalake, catalog }))- await dispatch(setActivatedDetailsLoading(false))- await dispatch(fetchSchemas({ init: true, page: 'catalogs', metalake, catalog, catalogType }))- dispatch(+ await load(setActivatedDetailsLoading(true))+ await load(getCatalogDetails({ init: true, metalake, catalog }))+ await load(setActivatedDetailsLoading(false))+ await load(fetchSchemas({ init: true, page: 'catalogs', metalake, catalog, catalogType }))+ load(getCurrentEntityTags({init: true,metalake,@@ -151,7 +173,7 @@ const CatalogsListPage = () => {details: true}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -165,9 +187,9 @@ const CatalogsListPage = () => {if (paramsSize === 4 && catalog && catalogType && schema) {let catalogsList = store.catalogsif (!catalogsList.length) {- const { payload } = await dispatch(fetchCatalogs({ init: true, metalake }))+ const { payload } = await load(fetchCatalogs({ init: true, metalake }))catalogsList = payload?.catalogs || []- await dispatch(fetchSchemas({ init: true, metalake, catalog, catalogType }))+ await load(fetchSchemas({ init: true, metalake, catalog, catalogType }))}const currentCatalog = catalogsList.find(c => c.name === catalog)@@ -175,30 +197,31 @@ const CatalogsListPage = () => {currentCatalog?.provider === 'lakehouse-iceberg' &¤tCatalog?.properties?.['catalog-backend'] === 'jdbc'if (isIcebergJdbcCatalog) {- dispatch(fetchSchemas({ metalake, catalog, catalogType, parentSchema: schema }))+ load(fetchSchemas({ metalake, catalog, catalogType, parentSchema: schema }))}- dispatch(fetchFunctions({ init: true, metalake, catalog, schema }))+ load(fetchFunctions({ init: true, metalake, catalog, schema }))switch (catalogType) {case 'relational':- dispatch(fetchTables({ init: true, page: 'schemas', metalake, catalog, schema }))- dispatch(fetchViews({ init: true, metalake, catalog, schema }))+ load(fetchTables({ init: true, page: 'schemas', metalake, catalog, schema }))+ load(fetchViews({ init: true, metalake, catalog, schema }))+ load(fetchSemanticModels({ init: true, metalake, catalog, schema }))breakcase 'fileset':- dispatch(fetchFilesets({ init: true, page: 'schemas', metalake, catalog, schema }))+ load(fetchFilesets({ init: true, page: 'schemas', metalake, catalog, schema }))breakcase 'messaging':- dispatch(fetchTopics({ init: true, page: 'schemas', metalake, catalog, schema }))+ load(fetchTopics({ init: true, page: 'schemas', metalake, catalog, schema }))breakcase 'model':- dispatch(fetchModels({ init: true, page: 'schemas', metalake, catalog, schema }))+ load(fetchModels({ init: true, page: 'schemas', metalake, catalog, schema }))breakdefault:break}- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getSchemaDetails({ init: true, metalake, catalog, schema }))- await dispatch(setActivatedDetailsLoading(false))- dispatch(+ await load(setActivatedDetailsLoading(true))+ await load(getSchemaDetails({ init: true, metalake, catalog, schema }))+ await load(setActivatedDetailsLoading(false))+ load(getCurrentEntityTags({init: true,metalake,@@ -207,7 +230,7 @@ const CatalogsListPage = () => {details: true}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -218,21 +241,21 @@ const CatalogsListPage = () => {)}- if (paramsSize === 5 && catalog && catalogType && schema) {+ if ((paramsSize === 5 || (paramsSize === 6 && model && version)) && catalog && catalogType && schema) {if (!store.catalogs.length) {- await dispatch(fetchCatalogs({ metalake }))- await dispatch(fetchSchemas({ metalake, catalog, catalogType }))+ await load(fetchCatalogs({ metalake }))+ await load(fetchSchemas({ metalake, catalog, catalogType }))}if (table || fileset || topic || model) {switch (catalogType) {case 'relational':store.tables.length === 0 &&- (await dispatch(fetchTables({ init: true, page: 'schemas', metalake, catalog, schema })))- await dispatch(resetActivatedDetails())- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getTableDetails({ init: true, metalake, catalog, schema, table }))- await dispatch(setActivatedDetailsLoading(false))- dispatch(+ (await load(fetchTables({ init: true, page: 'schemas', metalake, catalog, schema })))+ await load(resetActivatedDetails())+ await load(setActivatedDetailsLoading(true))+ await load(getTableDetails({ init: true, metalake, catalog, schema, table }))+ await load(setActivatedDetailsLoading(false))+ load(getCurrentEntityTags({init: true,metalake,@@ -240,7 +263,7 @@ const CatalogsListPage = () => {metadataObjectFullName: `${catalog}.${schema}.${table}`}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -252,12 +275,12 @@ const CatalogsListPage = () => {breakcase 'fileset':store.filesets.length === 0 &&- (await dispatch(fetchFilesets({ init: true, page: 'schemas', metalake, catalog, schema })))- await dispatch(resetActivatedDetails())- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getFilesetDetails({ init: true, metalake, catalog, schema, fileset }))- await dispatch(setActivatedDetailsLoading(false))- dispatch(+ (await load(fetchFilesets({ init: true, page: 'schemas', metalake, catalog, schema })))+ await load(resetActivatedDetails())+ await load(setActivatedDetailsLoading(true))+ await load(getFilesetDetails({ init: true, metalake, catalog, schema, fileset }))+ await load(setActivatedDetailsLoading(false))+ load(getCurrentEntityTags({init: true,metalake,@@ -266,7 +289,7 @@ const CatalogsListPage = () => {details: true}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -278,11 +301,11 @@ const CatalogsListPage = () => {breakcase 'messaging':store.topics.length === 0 &&- (await dispatch(fetchTopics({ init: true, page: 'schemas', metalake, catalog, schema })))- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getTopicDetails({ init: true, metalake, catalog, schema, topic }))- await dispatch(setActivatedDetailsLoading(false))- dispatch(+ (await load(fetchTopics({ init: true, page: 'schemas', metalake, catalog, schema })))+ await load(setActivatedDetailsLoading(true))+ await load(getTopicDetails({ init: true, metalake, catalog, schema, topic }))+ await load(setActivatedDetailsLoading(false))+ load(getCurrentEntityTags({init: true,metalake,@@ -291,7 +314,7 @@ const CatalogsListPage = () => {details: true}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -303,12 +326,14 @@ const CatalogsListPage = () => {breakcase 'model':store.models.length === 0 &&- (await dispatch(fetchModels({ init: true, page: 'schemas', metalake, catalog, schema })))- await dispatch(fetchModelVersions({ init: true, metalake, catalog, schema, model }))- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getModelDetails({ init: true, metalake, catalog, schema, model }))- await dispatch(setActivatedDetailsLoading(false))- dispatch(+ (await load(fetchModels({ init: true, page: 'schemas', metalake, catalog, schema })))+ await load(fetchModelVersions({ init: true, metalake, catalog, schema, model }))+ await load(setActivatedDetailsLoading(true))++ // Version URLs render the parent model header and its version list.+ await load(getModelDetails({ init: true, metalake, catalog, schema, model, version }))+ await load(setActivatedDetailsLoading(false))+ load(getCurrentEntityTags({init: true,metalake,@@ -317,7 +342,7 @@ const CatalogsListPage = () => {details: true}))- dispatch(+ load(getCurrentEntityPolicies({init: true,metalake,@@ -332,33 +357,59 @@ const CatalogsListPage = () => {}}if (func) {- store.functions.length === 0 && (await dispatch(fetchFunctions({ init: true, metalake, catalog, schema })))- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getFunctionDetails({ init: true, metalake, catalog, schema, functionName: func }))- await dispatch(setActivatedDetailsLoading(false))+ store.functions.length === 0 && (await load(fetchFunctions({ init: true, metalake, catalog, schema })))+ await load(setActivatedDetailsLoading(true))+ await load(getFunctionDetails({ init: true, metalake, catalog, schema, functionName: func }))+ await load(setActivatedDetailsLoading(false))}if (view) {- store.views.length === 0 && (await dispatch(fetchViews({ init: true, metalake, catalog, schema })))- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getViewDetails({ init: true, metalake, catalog, schema, view }))- await dispatch(setActivatedDetailsLoading(false))+ store.views.length === 0 && (await load(fetchViews({ init: true, metalake, catalog, schema })))+ await load(setActivatedDetailsLoading(true))+ await load(getViewDetails({ init: true, metalake, catalog, schema, view }))+ await load(setActivatedDetailsLoading(false))}- }- if (paramsSize === 6 && version) {- if (!store.catalogs.length) {- await dispatch(fetchCatalogs({ metalake }))- await dispatch(fetchSchemas({ metalake, catalog, catalogType }))- await dispatch(fetchModels({ init: true, page: 'schemas', metalake, catalog, schema }))+ if (semanticModel) {+ if (canceled) return+ store.semanticModels.length === 0 &&+ (await load(fetchSemanticModels({ init: true, metalake, catalog, schema })))+ if (canceled) return+ load(resetActivatedDetails())+ load(setActivatedDetailsLoading(true))++ const detailRequest = load(+ getSemanticModelDetails({ init: true, metalake, catalog, schema, semanticModel })+ )+ await detailRequest+ if (canceled) return+ load(setActivatedDetailsLoading(false))+ load(+ getCurrentEntityTags({+ init: true,+ metalake,+ metadataObjectType: 'semantic_model',+ metadataObjectFullName: `${catalog}.${schema}.${semanticModel}`,+ details: true+ })+ )+ load(+ getCurrentEntityPolicies({+ init: true,+ metalake,+ metadataObjectType: 'semantic_model',+ metadataObjectFullName: `${catalog}.${schema}.${semanticModel}`,+ details: true+ })+ )}- await dispatch(setActivatedDetailsLoading(true))- await dispatch(getVersionDetails({ init: true, metalake, catalog, schema, model, version }))- await dispatch(setActivatedDetailsLoading(false))}}}fetchDependsData()- dispatch(setSelectedNodes(routeParams.catalog ? [buildNodePath(routeParams)] : []))+ return () => {+ canceled = true+ requests.forEach(request => request.abort())+ }}, [searchParams, dispatch])return (diff --git a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.jsnew file mode 100644index 0000000000..c77b25814d--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.js@@ -0,0 +1,287 @@+/*+ * 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 { Alert, 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, onSaved } = props+ const [confirmLoading, setConfirmLoading] = useState(false)+ const [isLoading, setIsLoading] = useState(false)+ const [cacheData, setCacheData] = useState()+ const [saveError, setSaveError] = 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 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(+ <ul className='list-disc pl-4'>+ {errors.map(error => (+ <li key={error}>{error}</li>+ ))}+ </ul>+ )+ : Promise.resolve()+ }++ const handleSubmit = e => {+ e.preventDefault()+ form+ .validateFields()+ .then(async values => {+ const { definition } = parseSemanticModelDefinition(values.definition)++ setConfirmLoading(true)+ setSaveError('')++ const submitData = {+ name: values.name.trim(),+ comment: values.comment,+ definition,+ properties: Object.fromEntries((values.properties || []).map(({ key, value }) => [key, value]))+ }++ let result+ if (editSemanticModel) {+ const updates = genSemanticModelUpdates(cacheData, submitData)+ if (updates.length) {+ result = await dispatch(+ updateSemanticModel({+ metalake,+ catalog,+ schema,+ semanticModel: editSemanticModel,+ expectedDefinition: cacheData.definition,+ data: { updates }+ })+ )+ }+ } else {+ result = await dispatch(createSemanticModel({ data: submitData, metalake, catalog, schema }))+ }++ if (result?.payload?.err || result?.error) {+ setSaveError(result.payload?.message || result.error?.message || 'Unable to save the Semantic Model.')+ } else {+ setOpen(false)+ if (result) await onSaved?.(result.payload)+ }+ })+ .catch(info => {+ if (info?.errorFields?.length) {+ form.scrollToField(info.errorFields[0].name)+ } else {+ console.error(info)+ }+ })+ .finally(() => setConfirmLoading(false))+ }++ const handleCancel = () => {+ setOpen(false)+ }++ return (+ <>+ <Modal+ title={!editSemanticModel ? 'Create Semantic Model' : 'Edit Semantic Model'}+ open={open}+ onOk={handleSubmit}+ okText='Submit'+ okButtonProps={{+ 'data-refer': 'handle-submit-semantic-model',+ disabled: isLoading || (!!editSemanticModel && !cacheData)+ }}+ maskClosable={false}+ keyboard={false}+ width={800}+ confirmLoading={confirmLoading}+ onCancel={handleCancel}+ >+ <Paragraph type='secondary'>+ {!editSemanticModel+ ? 'Create a new semantic model.'+ : `Edit the semantic model ${editSemanticModel}. The definition is replaced as a whole.`}+ </Paragraph>+ {saveError && (+ <Alert className='mb-3' type='error' showIcon message={saveError} description='Your edits are retained.' />+ )}+ <div+ className={cn('relative', {+ 'after:absolute after:-bottom-10 after:left-0 after:right-0 after:h-10 after:shadow-[0px_-10px_8px_-8px_rgba(5,5,5,0.1)]':+ topShadow,+ 'before:absolute before:-top-10 before:left-0 before:right-0 before:h-10 before:z-10 before:shadow-[0px_10px_8px_-8px_rgba(5,5,5,0.1)]':+ bottomShadow+ })}+ >+ <div className='overflow-auto' style={{ maxHeight: `${dialogContentMaxHeigth}px` }} ref={scrollRef}>+ <Spin spinning={isLoading}>+ <Form+ form={form}+ initialValues={defaultValues}+ layout='vertical'+ name='semanticModelForm'+ validateMessages={validateMessages}+ >+ <Form.Item+ name='name'+ label='Semantic Model Name'+ rules={[{ required: true }, { type: 'string', max: 64 }, { pattern: new RegExp(nameRegex) }]}+ messageVariables={{ label: 'semantic model name' }}+ >+ <Input data-refer='semantic-model-name-field' placeholder={mismatchName} />+ </Form.Item>+ <Form.Item name='comment' label='Comment'>+ <TextArea data-refer='semantic-model-comment-field' />+ </Form.Item>+ <Form.Item+ name='definition'+ label='Definition (advanced JSON)'+ extra='The datasets, relationships and metrics of the semantic model, as JSON. The server validates the sources.'+ rules={[{ required: true }, { validator: validateDefinition }]}+ messageVariables={{ label: 'definition' }}+ >+ <TextArea+ data-refer='semantic-model-definition-field'+ autoSize={{ minRows: 12, maxRows: 24 }}+ className='font-mono text-xs'+ placeholder={definitionPlaceholder}+ />+ </Form.Item>+ <Form.Item label='Properties'>+ <Form.List name='properties'>+ {(fields, subOpt) => (+ <RenderPropertiesFormItem+ fields={fields}+ subOpt={subOpt}+ form={form}+ isEdit={!!editSemanticModel}+ isDisable={false}+ />+ )}+ </Form.List>+ </Form.Item>+ </Form>+ </Spin>+ </div>+ </div>+ </Modal>+ </>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsx b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsxnew file mode 100644index 0000000000..d9d187e194--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/CreateSemanticModelDialog.test.jsx@@ -0,0 +1,209 @@+/*+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Simulate } from 'react-dom/test-utils'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer from '@/lib/store/metalakes'+import CreateSemanticModelDialog from './CreateSemanticModelDialog'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++const definition = { datasets: [{ name: 'orders', source: { namespace: ['sales', 'mart'], name: 'orders' } }] }++const model = {+ name: 'orders',+ comment: 'original',+ definition,+ properties: { name: 'literal', comment: '', definition: 'JSON' }+}+let root+let container+let close++beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle++ // jsdom has no pseudo-element layout; Ant Design uses this to measure scrollbars.+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve(url.endsWith('/orders') ? { semanticModel: model } : { identifiers: [] })+ )+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+ close = vi.fn()+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++const input = name => document.querySelector(`[data-refer="semantic-model-${name}-field"]`)+const button = () => document.querySelector('[data-refer="handle-submit-semantic-model"]')++const fill = async (name, value) => {+ await act(async () => Simulate.change(input(name), { target: { value } }))+}++const submit = async () => {+ await act(async () => {+ button().click()+ await new Promise(resolve => setTimeout(resolve, 50))+ })+}++const renderDialog = async edit => {+ const store = configureStore({ reducer: { metalakes: reducer, auth: () => ({ systemConfig: {} }) } })+ await act(async () =>+ root.render(+ <Provider store={store}>+ <CreateSemanticModelDialog+ open+ setOpen={close}+ metalake='demo'+ catalog='sales'+ schema='mart'+ editSemanticModel={edit ? 'orders' : undefined}+ />+ </Provider>+ )+ )+}++describe('semantic model editor', () => {+ it.each([false, true])('allows the model name ossie (edit=%s)', async edit => {+ defHttp.post.mockResolvedValue({ semanticModel: { ...model, name: 'ossie' } })+ defHttp.put.mockResolvedValue({ semanticModel: { ...model, name: 'ossie' } })+ await renderDialog(edit)+ await fill('name', 'ossie')+ if (!edit) await fill('definition', JSON.stringify(definition))+ await submit()+ expect(edit ? defHttp.put : defHttp.post).toHaveBeenCalledOnce()+ expect(close).toHaveBeenCalledWith(false)+ })++ it('blocks a nested expression error before submission', async () => {+ await renderDialog(false)+ await fill('name', 'orders')+ await fill(+ 'definition',+ JSON.stringify({ datasets: [{ ...definition.datasets[0], fields: [{ name: 'amount' }] }] })+ )+ await submit()+ expect(document.body.textContent).toContain('datasets[0].fields[0].expression must have non-empty dialects.')+ expect(defHttp.post).not.toHaveBeenCalled()+ expect(close).not.toHaveBeenCalled()+ })++ it.each([false, true])('retains input on failed save and supports retry (edit=%s)', async edit => {+ const write = edit ? defHttp.put : defHttp.post+ write.mockRejectedValueOnce(new Error('Invalid dataset source')).mockResolvedValue({ semanticModel: model })+ await renderDialog(edit)+ if (!edit) {+ await fill('name', 'orders')+ await fill('definition', JSON.stringify(definition))+ }+ await fill('comment', 'unsaved comment')+ const text = input('definition').value+ await submit()+ expect(write).toHaveBeenCalledTimes(1)+ expect(close).not.toHaveBeenCalled()+ expect(input('comment').value).toBe('unsaved comment')+ expect(input('definition').value).toBe(text)+ expect(button().classList.contains('ant-btn-loading')).toBe(false)+ await submit()+ expect(write).toHaveBeenCalledTimes(2)+ expect(close).toHaveBeenCalledWith(false)+ })++ it('does not replace properties named after form fields', async () => {+ defHttp.put.mockResolvedValue({ semanticModel: model })+ await renderDialog(true)+ await fill('comment', 'new comment')+ await submit()+ expect(defHttp.put.mock.calls[0][0].data).toEqual({+ updates: [{ '@type': 'updateComment', newComment: 'new comment' }]+ })+ })++ it.each(['constructor', 'toString'])('removes a property named %s through the editor', async name => {+ defHttp.get.mockResolvedValueOnce({ semanticModel: { ...model, properties: { [name]: 'value' } } })+ defHttp.put.mockResolvedValue({ semanticModel: model })+ await renderDialog(true)+ await act(async () =>+ document.querySelector('.ant-modal .lucide-minus').dispatchEvent(new MouseEvent('click', { bubbles: true }))+ )+ await submit()+ expect(defHttp.put.mock.calls[0]?.[0].data).toEqual({+ updates: [{ '@type': 'removeProperty', property: name }]+ })+ expect(close).toHaveBeenCalledWith(false)+ })++ it('disables saving when the model could not be loaded', async () => {+ defHttp.get.mockRejectedValue(new Error('Permission denied'))+ await renderDialog(true)+ expect(button().disabled).toBe(true)+ expect(close).not.toHaveBeenCalled()+ expect(defHttp.put).not.toHaveBeenCalled()+ })++ it('closes an unchanged edit without a write request', async () => {+ await renderDialog(true)+ await submit()+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(close).toHaveBeenCalledWith(false)+ })++ it('renders each validation problem separately without sending a request', async () => {+ await renderDialog(false)+ await fill('name', 'orders')+ await fill('definition', JSON.stringify({ datasets: [{ ...definition.datasets[0], fields: [{}, null] }] }))+ await submit()+ expect([...document.querySelectorAll('.ant-form-item-explain-error li')].map(item => item.textContent)).toEqual([+ 'datasets[0].fields[0] must have a non-empty name.',+ 'datasets[0].fields[1] must have a non-empty name.'+ ])+ expect(defHttp.post).not.toHaveBeenCalled()+ expect(close).not.toHaveBeenCalled()+ })+})diff --git a/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.js b/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.jsnew file mode 100644index 0000000000..776ab747be--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.js@@ -0,0 +1,247 @@+/*+ * 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 { useEffect, useRef, useState } from 'react'+import { Alert, Button, Modal, Space, Typography, Upload, message } from 'antd'+import Link from 'next/link'+import { UploadOutlined } from '@ant-design/icons'+import { importSemanticModelApi } from '@/lib/api/semanticModels'+import { useAppDispatch } from '@/lib/hooks/useStore'+import { fetchSemanticModels } from '@/lib/store/metalakes'+import { parseOssiePreview } from '@/lib/utils/ossiePreview'+import { semanticModelErrorMessage } from '@/lib/utils/semanticModel'++export default function ImportSemanticModelDialog({ open, setOpen, metalake, catalog, schema }) {+ const dispatch = useAppDispatch()+ const [file, setFile] = useState(null)+ const [loading, setLoading] = useState(false)+ const [error, setError] = useState('')+ const [errorStage, setErrorStage] = useState('file')+ const [selection, setSelection] = useState(null)+ const [reading, setReading] = useState(false)+ const selectionId = useRef(0)+ const errorRef = useRef(null)+ useEffect(() => {+ if (error) errorRef.current?.scrollIntoView({ block: 'nearest' })+ }, [error])+ useEffect(+ () => () => {+ selectionId.current+++ },+ []+ )++ const selectFile = async selected => {+ const id = ++selectionId.current+ setErrorStage('file')+ setError('')+ setSelection(null)+ setFile(selected)+ setReading(true)+ try {+ const document = await selected.text()+ const format = selected.name.toLowerCase().endsWith('.json') ? 'json' : 'yaml'+ const preview = parseOssiePreview(document, format)+ if (id === selectionId.current) setSelection({ document, format, preview })+ } catch (err) {+ if (id === selectionId.current) setError(semanticModelErrorMessage(err, 'Unable to read the OSSIE document.'))+ } finally {+ if (id === selectionId.current) setReading(false)+ }+ }++ const importDocument = async () => {+ if (!selection || reading || loading) return+ setLoading(true)+ setErrorStage('import')+ setError('')+ try {+ const { document, format } = selection++ const response = await importSemanticModelApi({+ metalake,+ catalog,+ schema,+ document,+ format+ })+ if (!response?.semanticModel?.name) throw new Error('Import returned an empty response.')+ await dispatch(fetchSemanticModels({ metalake, catalog, schema, init: true }))++ const params = new URLSearchParams({+ metalake,+ catalog,+ catalogType: 'relational',+ schema,+ semanticModel: response.semanticModel.name+ })+ message.success({+ key: 'semantic-model-import',+ content: (+ <Space wrap>+ <span>+ Semantic Model <strong>{response.semanticModel.name}</strong> imported+ </span>+ <Link href={`/catalogs?${params.toString()}`} onClick={() => message.destroy('semantic-model-import')}>+ View model+ </Link>+ </Space>+ ),+ duration: 10+ })+ setOpen(false)+ } catch (err) {+ setError(semanticModelErrorMessage(err, 'Failed to import the OSSIE document.'))+ } finally {+ setLoading(false)+ }+ }++ return (+ <Modal+ title='Import OSSIE document'+ style={{ top: 24 }}+ styles={{ body: { maxHeight: 'calc(100vh - 160px)', overflowY: 'auto' } }}+ open={open}+ onCancel={() => setOpen(false)}+ onOk={importDocument}+ okText='Import'+ confirmLoading={loading}+ okButtonProps={{+ disabled: !selection || reading,+ 'data-refer': 'import-semantic-model-submit',+ 'aria-label': 'Import'+ }}+ cancelButtonProps={{ disabled: loading }}+ closable={!loading}+ maskClosable={!loading}+ keyboard={!loading}+ >+ <Space direction='vertical' className='w-full' size='middle'>+ <Typography.Paragraph className='mb-0'>+ Select a standalone OSSIE YAML or JSON document to create a Semantic Model in this schema.+ </Typography.Paragraph>+ <div>+ <Typography.Text type='secondary' className='block'>+ Destination schema+ </Typography.Text>+ <Typography.Text strong>+ {metalake} / {catalog} / {schema}+ </Typography.Text>+ </div>+ {selection && (+ <div>+ <Typography.Text type='secondary' className='block'>+ OSSIE version+ </Typography.Text>+ <Typography.Text strong>{selection.preview.version}</Typography.Text>+ </div>+ )}+ <Upload+ accept='.yaml,.yml,.json'+ maxCount={1}+ showUploadList={false}+ disabled={loading}+ fileList={file ? [file] : []}+ beforeUpload={selected => {+ setErrorStage('file')+ setError('')+ if (!/\.(ya?ml|json)$/i.test(selected.name)) {+ selectionId.current+++ setSelection(null)+ setReading(false)+ setFile(null)+ setError('Select a .yaml, .yml, or .json file.')++ return Upload.LIST_IGNORE+ }+ selectFile(selected)++ return false+ }}+ >+ <Button aria-label={file ? 'Replace file' : 'Select file'} icon={<UploadOutlined />} disabled={loading}>+ {file ? 'Replace file' : 'Select file'}+ </Button>+ </Upload>+ {file && (+ <div className='flex items-center gap-3'>+ <div className='min-w-0 flex-1'>+ <Typography.Text className='block break-all'>{file.name}</Typography.Text>+ <Typography.Text type='secondary'>+ {file.name.toLowerCase().endsWith('.json') ? 'JSON' : 'YAML'} · {file.size.toLocaleString()} bytes+ </Typography.Text>+ </div>+ <Button+ disabled={loading}+ onClick={() => {+ selectionId.current+++ setSelection(null)+ setReading(false)+ setFile(null)+ setError('')+ }}+ >+ Remove file+ </Button>+ </div>+ )}+ {reading && <Typography.Text>Reading document...</Typography.Text>}+ {selection && (+ <>+ <section aria-label='Import preview' data-refer='import-preview'>+ <Typography.Text type='secondary' className='block'>+ Import preview+ </Typography.Text>+ <Typography.Title level={5} className='break-words' style={{ marginTop: 4 }}>+ {selection.preview.name}+ </Typography.Title>+ <dl className='m-0 grid grid-cols-4 gap-3'>+ {['datasets', 'fields', 'relationships', 'metrics'].map(key => (+ <div key={key}>+ <dt className='text-xs text-textSecondary'>{key[0].toUpperCase() + key.slice(1)}</dt>+ <dd className='m-0 text-lg font-medium'>{selection.preview[key]}</dd>+ </div>+ ))}+ </dl>+ </section>+ <Typography.Text type='secondary'>+ The server will validate the complete document and its sources on import.+ </Typography.Text>+ </>+ )}+ {error && (+ <div ref={errorRef} className='space-y-2'>+ <Alert+ type='error'+ showIcon+ message={errorStage === 'file' ? 'File preview failed' : 'Import failed'}+ description={<span className='whitespace-pre-wrap'>{error}</span>}+ />+ <Typography.Text type='secondary'>+ {errorStage === 'file'+ ? 'No import was attempted. Replace or remove the file to correct it.'+ : 'The selected file is retained. Retry the import or replace the file.'}+ </Typography.Text>+ </div>+ )}+ </Space>+ </Modal>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.test.jsx b/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.test.jsxnew file mode 100644index 0000000000..f3f9778656--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/ImportSemanticModelDialog.test.jsx@@ -0,0 +1,211 @@+/*+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { message } from 'antd'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer, { setLoadedNodes, setMetalakeTree } from '@/lib/store/metalakes'+import ImportSemanticModelDialog from './ImportSemanticModelDialog'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))+const originalScrollIntoView = Element.prototype.scrollIntoView+const schemaKey = '{{demo}}{{sales}}{{relational}}{{mart}}'+let root+let container+let close+let store++beforeEach(() => {+ vi.clearAllMocks()+ Element.prototype.scrollIntoView = vi.fn()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle++ // jsdom has no pseudo-element layout; Ant Design uses this to measure scrollbars.+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ defHttp.get.mockResolvedValue({ identifiers: [{ name: 'imported', namespace: ['demo', 'sales', 'mart'] }] })+ store = configureStore({ reducer: { metalakes: reducer } })+ store.dispatch(+ setMetalakeTree([{ key: schemaKey, node: 'schema', children: [{ key: 'table', node: 'table', name: 'orders' }] }])+ )+ store.dispatch(setLoadedNodes([schemaKey]))+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+ close = vi.fn()+})++afterEach(async () => {+ await act(async () => {+ root.unmount()+ message.destroy()+ })+ container.remove()+ Element.prototype.scrollIntoView = originalScrollIntoView+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++const renderDialog = async () => {+ await act(async () =>+ root.render(+ <Provider store={store}>+ <ImportSemanticModelDialog open setOpen={close} metalake='demo' catalog='sales' schema='mart' />+ </Provider>+ )+ )+}++const selectFile = async (name, text) => {+ const input = document.querySelector('input[type="file"]')+ const file = new File([text], name)+ file.text = async () => text+ Object.defineProperty(input, 'files', { configurable: true, value: [file] })+ await act(async () => input.dispatchEvent(new Event('change', { bubbles: true })))+}++const submit = async () => {+ await act(async () => {+ document.querySelector('[data-refer="import-semantic-model-submit"]').click()+ await new Promise(resolve => setTimeout(resolve, 50))+ })+}++describe('OSSIE import', () => {+ it.each([+ ['model.yaml', 'application/yaml', 'name: imported\nversion: 0.2.0.dev0\n'],+ ['model.YML', 'application/yaml', 'name: imported\nversion: 0.2.0.dev0\n'],+ ['model.json', 'application/json', '{ "version": "0.2.0.dev0", "name": "imported", "ai_context": "Guide" }']+ ])('imports %s unchanged and refreshes the list and loaded tree', async (name, type, text) => {+ defHttp.post.mockResolvedValue({ semanticModel: { name: 'imported' } })+ await renderDialog()+ expect(document.querySelector('[data-refer="import-semantic-model-submit"]').disabled).toBe(true)+ expect(document.body.textContent).toContain('demo / sales / mart')+ await selectFile(name, text)+ expect(document.body.textContent).toContain('Replace file')+ expect(document.body.textContent).toContain('Remove file')+ expect(document.body.textContent).toContain('bytes')+ expect(document.body.textContent).toContain('Import preview')+ expect(document.body.textContent).toContain('OSSIE version')+ expect(document.body.textContent).toContain('0.2.0.dev0')+ expect(document.body.textContent).toContain('demo / sales / mart')+ expect(document.body.textContent).toContain('imported')+ await submit()+ expect(defHttp.post).toHaveBeenCalledWith(+ expect.objectContaining({+ url: '/api/metalakes/demo/catalogs/sales/schemas/mart/semantic-models/ossie',+ data: text,+ headers: { 'Content-Type': type }+ }),+ { errorMessageMode: 'none' }+ )+ expect(defHttp.post.mock.calls[0][0].transformRequest[0](text)).toBe(text)+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['imported'])+ expect(store.getState().metalakes.metalakeTree[0].children.map(node => node.name)).toEqual(['orders', 'imported'])+ expect(close).toHaveBeenCalledWith(false)+ const link = document.querySelector('.ant-message a')+ expect(link.textContent).toBe('View model')+ expect(new URL(link.href).searchParams.get('semanticModel')).toBe('imported')+ })++ it('shows server validation errors, retains the file, and allows retry', async () => {+ defHttp.post+ .mockRejectedValueOnce({ response: { data: { message: 'datasets[0].source is invalid' } } })+ .mockResolvedValue({ semanticModel: { name: 'imported' } })+ await renderDialog()+ await selectFile('model.json', '{"name":"imported","version":"0.2.0"}')+ await submit()+ expect(document.querySelector('.ant-alert-message').textContent).toBe('Import failed')+ expect(Element.prototype.scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' })+ expect(document.querySelector('.ant-alert-description').textContent).toBe('datasets[0].source is invalid')+ expect(document.body.textContent).toContain('model.json')+ expect(close).not.toHaveBeenCalled()+ expect(defHttp.get).not.toHaveBeenCalled()+ await submit()+ expect(defHttp.post).toHaveBeenCalledTimes(2)+ expect(close).toHaveBeenCalledWith(false)+ })++ it('rejects malformed JSON at preview time without submitting it', async () => {+ await renderDialog()+ await selectFile('model.json', '{ invalid }')+ expect(document.querySelector('.ant-alert-message').textContent).toBe('File preview failed')+ expect(document.body.textContent).toContain('No import was attempted')+ expect(document.querySelector('[data-refer="import-semantic-model-submit"]').disabled).toBe(true)+ expect(defHttp.post).not.toHaveBeenCalled()+ })++ it('ignores a previous file read that finishes after the next selection', async () => {+ await renderDialog()+ let finish++ const text = new Promise(resolve => {+ finish = resolve+ })+ const file = new File([''], 'old.yaml')+ file.text = () => text+ const input = document.querySelector('input[type="file"]')+ Object.defineProperty(input, 'files', { configurable: true, value: [file] })+ await act(async () => input.dispatchEvent(new Event('change', { bubbles: true })))+ await selectFile('new.json', '{"name":"new","version":"0.2.0"}')+ await act(async () => finish('name: old\nversion: 0.2.0'))+ expect(document.querySelector('[data-refer="import-preview"]').textContent).toContain('new')+ expect(document.querySelector('[data-refer="import-preview"]').textContent).not.toContain('old')+ })++ it.each([+ ['model.txt', 'name: invalid', 'Select a .yaml, .yml, or .json file.'],+ ['model.yaml', ' ', 'The selected file is empty.']+ ])('rejects invalid selection %s', async (name, text, error) => {+ await renderDialog()+ await selectFile(name, text)+ await submit()+ expect(document.querySelector('.ant-alert-description').textContent).toBe(error)+ expect(defHttp.post).not.toHaveBeenCalled()+ expect(close).not.toHaveBeenCalled()+ })+})++it.each(['{"name":"model"}', '{"name":"model","version":2}', 'name: model\nversion: " "'])(+ 'blocks version-invalid preview %s',+ async text => {+ await renderDialog()+ await selectFile(text.startsWith('{') ? 'model.json' : 'model.yaml', text)+ expect(document.body.textContent).toContain('non-empty string version')+ expect(document.querySelector('[data-refer="import-semantic-model-submit"]').disabled).toBe(true)+ expect(defHttp.post).not.toHaveBeenCalled()+ }+)diff --git a/web-v2/web/src/app/catalogs/rightContent/RegisterModelDialog.js b/web-v2/web/src/app/catalogs/rightContent/RegisterModelDialog.jsindex a001d36d02..69e754077c 100644--- a/web-v2/web/src/app/catalogs/rightContent/RegisterModelDialog.js+++ b/web-v2/web/src/app/catalogs/rightContent/RegisterModelDialog.js@@ -45,7 +45,7 @@ const defaultValues = {}export default function RegisterModelDialog({ ...props }) {- const { open, setOpen, metalake, catalog, catalogType, schema, editModel, init } = props+ const { open, setOpen, metalake, catalog, catalogType, schema, editModel, version, init } = propsconst [confirmLoading, setConfirmLoading] = useState(false)const [isLoading, setIsLoading] = useState(false)const [cacheData, setCacheData] = useState()@@ -137,7 +137,7 @@ export default function RegisterModelDialog({ ...props }) {const reqData = { updates: genUpdates(cacheData, submitData) }if (reqData.updates.length) {await dispatch(- updateModel({ init, metalake, catalog, catalogType, schema, model: editModel, data: reqData })+ updateModel({ init, metalake, catalog, catalogType, schema, model: editModel, version, data: reqData }))}} else {diff --git a/web-v2/web/src/app/catalogs/rightContent/RightContent.js b/web-v2/web/src/app/catalogs/rightContent/RightContent.jsindex ef5639e407..acdd43c718 100644--- a/web-v2/web/src/app/catalogs/rightContent/RightContent.js+++ b/web-v2/web/src/app/catalogs/rightContent/RightContent.js@@ -67,6 +67,11 @@ const ViewDetailsPage = dynamic(() => import('./entitiesContent/ViewDetailsPage'ssr: false})+const SemanticModelDetailsPage = dynamic(() => import('./entitiesContent/SemanticModelDetailsPage'), {+ loading: () => <Loading height={'200px'} />,+ ssr: false+})+const RightContent = () => {const searchParams = useSearchParams()@@ -76,10 +81,12 @@ const RightContent = () => {const schema = searchParams.get('schema')const functionName = searchParams.get('function')const viewName = searchParams.get('view')+ const semanticModelName = searchParams.get('semanticModel')const entity =functionName ||viewName ||+ semanticModelName ||searchParams.get('table') ||searchParams.get('fileset') ||searchParams.get('topic') ||@@ -102,6 +109,9 @@ const RightContent = () => {if (viewName) {return <ViewDetailsPage />}+ if (semanticModelName) {+ return <SemanticModelDetailsPage key={searchParams.toString()} />+ }switch (catalogType) {case 'relational':return (@@ -150,9 +160,9 @@ const RightContent = () => {}return (- <div className='p-6' ref={ref}>+ <div className={semanticModelName ? 'flex h-full min-h-0 flex-col overflow-auto px-6 py-4' : 'p-6'} ref={ref}><Breadcrumb- className='mb-4'+ className={semanticModelName ? 'mb-2 shrink-0' : 'mb-4 shrink-0'}separator='>'items={[{@@ -242,7 +252,7 @@ const RightContent = () => {className='inline-block min-w-10 truncate'style={{ maxWidth: `calc((${width}px - 160px)/4)` }}>- {decodeURIComponent(entity)}+ {entity}</Link>) : (<span@@ -250,7 +260,7 @@ const RightContent = () => {className='inline-block min-w-10 truncate'style={{ maxWidth: `calc((${width}px - 160px)/4)` }}>- {decodeURIComponent(entity)}+ {entity}</span>)}diff --git a/web-v2/web/src/app/catalogs/rightContent/RightContent.test.jsx b/web-v2/web/src/app/catalogs/rightContent/RightContent.test.jsxnew file mode 100644index 0000000000..c76cda3820--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/RightContent.test.jsx@@ -0,0 +1,65 @@+/*+ * 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 { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import RightContent from './RightContent'++const navigation = vi.hoisted(() => ({ name: '', type: 'semanticModel' }))+vi.mock('next/navigation', () => ({+ useSearchParams: () =>+ new URLSearchParams({+ metalake: 'demo',+ catalog: 'sales',+ schema: 'mart',+ catalogType: 'relational',+ [navigation.type]: navigation.name+ })+}))+vi.mock('next/dynamic', () => ({ default: () => () => null }))+vi.mock('./entitiesContent/CatalogsPage', () => ({ default: () => null }))+vi.mock('use-resize-observer', () => ({ default: () => ({ width: 1000 }) }))++let root+let container++beforeEach(() => {+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.unstubAllGlobals()+})++it.each([+ ['semanticModel', 'sales%20model'],+ ['semanticModel', 'margin%'],+ ['function', 'sales%20model'],+ ['function', 'margin%']+])('renders the decoded %s breadcrumb %s without decoding it again', async (type, name) => {+ Object.assign(navigation, { type, name })+ await act(async () => root.render(<RightContent />))+ expect(container.querySelector('.ant-breadcrumb li:last-child [title]').textContent).toBe(name)+})diff --git a/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.js b/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.jsnew file mode 100644index 0000000000..bf4baa922b--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/SemanticMetadataEditor.js@@ -0,0 +1,403 @@+/*+ * 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 { useEffect, useRef, useState } from 'react'+import { Alert, Button, Form, Input, Modal, Select, Space, Tabs, theme } from 'antd'+import { isEqual } from 'lodash-es'+import { useAppDispatch } from '@/lib/hooks/useStore'+import { updateSemanticModel } from '@/lib/store/metalakes'+import { semanticDataTypes, validateSemanticModelDefinition } from '@/lib/utils/semanticModel'+import {+ getSemanticMetadataEntity,+ semanticMetadataFormValues,+ updateSemanticMetadata+} from '@/lib/utils/semanticMetadata'++export default function SemanticMetadataEditor(props) {+ try {+ getSemanticMetadataEntity(props.definition, props.target)+ } catch (error) {+ return (+ <Modal+ open+ title='Metadata unavailable'+ onCancel={props.onClose}+ footer={<Button onClick={props.onClose}>Close</Button>}+ >+ <Alert type='error' showIcon message={error.message} />+ </Modal>+ )+ }++ return <SemanticMetadataForm {...props} />+}++function SemanticMetadataForm({ definition, target, metalake, catalog, schema, semanticModel, onClose, onSaved }) {+ const { token } = theme.useToken()+ const dispatch = useAppDispatch()+ const [form] = Form.useForm()+ const [saving, setSaving] = useState(false)+ const [errors, setErrors] = useState([])+ const [section, setSection] = useState(target.kind === 'model' ? 'context' : target.section || 'basic')+ const [focusField, setFocusField] = useState(null)+ const [confirmDiscard, setConfirmDiscard] = useState(false)+ const errorRef = useRef(null)+ const expressionRef = useRef(null)++ useEffect(() => {+ if (!focusField) return++ // Tabs reveal their panel after the active key changes; focus once it is visible.+ const frame = requestAnimationFrame(() => {+ form.scrollToField(focusField, { block: 'nearest' })+ const input = form.getFieldInstance(focusField)+ if (input?.focus) input.focus()+ else if (focusField[0] === 'dialects') expressionRef.current?.focus()+ setFocusField(null)+ })++ return () => cancelAnimationFrame(frame)+ }, [section, focusField, form])++ useEffect(() => {+ if (errors.length) errorRef.current?.focus()+ }, [errors])++ // Keep the editing snapshot stable through list/detail refreshes while the dialog is open.+ const [original] = useState(definition)+ const entity = getSemanticMetadataEntity(original, target)+ const [initial] = useState(() => semanticMetadataFormValues(entity))+ const structuredContextInitialized = useRef(initial.contextFormat === 'structured')+ const contextFormat = Form.useWatch('contextFormat', form) || initial.contextFormat+ const hasExpression = ['field', 'metric'].includes(target.kind)+ const title = target.kind === 'model' ? 'Edit Model AI Context' : `Edit ${target.kind} ${target.name}`++ const close = () => {+ if (saving) return+ if (isEqual(initial, form.getFieldsValue(true))) onClose()+ else setConfirmDiscard(true)+ }++ const save = async () => {+ try {+ await form.validateFields()+ } catch (failure) {+ const name = failure.errorFields?.[0]?.name+ if (name) {+ setSection(+ name[0] === 'dialects'+ ? 'expressions'+ : ['contextFormat', 'contextText', 'instructions', 'synonyms', 'examples'].includes(name[0])+ ? 'context'+ : 'basic'+ )+ setFocusField(name)+ }++ return+ }+ const updated = updateSemanticMetadata(original, target, form.getFieldsValue(true))+ const problems = validateSemanticModelDefinition(updated)+ setErrors(problems)+ if (problems.length) return+ if (isEqual(original, updated)) {+ onClose()++ return+ }+ setSaving(true)+ try {+ const result = await dispatch(+ updateSemanticModel({+ metalake,+ catalog,+ schema,+ semanticModel,+ expectedDefinition: original,+ data: { updates: [{ '@type': 'replaceDefinition', definition: updated }] }+ })+ )+ if (result.error || result.payload?.err || !result.payload) {+ setErrors([result.payload?.message || result.error?.message || 'Unable to save metadata.'])++ return+ }+ await onSaved(result.payload)+ onClose()+ } finally {+ setSaving(false)+ }+ }++ const basic = (+ <>+ {target.kind === 'field' && (+ <>+ <Form.Item name='label' label='Label'>+ <Input />+ </Form.Item>+ <Form.Item name='timeDimension' label='Time dimension'>+ <Select+ allowClear+ placeholder='Not specified'+ options={[+ { value: true, label: 'Yes' },+ { value: false, label: 'No' }+ ]}+ />+ </Form.Item>+ </>+ )}+ {['dataset', 'field', 'metric'].includes(target.kind) && (+ <Form.Item name='description' label='Description'>+ <Input.TextArea autoSize={{ minRows: 2, maxRows: 6 }} />+ </Form.Item>+ )}+ {hasExpression && (+ <>+ <Form.Item name='datatype' label='Data type'>+ <Select allowClear placeholder='Not specified' options={semanticDataTypes.map(value => ({ value }))} />+ </Form.Item>+ </>+ )}+ {target.kind === 'relationship' && (+ <>+ <Space align='start' className='w-full'>+ {['from', 'to'].map(side => (+ <Form.Item+ key={side}+ name={side}+ label={side === 'from' ? 'From dataset' : 'To dataset'}+ rules={[{ required: true }]}+ >+ <Select+ className='min-w-48'+ options={original.datasets.map(dataset => ({ value: dataset.name, label: dataset.name }))}+ />+ </Form.Item>+ ))}+ </Space>+ {['fromColumns', 'toColumns'].map(side => (+ <Form.Item+ key={side}+ name={side}+ label={side === 'fromColumns' ? 'From columns' : 'To columns'}+ dependencies={[side === 'fromColumns' ? 'toColumns' : 'fromColumns']}+ rules={[+ {+ validator: (_, values) => {+ if (!values?.length || values.some(value => !value.trim()))+ return Promise.reject(new Error('Select at least one non-empty column.'))+ const other = form.getFieldValue(side === 'fromColumns' ? 'toColumns' : 'fromColumns')+ if (values.length !== other?.length)+ return Promise.reject(new Error('From and to columns must have matching counts.'))++ return Promise.resolve()+ }+ }+ ]}+ >+ <Select mode='tags' />+ </Form.Item>+ ))}+ </>+ )}+ </>+ )++ const expressions = (+ <div ref={expressionRef} tabIndex={-1}>+ <Form.List+ name='dialects'+ rules={[+ {+ validator: (_, values) => {+ if (!values?.length) return Promise.reject(new Error('Add at least one dialect expression.'))+ const names = values.map(value => value?.dialect).filter(Boolean)+ if (new Set(names).size !== names.length)+ return Promise.reject(new Error('Dialect names must be unique.'))++ return Promise.resolve()+ }+ }+ ]}+ >+ {(fields, { add, remove }, { errors: listErrors }) => (+ <>+ {fields.map(({ key, name, ...rest }) => (+ <div key={key} className='mb-3 rounded border border-borderColor p-3'>+ <Form.Item+ {...rest}+ name={[name, 'dialect']}+ label='Dialect'+ rules={[{ required: true, whitespace: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ {...rest}+ name={[name, 'expression']}+ label='SQL expression'+ rules={[{ required: true, whitespace: true }]}+ >+ <Input.TextArea className='font-mono' autoSize={{ minRows: 3, maxRows: 8 }} />+ </Form.Item>+ <Button onClick={() => remove(name)} aria-label={`Remove dialect ${name + 1}`}>+ Remove dialect+ </Button>+ </div>+ ))}+ <Form.ErrorList errors={listErrors} />+ <Button className='mb-3' onClick={() => add({ dialect: '', expression: '' })}>+ Add dialect+ </Button>+ </>+ )}+ </Form.List>+ </div>+ )++ const context = (+ <>+ <Form.Item name='contextFormat' label='Guidance format'>+ <Select+ options={[+ { value: 'text', label: 'Text', disabled: !!entity.aiContext && typeof entity.aiContext === 'object' },+ { value: 'structured', label: 'Structured' }+ ]}+ onChange={value => {+ if (value === 'structured' && !structuredContextInitialized.current) {+ form.setFieldValue('instructions', form.getFieldValue('contextText'))+ structuredContextInitialized.current = true+ }+ }}+ />+ </Form.Item>+ {contextFormat === 'text' ? (+ <Form.Item name='contextText' label='Guidance'>+ <Input.TextArea autoSize={{ minRows: 3, maxRows: 8 }} />+ </Form.Item>+ ) : (+ <>+ <Form.Item name='instructions' label='Instructions'>+ <Input.TextArea autoSize={{ minRows: 3, maxRows: 8 }} />+ </Form.Item>+ <Form.Item name='synonyms' label='Synonyms'>+ <Select mode='tags' />+ </Form.Item>+ <Form.List name='examples'>+ {(fields, { add, remove }) => (+ <>+ {fields.map(({ key, name, ...rest }) => (+ <div key={key} className='mb-3'>+ <Form.Item {...rest} name={name} label={`Example ${name + 1}`}>+ <Input.TextArea autoSize={{ minRows: 2, maxRows: 5 }} />+ </Form.Item>+ <Button onClick={() => remove(name)} aria-label={`Remove example ${name + 1}`}>+ Remove example+ </Button>+ </div>+ ))}+ <Button onClick={() => add('')}>Add example</Button>+ </>+ )}+ </Form.List>+ </>+ )}+ </>+ )++ return (+ <>+ <Modal+ open+ title={title}+ style={{ top: 24 }}+ width={760}+ styles={{ body: { maxHeight: 'calc(100vh - 160px)', overflowY: 'auto' } }}+ onCancel={close}+ onOk={save}+ okText='Save'+ okButtonProps={{ 'aria-label': 'Save' }}+ confirmLoading={saving}+ cancelButtonProps={{ disabled: saving }}+ closable={!saving}+ maskClosable={!saving}+ keyboard={!saving}+ >+ {errors.length > 0 && (+ <div ref={errorRef} tabIndex={-1} className='mb-3'>+ <Alert+ type='error'+ showIcon+ message='Could not save metadata'+ description={+ <>+ <ul className='m-0 pl-5'>+ {errors.map(error => (+ <li key={error}>{error}</li>+ ))}+ </ul>+ <p className='mb-0'>Your edits are retained.</p>+ </>+ }+ />+ </div>+ )}+ <Form+ form={form}+ initialValues={initial}+ layout='vertical'+ disabled={saving}+ name='semanticMetadata'+ onValuesChange={changed => {+ // Form.List does not revalidate its own rules when a nested field changes.+ if (changed.dialects) form.validateFields([['dialects']]).catch(() => {})+ }}+ >+ <Tabs+ tabBarStyle={{ position: 'sticky', top: 0, zIndex: 1, background: token.colorBgContainer }}+ activeKey={section}+ onChange={setSection}+ items={[+ ...(target.kind !== 'model' ? [{ key: 'basic', label: 'Basic information', children: basic }] : []),+ ...(hasExpression ? [{ key: 'expressions', label: 'Expressions', children: expressions }] : []),+ { key: 'context', label: 'AI Context', children: context }+ ].map(item => ({+ ...item,+ forceRender: true,+ children: <div className='pr-2'>{item.children}</div>+ }))}+ />+ </Form>+ </Modal>+ <Modal+ open={confirmDiscard}+ title='Discard unsaved changes?'+ okText='Discard changes'+ cancelText='Keep editing'+ okButtonProps={{ danger: true }}+ onOk={onClose}+ onCancel={() => setConfirmDiscard(false)}+ >+ Your metadata edits have not been saved.+ </Modal>+ </>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/ModelDetailsPage.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/ModelDetailsPage.jsindex 2b4e7148e6..5f10815ff8 100644--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/ModelDetailsPage.js+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/ModelDetailsPage.js@@ -454,6 +454,7 @@ export default function ModelDetailsPage({ ...props }) {catalog={catalog}schema={schema}editModel={model}+ version={searchParams.get('version')}init={true}/>)}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.jsindex 7c837a9cbc..452276901c 100644--- a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.js@@ -59,6 +59,7 @@ import {deleteTopic,deleteTable,deleteView,+ deleteSemanticModel,getTableDetails,getCurrentEntityOwner} from '@/lib/store/metalakes'@@ -70,6 +71,8 @@ import CreateFilesetDialog from '../CreateFilesetDialog'import RegisterModelDialog from '../RegisterModelDialog'import CreateTopicDialog from '../CreateTopicDialog'import CreateTableDialog from '../CreateTableDialog'+import CreateSemanticModelDialog from '../CreateSemanticModelDialog'+import ImportSemanticModelDialog from '../ImportSemanticModelDialog'import Functions from './Functions'const SetOwnerDialog = dynamic(() => import('@/components/SetOwnerDialog'), {@@ -89,6 +92,9 @@ export default function SchemaDetailsPage() {const [openTopic, setOpenTopic] = useState(false)const [openOwner, setOpenOwner] = useState(false)const [openModel, setOpenModel] = useState(false)+ const [openSemanticModel, setOpenSemanticModel] = useState(false)+ const [openImportSemanticModel, setOpenImportSemanticModel] = useState(false)+ const [editSemanticModel, setEditSemanticModel] = useState('')const [editTable, setEditTable] = useState('')const [editFileset, setEditFileset] = useState('')const [editTopic, setEditTopic] = useState('')@@ -103,6 +109,10 @@ export default function SchemaDetailsPage() {const catalog = searchParams.get('catalog')const schema = searchParams.get('schema')const store = useAppSelector(state => state.metalakes)++ const semanticModelRequest =+ store.semanticModelRequests[`{{${currentMetalake}}}{{${catalog}}}{{relational}}{{${schema}}}`]+ const semanticModelListLoading = !!semanticModelRequest?.inFlight.includes(store.semanticModelListRequestId)const dispatch = useAppDispatch()const [search, setSearch] = useState('')const [tabOptions, setTabOptions] = useState([])@@ -193,12 +203,14 @@ export default function SchemaDetailsPage() {? [{ label: 'Tables', key: 'Tables' },{ label: 'Views', key: 'Views' },+ { label: 'Semantic Models', key: 'Semantic Models' },{ label: 'Functions', key: 'Functions' },{ label: 'Associated Roles', key: 'Associated Roles' }]: [{ label: 'Tables', key: 'Tables' },{ label: 'Views', key: 'Views' },+ { label: 'Semantic Models', key: 'Semantic Models' },{ label: 'Functions', key: 'Functions' }])@@ -353,6 +365,18 @@ export default function SchemaDetailsPage() {children: undefined}))+ const semanticModelData = [...(store.semanticModels || [])]+ .filter(c => {+ if (search === '') return true++ return c.name.includes(search)+ })+ .map(entity => ({+ ...entity,+ key: entity.name,+ children: undefined+ }))+const subSchemaData = [...subSchemas].filter(item => {if (search === '') return true@@ -488,8 +512,10 @@ export default function SchemaDetailsPage() {validateFn = fn}+ const typeLabel = type === 'semanticModel' ? 'semantic model' : type+modalToUse.confirm({- title: `Are you sure to delete the ${type} ${entity}?`,+ title: `Are you sure to delete the ${typeLabel} ${entity}?`,icon: <ExclamationCircleFilled />,content: (<ConfirmInput name={entity} isManaged={isManaged} location={location} registerValidate={registerValidate} />@@ -513,6 +539,10 @@ export default function SchemaDetailsPage() {case 'relational':if (type === 'view') {await dispatch(deleteView({ metalake: currentMetalake, catalog, schema, view: entity }))+ } else if (type === 'semanticModel') {+ await dispatch(+ deleteSemanticModel({ metalake: currentMetalake, catalog, schema, semanticModel: entity })+ )} else {await dispatch(deleteTable({ metalake: currentMetalake, catalog, catalogType, schema, table: entity }))}@@ -631,6 +661,81 @@ export default function SchemaDetailsPage() {[currentMetalake, catalogType, catalog, schema, catalogData?.provider])+ const semanticModelColumns = useMemo(+ () => [+ {+ title: 'Semantic Model Name',+ dataIndex: 'name',+ key: 'name',+ width: 300,+ ellipsis: true,+ sorter: (a, b) => a?.name.toLowerCase().localeCompare(b?.name.toLowerCase()),+ render: name => (+ <Link+ data-refer={`semantic-model-link-${name}`}+ href={`/catalogs?metalake=${encodeURIComponent(currentMetalake)}&catalogType=${catalogType}&catalog=${encodeURIComponent(catalog)}&schema=${encodeURIComponent(schema)}&semanticModel=${encodeURIComponent(name)}`}+ >+ {name}+ </Link>+ )+ },+ {+ title: 'Tags',+ dataIndex: 'tags',+ key: 'tags',+ render: (_, record) => (+ <Tags metadataObjectType={'semantic_model'} metadataObjectFullName={`${catalog}.${schema}.${record.name}`} />+ )+ },+ {+ title: 'Actions',+ dataIndex: 'action',+ key: 'action',+ width: 100,+ render: (_, record) => (+ <Space size={4}>+ <Tooltip title='Edit'>+ <Button+ type='text'+ size='small'+ aria-label='Edit Semantic Model'+ data-refer={`edit-semantic-model-${record.name}`}+ icon={<Icons.Pencil className='size-4' />}+ onClick={() => {+ setEditSemanticModel(record.name)+ setOpenSemanticModel(true)+ }}+ />+ </Tooltip>+ <Tooltip title='Delete'>+ <Button+ type='text'+ size='small'+ aria-label='Delete Semantic Model'+ data-refer={`delete-semantic-model-${record.name}`}+ icon={<Icons.Trash2Icon className='size-4' />}+ onClick={() => showDeleteConfirm(record, 'semanticModel')}+ />+ </Tooltip>+ {anthEnable && (+ <Tooltip title='Set Owner'>+ <Button+ type='text'+ size='small'+ aria-label='Set Owner'+ data-refer={`set-owner-semantic-model-${record.name}`}+ icon={<Icons.UserPen className='size-4' />}+ onClick={() => handleSetOwner('semantic_model', `${catalog}.${schema}.${record.name}`)}+ />+ </Tooltip>+ )}+ </Space>+ )+ }+ ],+ [currentMetalake, catalogType, catalog, schema, anthEnable]+ )+const subSchemaColumns = useMemo(() => {return buildSchemaColumns({currentMetalake,@@ -660,6 +765,14 @@ export default function SchemaDetailsPage() {return { columns: viewColumns, minWidth: 100 }}, [viewColumns])+ const {+ resizableColumns: semanticModelResizableColumns,+ components: semanticModelComponents,+ tableWidth: semanticModelTableWidth+ } = useAntdColumnResize(() => {+ return { columns: semanticModelColumns, minWidth: 100 }+ }, [semanticModelColumns])+const {resizableColumns: subSchemaResizableColumns,components: subSchemaComponents,@@ -804,6 +917,62 @@ export default function SchemaDetailsPage() {components={viewComponents}/></>+ ) : tabKey === 'Semantic Models' ? (+ <>+ <Flex justify='flex-end' className='mb-4' gap='middle' wrap>+ <Search+ className='w-full sm:w-64'+ name='searchSemanticModelInput'+ placeholder='Search...'+ value={search}+ onChange={onSearchTable}+ />+ <Space wrap>+ <Button onClick={() => setOpenImportSemanticModel(true)}>Import OSSIE</Button>+ <Button+ data-refer='create-semantic-model-btn'+ type='primary'+ icon={<PlusOutlined />}+ onClick={() => {+ setEditSemanticModel('')+ setOpenSemanticModel(true)+ }}+ >+ Create Semantic Model+ </Button>+ </Space>+ </Flex>+ <Spin spinning={store.tableLoading || semanticModelListLoading}>+ <Table+ data-refer='semantic-model-list-grid'+ size='small'+ scroll={{ x: semanticModelTableWidth, y: 'max(20rem, calc(100vh - 37rem))' }}+ dataSource={semanticModelData}+ pagination={{ position: ['bottomCenter'], showSizeChanger: true }}+ columns={semanticModelResizableColumns}+ components={semanticModelComponents}+ />+ </Spin>+ {openImportSemanticModel && (+ <ImportSemanticModelDialog+ open={openImportSemanticModel}+ setOpen={setOpenImportSemanticModel}+ metalake={currentMetalake}+ catalog={catalog}+ schema={schema}+ />+ )}+ {openSemanticModel && (+ <CreateSemanticModelDialog+ open={openSemanticModel}+ setOpen={setOpenSemanticModel}+ metalake={currentMetalake}+ catalog={catalog}+ schema={schema}+ editSemanticModel={editSemanticModel}+ />+ )}+ </>) : (<><Flex justify='flex-end' className='mb-4'>diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.test.jsx b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.test.jsxnew file mode 100644index 0000000000..3a3cdd9648--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaDetailsPage.test.jsx@@ -0,0 +1,126 @@+/*+ * 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 { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer, { fetchSemanticModels, setActiveCatalogEntity } from '@/lib/store/metalakes'+import SchemaDetailsPage from './SchemaDetailsPage'++const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+vi.mock('next/navigation', () => ({+ useSearchParams: () => new URLSearchParams({ ...namespace, catalogType: 'relational' }),+ useRouter: () => ({ push: vi.fn() })+}))+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))+let store+let root+let container+beforeEach(() => {+ vi.resetAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ store = configureStore({ reducer: { metalakes: reducer, auth: () => ({ anthEnable: false, systemConfig: {} }) } })+ store.dispatch(setActiveCatalogEntity(namespace))+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})+afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++it.each(['success', 'failure', 'abort'])(+ 'shows the schema model-list spinner only while its list is pending: %s',+ async outcome => {+ let finish+ let fail+ defHttp.get.mockImplementation(({ url }) => {+ if (url.endsWith('/semantic-models'))+ return new Promise((resolve, reject) => {+ finish = resolve+ fail = reject+ })++ return Promise.resolve({ catalog: { name: 'sales', provider: 'jdbc-mysql' } })+ })+ await act(async () =>+ root.render(+ <Provider store={store}>+ <SchemaDetailsPage />+ </Provider>+ )+ )+ await act(async () =>+ [...document.querySelectorAll('[role="tab"]')].find(tab => tab.textContent === 'Semantic Models').click()+ )+ const spinning = () => container.querySelectorAll('.ant-spin-spinning').length++ const waitForSpinner = expected =>+ vi.waitFor(async () => {+ // Ant Design debounces spinner transitions, including when delay is zero.+ await act(async () => new Promise(resolve => setTimeout(resolve, 10)))+ expect(spinning()).toBe(expected)+ })+ expect(spinning()).toBe(0)+ let request+ await act(async () => {+ request = store.dispatch(fetchSemanticModels({ ...namespace, init: true }))+ })+ await waitForSpinner(1)+ await act(async () => {+ if (outcome === 'success') finish({ identifiers: [{ name: 'orders' }] })+ else if (outcome === 'failure') fail(new Error('Server unavailable'))+ else request.abort()+ await request+ })+ await waitForSpinner(0)+ if (outcome === 'success')+ expect(container.querySelector('[data-refer="semantic-model-list-grid"]').textContent).toContain('orders')+ let background+ await act(async () => {+ background = store.dispatch(fetchSemanticModels({ ...namespace, schema: 'other', init: true }))+ })+ expect(spinning()).toBe(0)+ await act(async () => {+ finish({ identifiers: [] })+ await background+ })+ }+)diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaSemanticModels.test.jsx b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaSemanticModels.test.jsxnew file mode 100644index 0000000000..72b38e6eea--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SchemaSemanticModels.test.jsx@@ -0,0 +1,132 @@+/*+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer, { fetchSemanticModels } from '@/lib/store/metalakes'+import SchemaDetailsPage from './SchemaDetailsPage'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))+vi.mock('next/navigation', () => ({+ useSearchParams: () =>+ new URLSearchParams({ metalake: 'demo', catalog: 'sales', schema: 'mart', catalogType: 'relational' })+}))+vi.mock('../../page', async () => {+ const { createContext } = await import('react')++ return { TreeRefContext: createContext(null) }+})+vi.mock('@/components/CustomTags', () => ({ default: () => null }))+vi.mock('@/components/PolicyTag', () => ({ default: () => null }))+vi.mock('next/dynamic', () => ({+ default: () => props => (+ <div data-testid='owner-target'>+ {props.metalake}/{props.metadataObjectType}/{props.metadataObjectFullName}+ </div>+ )+}))++let root+let container+let store++beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle++ // jsdom has no pseudo-element layout; Ant Design uses this to measure scrollbars.+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ defHttp.get.mockResolvedValue({+ catalog: { name: 'sales', provider: 'jdbc-mysql', properties: {} },+ owner: { name: 'tester', type: 'user' }+ })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('Semantic Model ownership action', () => {+ it.each([true, false])('gates Set Owner on authorization (enabled=%s)', async anthEnable => {+ store = configureStore({ reducer: { metalakes: reducer, auth: () => ({ anthEnable }) } })+ const args = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ store.dispatch(fetchSemanticModels.pending('load', args))+ store.dispatch(+ fetchSemanticModels.fulfilled(+ { semanticModels: [{ name: 'orders', namespace: ['demo', 'sales', 'mart'] }] },+ 'load',+ args+ )+ )+ await act(async () =>+ root.render(+ <Provider store={store}>+ <SchemaDetailsPage />+ </Provider>+ )+ )+ await act(async () =>+ [...document.querySelectorAll('[role="tab"]')].find(tab => tab.textContent === 'Semantic Models').click()+ )+ for (const [prefix, label] of [+ ['edit', 'Edit Semantic Model'],+ ['delete', 'Delete Semantic Model']+ ]) {+ const button = document.querySelector(`[data-refer="${prefix}-semantic-model-orders"]`)+ expect(button.tagName).toBe('BUTTON')+ expect(button.getAttribute('aria-label')).toBe(label)+ button.focus()+ expect(document.activeElement).toBe(button)+ }+ const action = document.querySelector('[data-refer="set-owner-semantic-model-orders"]')+ if (anthEnable) {+ expect(action).not.toBeNull()+ await act(async () => action.click())+ expect(document.querySelector('[data-testid="owner-target"]').textContent).toBe(+ 'demo/semantic_model/sales.mart.orders'+ )+ } else {+ expect(action).toBeNull()+ }+ })+})diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticMetadataSection.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticMetadataSection.jsnew file mode 100644index 0000000000..2378320076--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticMetadataSection.js@@ -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.+ */++import { Button, Collapse, theme } from 'antd'++export default function SemanticMetadataSection({ label, onEdit, children }) {+ const { token } = theme.useToken()++ return (+ <Collapse+ size='small'+ className='mb-3'+ items={[+ {+ key: 'metadata',+ label: (+ <span+ className='inline-flex min-h-6 items-center'+ style={{ fontSize: token.fontSize, fontWeight: token.fontWeightStrong, color: token.colorText }}+ >+ {label}+ </span>+ ),+ extra: onEdit && (+ <Button+ size='small'+ type='link'+ aria-label={`Edit ${label}`}+ onClick={event => {+ event.stopPropagation()+ onEdit()+ }}+ >+ Edit+ </Button>+ ),+ children+ }+ ]}+ />+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelAIContext.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelAIContext.jsnew file mode 100644index 0000000000..7b73fbb6a7--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelAIContext.js@@ -0,0 +1,107 @@+/*+ * 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 { Button, Tag, theme } from 'antd'+import SemanticMetadataSection from './SemanticMetadataSection'++export default function SemanticModelAIContext({ context, label = 'AI Context', inline = false, onEdit }) {+ const { token } = theme.useToken()+ if (!context || (typeof context === 'object' && !Object.keys(context).length)) return null++ const additional =+ typeof context === 'object'+ ? Object.fromEntries(+ Object.entries(context).filter(([key]) => !['instructions', 'synonyms', 'examples'].includes(key))+ )+ : {}++ const content = (+ <div className='whitespace-pre-wrap break-words'>+ {typeof context === 'string' ? (+ <p className='m-0'>{context}</p>+ ) : (+ <dl className='m-0 space-y-3'>+ {context.instructions && (+ <div>+ <dt className='text-xs font-medium' style={{ color: token.colorTextSecondary }}>+ Instructions+ </dt>+ <dd className='m-0'>{context.instructions}</dd>+ </div>+ )}+ {context.synonyms?.length > 0 && (+ <div>+ <dt className='text-xs font-medium' style={{ color: token.colorTextSecondary }}>+ Synonyms+ </dt>+ <dd className='m-0'>+ {context.synonyms.map((value, index) => (+ <Tag key={index} className='mb-1 whitespace-pre-wrap'>+ {value}+ </Tag>+ ))}+ </dd>+ </div>+ )}+ {context.examples?.length > 0 && (+ <div>+ <dt className='text-xs font-medium' style={{ color: token.colorTextSecondary }}>+ Examples+ </dt>+ <dd className='m-0'>+ <ul className='list-disc pl-5'>+ {context.examples.map((value, index) => (+ <li key={index}>{value}</li>+ ))}+ </ul>+ </dd>+ </div>+ )}+ {Object.keys(additional).length > 0 && (+ <div>+ <dt className='text-xs font-medium' style={{ color: token.colorTextSecondary }}>+ Additional context+ </dt>+ <dd className='m-0'>+ <pre className='m-0 whitespace-pre-wrap break-all font-mono text-xs'>+ {JSON.stringify(additional, null, 2)}+ </pre>+ </dd>+ </div>+ )}+ </dl>+ )}+ </div>+ )++ return inline ? (+ <>+ {onEdit && (+ <Button className='mb-3' onClick={onEdit}>+ Edit AI Context+ </Button>+ )}+ {content}+ </>+ ) : (+ <SemanticMetadataSection label={label} onEdit={onEdit}>+ {content}+ </SemanticMetadataSection>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.jsnew file mode 100644index 0000000000..18b2f6d883--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.js@@ -0,0 +1,846 @@+/*+ * 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 { catalogEntityKey } from '@/lib/utils/catalogEntity'+import { useEffect, useMemo, useRef, useState } from 'react'+import {+ Button,+ Divider,+ Flex,+ Input,+ Modal,+ Popover,+ Space,+ Spin,+ Table,+ Tabs,+ Tag,+ Tooltip,+ Typography,+ message+} from 'antd'+import styles from './SemanticModelDetailsPage.module.css'+import { useAntdColumnResize } from 'react-antd-column-resize'+import { useRouter, useSearchParams } from 'next/navigation'+import Tags from '@/components/CustomTags'+import GetOwner from '@/components/GetOwner'+import Icons from '@/components/Icons'+import PropertiesContent from '@/components/PropertiesContent'+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'+import { getSemanticModelDetails } from '@/lib/store/metalakes'+import { copyToClipboard } from '@/lib/utils'+import { formatToDateTime, isValidDate } from '@/lib/utils/date'+import { formatSemanticModelDefinition } from '@/lib/utils/semanticModel'+import { ColumnTypeColorEnum } from '@/config'+import SemanticModelExpression from './SemanticModelExpression'+import SemanticModelAIContext from './SemanticModelAIContext'+import SemanticModelExport from './SemanticModelExport'+import SemanticModelExtensions from './SemanticModelExtensions'+import CreateSemanticModelDialog from '../CreateSemanticModelDialog'+import SemanticMetadataEditor from '../SemanticMetadataEditor'++const { Title, Paragraph } = Typography++const sourceFullName = source => {+ if (!source) {+ return '-'+ }++ return [...(source.namespace || []), source.name].filter(Boolean).join('.')+}++const renderDataType = datatype => {+ if (!datatype) return <span>-</span>+ const type = { DateTime: 'timestamp', DateTimeTz: 'timestamp_tz' }[datatype] || datatype.toLowerCase()++ return <Tag color={ColumnTypeColorEnum[type] || undefined}>{datatype}</Tag>+}++const topAlignedColumns = columns =>+ columns.map(column => ({ ...column, onCell: () => ({ style: { verticalAlign: 'top' } }) }))++const renderColumns = columns => <span className='font-mono text-xs'>{(columns || []).join(', ') || '-'}</span>++const hasMetadata = entity => !!entity.aiContext || entity.customExtensions?.length > 0++export default function SemanticModelDetailsPage() {+ const searchParams = useSearchParams()+ const router = useRouter()+ const dispatch = useAppDispatch()+ const metalake = searchParams.get('metalake')+ const catalog = searchParams.get('catalog')+ const schema = searchParams.get('schema')+ const semanticModelName = searchParams.get('semanticModel')+ const auth = useAppSelector(state => state.auth)+ const { anthEnable } = auth+ const store = useAppSelector(state => state.metalakes)+ const detailsKey = catalogEntityKey({ metalake, catalog, schema, semanticModel: semanticModelName })+ const semanticModel = store.activatedDetailsKey === detailsKey ? store.activatedDetails : null+ const [tabKey, setTabKey] = useState('Datasets')+ const [openEdit, setOpenEdit] = useState(false)+ const [metadataEdit, setMetadataEdit] = useState(null)+ const [fieldContext, setFieldContext] = useState(null)+ const [metadataDetails, setMetadataDetails] = useState(null)+ const [expandedDefinition, setExpandedDefinition] = useState(false)+ const [fieldSearch, setFieldSearch] = useState('')+ const [metricSearch, setMetricSearch] = useState('')+ const [expandedDatasets, setExpandedDatasets] = useState([])++ const mounted = useRef(true)+ useEffect(() => {+ mounted.current = true++ return () => {+ mounted.current = false+ }+ }, [])++ const definition = semanticModel?.definition+ useEffect(() => {+ if (definition) return+ setMetadataEdit(null)+ setFieldContext(null)+ setMetadataDetails(null)+ setOpenEdit(false)+ setExpandedDefinition(false)+ }, [definition])+ const properties = semanticModel?.properties+ const createdAt = semanticModel?.audit?.createTime+ const createdAtText = !createdAt || !isValidDate(createdAt) ? '-' : formatToDateTime(createdAt)+ const lastModifiedAt = semanticModel?.audit?.lastModifiedTime+ const lastModifiedText = !lastModifiedAt || !isValidDate(lastModifiedAt) ? '-' : formatToDateTime(lastModifiedAt)+ const metadataObjectFullName = `${catalog}.${schema}.${semanticModelName}`++ const datasets = useMemo(+ () => (definition?.datasets || []).map(dataset => ({ ...dataset, key: dataset.name })),+ [definition]+ )++ const relationships = useMemo(+ () => (definition?.relationships || []).map(relationship => ({ ...relationship, key: relationship.name })),+ [definition]+ )++ const metrics = useMemo(+ () => (definition?.metrics || []).map(metric => ({ ...metric, key: metric.name })),+ [definition]+ )++ const fieldQuery = fieldSearch.trim().toLowerCase()++ const filteredDatasets = useMemo(+ () =>+ fieldQuery+ ? datasets+ .map(dataset => ({+ ...dataset,+ fields: (dataset.fields || []).filter(field =>+ [field.name, field.label].some(value => value?.toLowerCase().includes(fieldQuery))+ )+ }))+ .filter(dataset => dataset.fields.length)+ : datasets,+ [datasets, fieldQuery]+ )++ const filteredMetrics = useMemo(+ () => metrics.filter(metric => metric.name.toLowerCase().includes(metricSearch.trim().toLowerCase())),+ [metrics, metricSearch]+ )++ const renderMetadata = (entity, label, target) => (+ <>+ <SemanticModelAIContext+ context={entity?.aiContext}+ label={`${label} AI Context`}+ onEdit={+ target+ ? () => {+ setMetadataDetails(null)+ setMetadataEdit({ ...target, section: 'context' })+ }+ : undefined+ }+ />+ <SemanticModelExtensions extensions={entity?.customExtensions} label={`${label} Vendor Extensions`} />+ </>+ )++ const definitionText = useMemo(() => formatSemanticModelDefinition(definition), [definition])++ const tagContent = (+ <div>+ <Tags readOnly={true} metadataObjectType={'semantic_model'} metadataObjectFullName={metadataObjectFullName} />+ </div>+ )++ const propertyContent = <PropertiesContent properties={properties} />++ const onSaved = async updated => {+ if (!mounted.current) return+ if (updated.name !== semanticModelName) {+ const params = new URLSearchParams(searchParams.toString())+ params.set('semanticModel', updated.name)+ router.replace(`/catalogs?${params.toString()}`)+ } else {+ await dispatch(getSemanticModelDetails({ metalake, catalog, schema, semanticModel: updated.name, init: true }))+ }+ }++ const onCopyDefinition = async () => {+ try {+ await copyToClipboard(definitionText)+ message.success('Definition copied!')+ } catch (err) {+ console.error('Failed to copy definition: ', err)+ message.error('Failed to copy definition')+ }+ }++ const datasetColumns = useMemo(+ () => [+ {+ title: 'Dataset Name',+ dataIndex: 'name',+ key: 'name',+ fixed: 'left',+ width: 200,+ ellipsis: true,+ sorter: (a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())+ },+ {+ title: 'Source',+ dataIndex: 'source',+ key: 'source',+ width: 260,+ ellipsis: true,+ render: source => <span className='font-mono text-xs'>{sourceFullName(source)}</span>+ },+ {+ title: 'Primary Key',+ dataIndex: 'primaryKey',+ key: 'primaryKey',+ width: 180,+ ellipsis: true,+ render: renderColumns+ },+ {+ title: 'Unique Keys',+ dataIndex: 'uniqueKeys',+ key: 'uniqueKeys',+ width: 220,+ render: keys =>+ keys?.length ? (+ <Space direction='vertical' size={4}>+ {keys.map((columns, index) => (+ <Tag key={index}>{renderColumns(columns)}</Tag>+ ))}+ </Space>+ ) : (+ <span>-</span>+ )+ },+ {+ title: 'Fields',+ dataIndex: 'fields',+ key: 'fields',+ width: 80,+ render: fields => <span>{(fields || []).length}</span>+ },+ {+ title: 'Description',+ dataIndex: 'description',+ key: 'description',+ ellipsis: true,+ render: description => <span>{description || '-'}</span>+ },+ {+ title: 'Actions',+ key: 'actions',+ fixed: 'right',+ width: 90,+ render: (_, record) => (+ <Button+ size='small'+ aria-label={`Edit dataset ${record.name}`}+ onClick={() => setMetadataEdit({ kind: 'dataset', name: record.name })}+ >+ Edit+ </Button>+ )+ }+ ],+ []+ )++ const relationshipColumns = useMemo(+ () => [+ {+ title: 'Relationship Name',+ dataIndex: 'name',+ key: 'name',+ fixed: 'left',+ width: 220,+ ellipsis: true,+ sorter: (a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())+ },+ { title: 'From', dataIndex: 'from', key: 'from', width: 160, ellipsis: true },+ {+ title: 'From Columns',+ dataIndex: 'fromColumns',+ key: 'fromColumns',+ width: 200,+ ellipsis: true,+ render: renderColumns+ },+ { title: 'To', dataIndex: 'to', key: 'to', width: 160, ellipsis: true },+ {+ title: 'To Columns',+ dataIndex: 'toColumns',+ key: 'toColumns',+ ellipsis: true,+ render: renderColumns+ },+ {+ title: 'Actions',+ key: 'actions',+ fixed: 'right',+ width: 90,+ render: (_, record) => (+ <Button+ size='small'+ aria-label={`Edit relationship ${record.name}`}+ onClick={() => setMetadataEdit({ kind: 'relationship', name: record.name })}+ >+ Edit+ </Button>+ )+ }+ ],+ []+ )++ const metricColumns = useMemo(+ () => [+ {+ title: 'Metric Name',+ dataIndex: 'name',+ key: 'name',+ fixed: 'left',+ width: 200,+ ellipsis: true,+ sorter: (a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase())+ },+ {+ title: 'Data Type',+ dataIndex: 'datatype',+ key: 'datatype',+ width: 140,+ render: renderDataType+ },+ {+ title: 'Expression',+ dataIndex: 'expression',+ key: 'expression',+ render: (expression, record) => <SemanticModelExpression expression={expression} name={record.name} />+ },+ {+ title: 'Description',+ dataIndex: 'description',+ key: 'description',+ ellipsis: true,+ render: description => <span>{description || '-'}</span>+ },+ {+ title: 'Actions',+ key: 'actions',+ fixed: 'right',+ width: 90,+ render: (_, record) => (+ <Button+ size='small'+ aria-label={`Edit metric ${record.name}`}+ onClick={() => setMetadataEdit({ kind: 'metric', name: record.name })}+ >+ Edit+ </Button>+ )+ }+ ],+ []+ )++ const tabOptions = [+ { label: 'Overview', key: 'Overview' },+ { label: 'Datasets', key: 'Datasets' },+ { label: 'Relationships', key: 'Relationships' },+ { label: 'Metrics', key: 'Metrics' },+ { label: 'Definition', key: 'Definition' }+ ]++ const {+ resizableColumns: datasetResizableColumns,+ components: datasetComponents,+ tableWidth: datasetTableWidth+ } = useAntdColumnResize(() => {+ return { columns: topAlignedColumns(datasetColumns), minWidth: 100 }+ }, [datasetColumns])++ const {+ resizableColumns: relationshipResizableColumns,+ components: relationshipComponents,+ tableWidth: relationshipTableWidth+ } = useAntdColumnResize(() => {+ return { columns: topAlignedColumns(relationshipColumns), minWidth: 100 }+ }, [relationshipColumns])++ const {+ resizableColumns: metricResizableColumns,+ components: metricComponents,+ tableWidth: metricTableWidth+ } = useAntdColumnResize(() => {+ return { columns: topAlignedColumns(metricColumns), minWidth: 100 }+ }, [metricColumns])++ const expandedFieldsRow = dataset => (+ <section aria-label={`${dataset.name} fields`} className='py-2'>+ <div className='mb-3 flex items-center justify-between gap-3'>+ <Typography.Text strong>Fields ({(dataset.fields || []).length})</Typography.Text>+ {hasMetadata(dataset) && (+ <Button+ size='small'+ onClick={() =>+ setMetadataDetails({+ entity: dataset,+ label: dataset.name,+ target: { kind: 'dataset', name: dataset.name }+ })+ }+ >+ View dataset details+ </Button>+ )}+ </div>+ <div data-refer='semantic-model-fields-grid' className='divide-y divide-borderColor'>+ {(dataset.fields || []).map(field => (+ <section key={field.name} aria-label={`Field ${field.name}`} className='py-3'>+ <div className='mb-2 flex items-start justify-between gap-3'>+ <div className='min-w-0 break-words'>+ <Typography.Text strong>{field.name}</Typography.Text>+ {field.label && (+ <Typography.Text type='secondary' className='ml-2'>+ {field.label}+ </Typography.Text>+ )}+ </div>+ <Button+ size='small'+ aria-label={`Edit field ${field.name}`}+ onClick={() => setMetadataEdit({ kind: 'field', name: field.name, datasetName: dataset.name })}+ >+ Edit+ </Button>+ </div>+ <div className='grid grid-cols-1 gap-3 sm:grid-cols-2'>+ <div className='min-w-0'>+ <div className='mb-2'>+ {renderDataType(field.datatype)}+ <Typography.Text type='secondary'>+ Time dimension: {field.dimension?.isTime ? 'Yes' : 'No'}+ </Typography.Text>+ </div>+ {field.description && <Paragraph className='break-words'>{field.description}</Paragraph>}+ <Space wrap>+ {field.aiContext &&+ (typeof field.aiContext === 'string' || Object.keys(field.aiContext).length > 0) && (+ <Button+ size='small'+ aria-label={`${field.name} AI Context`}+ onClick={() => setFieldContext({ ...field, datasetName: dataset.name })}+ >+ AI Context+ </Button>+ )}+ {field.customExtensions?.length > 0 && (+ <Button+ size='small'+ aria-label={`${field.name} Vendor Extensions`}+ onClick={() =>+ setMetadataDetails({+ entity: field,+ label: field.name,+ target: { kind: 'field', name: field.name, datasetName: dataset.name }+ })+ }+ >+ Vendor Extensions+ </Button>+ )}+ </Space>+ </div>+ <SemanticModelExpression expression={field.expression} name={field.name} />+ </div>+ </section>+ ))}+ </div>+ </section>+ )++ return (+ <div className={styles.page} data-refer='semantic-model-details'>+ <Spin spinning={store.activatedDetailsLoading}>+ <Flex className='mb-2' gap='small' align='flex-start'>+ <div className='size-8'>+ <Icons.iconify icon='mdi:graph-outline' className='my-icon-large' />+ </div>+ <div className='relative bottom-1 min-w-0 flex-1'>+ <Title level={3} style={{ marginBottom: '0.125rem' }}>+ <div className='flex min-w-0 items-center gap-2'>+ <span title={semanticModelName} className='min-w-0 truncate'>+ {semanticModelName || ''}+ </span>+ <Tooltip title='Edit'>+ <Button+ type='text'+ size='small'+ aria-label='Edit Semantic Model'+ icon={<Icons.Pencil className='size-4' />}+ disabled={store.activatedDetailsLoading || !definition}+ onClick={() => setOpenEdit(true)}+ />+ </Tooltip>+ </div>+ </Title>+ <Paragraph type='secondary' className='truncate' title={semanticModel?.comment} style={{ marginBottom: 0 }}>+ {semanticModel?.comment}+ </Paragraph>+ </div>+ <div className='ml-auto shrink-0'>+ <SemanticModelExport+ key={metadataObjectFullName}+ metalake={metalake}+ catalog={catalog}+ schema={schema}+ semanticModel={semanticModelName}+ disabled={store.activatedDetailsLoading || !definition}+ />+ </div>+ </Flex>+ </Spin>+ <Tabs data-refer='details-tabs' activeKey={tabKey} onChange={setTabKey} items={tabOptions} />+ <Spin wrapperClassName={styles.body} spinning={store.activatedDetailsLoading}>+ {tabKey === 'Overview' && (+ <div className='min-h-0 overflow-auto'>+ <Space split={<Divider type='vertical' />} wrap={true} className='mb-2'>+ {anthEnable && (+ <Space size={4}>+ <Tooltip title='Owned' placement='top'>+ <Icons.User className='size-4' color='grey' />+ </Tooltip>+ <GetOwner+ metalake={metalake}+ metadataObjectType={'semantic_model'}+ metadataObjectFullName={metadataObjectFullName}+ />+ </Space>+ )}+ {semanticModel?.audit?.creator && (+ <Space size={4}>+ <Tooltip title='Creator' placement='top'>+ <Icons.UserPen className='size-4' color='grey' />+ </Tooltip>+ <span>{semanticModel.audit.creator}</span>+ </Space>+ )}+ <Space size={4}>+ <Tooltip title='Created' placement='top'>+ <span className='inline-flex'>+ <Icons.iconify icon='mdi:clock-outline' className='size-4' props={{ color: 'grey' }} />+ </span>+ </Tooltip>+ <span>{createdAtText}</span>+ </Space>+ <Space size={4}>+ <Tooltip title='Tags' placement='top'>+ <Icons.Tags className='size-4' color='grey' />+ </Tooltip>+ {store.currentEntityTags && store.currentEntityTags?.length > 0 ? (+ <Popover placement='bottom' title={<span>Tags</span>} content={tagContent}>+ <a className='text-defaultPrimary'>{store.currentEntityTags?.length}</a>+ </Popover>+ ) : (+ <a className='text-defaultPrimary'>0</a>+ )}+ </Space>+ <Space size={4}>+ <Tooltip title='Properties' placement='top'>+ <Icons.TableProperties className='size-4' color='grey' />+ </Tooltip>+ {properties && Object.keys(properties).length > 0 ? (+ <Popover placement='bottom' title={<span>Properties</span>} content={propertyContent}>+ <a className='text-defaultPrimary'>{Object.keys(properties).length}</a>+ </Popover>+ ) : (+ <a className='text-defaultPrimary'>0</a>+ )}+ </Space>+ <Space size={4} data-refer='semantic-model-policies'>+ <span>Policies</span>+ {store.currentEntityPolicies?.length > 0 ? (+ <Popover+ placement='bottom'+ title='Policies'+ content={+ <Space direction='vertical' size={4} className='max-w-sm'>+ {store.currentEntityPolicies.map(policy => (+ <Typography.Text key={policy.name} className='break-all'>+ {policy.name}+ </Typography.Text>+ ))}+ </Space>+ }+ >+ <a className='text-defaultPrimary' aria-label='View Semantic Model policies'>+ {store.currentEntityPolicies.length}+ </a>+ </Popover>+ ) : (+ <span>0</span>+ )}+ </Space>+ {semanticModel?.audit?.lastModifier && (+ <Space size={4} data-refer='semantic-model-last-modifier'>+ <Tooltip title='Last modified by'>+ <Icons.UserPen className='size-4' color='grey' />+ </Tooltip>+ <span>{semanticModel.audit.lastModifier}</span>+ </Space>+ )}+ {lastModifiedAt && (+ <Space size={4} data-refer='semantic-model-last-modified-time'>+ <Tooltip title='Last modified'>+ <Icons.History className='size-4' color='grey' />+ </Tooltip>+ <span>{lastModifiedText}</span>+ </Space>+ )}+ </Space>+ <Button+ className='mb-3 block'+ disabled={!definition}+ onClick={() => setMetadataEdit({ kind: 'model', section: 'context' })}+ >+ Edit Model AI Context+ </Button>+ {renderMetadata(definition, 'Model')}+ </div>+ )}+ {tabKey === 'Datasets' && (+ <>+ <Space className='mb-3 shrink-0'>+ <Input+ className='w-64'+ aria-label='Search fields'+ placeholder='Search field name or label'+ value={fieldSearch}+ onChange={event => setFieldSearch(event.target.value)}+ />+ {fieldSearch && <Button onClick={() => setFieldSearch('')}>Clear field search</Button>}+ </Space>+ <Table+ data-refer='semantic-model-datasets-grid'+ className={styles.table}+ size='small'+ tableLayout='fixed'+ scroll={{ x: datasetTableWidth, y: '100%' }}+ dataSource={filteredDatasets}+ columns={datasetResizableColumns}+ components={datasetComponents}+ expandable={{+ expandedRowRender: expandedFieldsRow,+ expandedRowKeys: fieldQuery ? filteredDatasets.map(dataset => dataset.key) : expandedDatasets,+ onExpandedRowsChange: keys => {+ if (!fieldQuery) setExpandedDatasets(keys)+ },+ rowExpandable: dataset => (dataset.fields || []).length > 0 || hasMetadata(dataset)+ }}+ pagination={{ position: ['bottomCenter'], showSizeChanger: true }}+ />+ </>+ )}+ {tabKey === 'Relationships' && (+ <Table+ data-refer='semantic-model-relationships-grid'+ className={styles.table}+ size='small'+ tableLayout='fixed'+ scroll={{ x: relationshipTableWidth, y: '100%' }}+ dataSource={relationships}+ columns={relationshipResizableColumns}+ components={relationshipComponents}+ expandable={{+ expandedRowRender: relationship =>+ renderMetadata(relationship, relationship.name, { kind: 'relationship', name: relationship.name }),+ rowExpandable: hasMetadata+ }}+ pagination={{ position: ['bottomCenter'], showSizeChanger: true }}+ />+ )}+ {tabKey === 'Metrics' && (+ <>+ <Space className='mb-3 shrink-0'>+ <Input+ aria-label='Search metrics'+ placeholder='Search metric name'+ value={metricSearch}+ onChange={event => setMetricSearch(event.target.value)}+ />+ {metricSearch && <Button onClick={() => setMetricSearch('')}>Clear metric search</Button>}+ </Space>+ <Table+ data-refer='semantic-model-metrics-grid'+ className={styles.table}+ size='small'+ tableLayout='fixed'+ scroll={{ x: metricTableWidth, y: '100%' }}+ dataSource={filteredMetrics}+ columns={metricResizableColumns}+ components={metricComponents}+ expandable={{+ expandedRowRender: metric => renderMetadata(metric, metric.name, { kind: 'metric', name: metric.name }),+ rowExpandable: hasMetadata+ }}+ pagination={{ position: ['bottomCenter'], showSizeChanger: true }}+ />+ </>+ )}+ {tabKey === 'Definition' &&+ (definitionText ? (+ <div className='flex min-h-0 flex-1 flex-col rounded border border-borderColor p-3'>+ <Space className='mb-3 shrink-0'>+ <Button onClick={() => setOpenEdit(true)}>Edit JSON definition</Button>+ <Tooltip title='Copy definition' placement='top'>+ <button+ type='button'+ aria-label='Copy definition'+ className='inline-flex cursor-pointer items-center rounded border border-borderColor bg-transparent p-1 text-textSecondary transition-colors hover:text-defaultPrimary'+ onClick={onCopyDefinition}+ >+ <Icons.Copy className='size-4' />+ </button>+ </Tooltip>+ <Button onClick={() => setExpandedDefinition(true)}>Expand definition</Button>+ </Space>+ <pre+ data-refer='semantic-model-definition'+ className='m-0 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-all font-mono text-sm leading-6'+ >+ {definitionText}+ </pre>+ </div>+ ) : (+ <Paragraph type='secondary'>No definition available.</Paragraph>+ ))}+ </Spin>+ {expandedDefinition && (+ <Modal+ open+ title={`${semanticModelName} definition`}+ width='100vw'+ style={{ top: 0, maxWidth: '100vw', margin: 0, paddingBottom: 0 }}+ styles={{+ content: { height: '100vh', display: 'flex', flexDirection: 'column', borderRadius: 0 },+ body: { flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }+ }}+ footer={null}+ onCancel={() => setExpandedDefinition(false)}+ >+ <Button className='mb-3 self-start' onClick={onCopyDefinition}>+ Copy definition+ </Button>+ <pre className='m-0 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-all font-mono text-sm leading-6'>+ {definitionText}+ </pre>+ </Modal>+ )}+ {definition && metadataDetails && (+ <Modal+ open+ title={`${metadataDetails.label} details`}+ footer={null}+ width={800}+ style={{ top: 24 }}+ styles={{ body: { maxHeight: 'calc(100vh - 140px)', overflowY: 'auto' } }}+ onCancel={() => setMetadataDetails(null)}+ >+ {renderMetadata(metadataDetails.entity, metadataDetails.label, metadataDetails.target)}+ </Modal>+ )}+ {definition && fieldContext && (+ <Modal+ open+ title={`${fieldContext.name} AI Context`}+ footer={null}+ style={{ top: 24 }}+ styles={{ body: { maxHeight: 'calc(100vh - 140px)', overflowY: 'auto' } }}+ onCancel={() => setFieldContext(null)}+ >+ <SemanticModelAIContext+ context={fieldContext.aiContext}+ inline+ onEdit={() => {+ setMetadataEdit({+ kind: 'field',+ name: fieldContext.name,+ datasetName: fieldContext.datasetName,+ section: 'context'+ })+ setFieldContext(null)+ }}+ />+ </Modal>+ )}+ {definition && metadataEdit && (+ <SemanticMetadataEditor+ definition={definition}+ target={metadataEdit}+ metalake={metalake}+ catalog={catalog}+ schema={schema}+ semanticModel={semanticModelName}+ onClose={() => setMetadataEdit(null)}+ onSaved={onSaved}+ />+ )}+ {openEdit && (+ <CreateSemanticModelDialog+ open={openEdit}+ setOpen={setOpenEdit}+ metalake={metalake}+ catalog={catalog}+ schema={schema}+ editSemanticModel={semanticModelName}+ onSaved={onSaved}+ />+ )}+ </div>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.module.css b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.module.cssnew file mode 100644index 0000000000..fc9b650335--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.module.css@@ -0,0 +1,84 @@+/*+ * 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.+ */++.page {+ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;+}++.page > :global(.ant-tabs) {+ flex-shrink: 0;+}++.page > :global(.ant-tabs) > :global(.ant-tabs-nav) {+ margin-bottom: 8px;+}++.body {+ flex: 1;+ min-height: 0;+}++.body > :global(.ant-spin-container) {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+}++.table {+ flex: 1;+ min-height: 0;+}++.table :global(.ant-spin-nested-loading) {+ height: 100%;+}++.table :global(.ant-spin-nested-loading),+.table :global(.ant-spin-container),+.table :global(.ant-table),+.table :global(.ant-table-container) {+ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;+}++.table :global(.ant-table-body) {+ flex: 1;+ min-height: 0;+ max-height: none !important;+ overflow: auto !important;+}++.table :global(.ant-table-header),+.table :global(.ant-table-pagination) {+ flex-shrink: 0;+}++/* On short windows, scroll the heading away instead of squeezing expanded fields into a sliver. */+@media (max-height: 750px) {+ .page {+ flex-shrink: 0;+ min-height: 580px;+ }+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsx b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsxnew file mode 100644index 0000000000..9d4826fba2--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelDetailsPage.test.jsx@@ -0,0 +1,1108 @@+/*+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { Simulate } from 'react-dom/test-utils'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer, {+ getSemanticModelDetails,+ getTableDetails,+ resetActivatedDetails,+ getCurrentEntityPolicies+} from '@/lib/store/metalakes'+import SemanticModelDetailsPage from './SemanticModelDetailsPage'+import SemanticMetadataEditor from '../SemanticMetadataEditor'++const navigation = vi.hoisted(() => ({ push: vi.fn(), replace: vi.fn(), name: 'sales model' }))++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), put: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))+vi.mock('next/navigation', () => ({+ useRouter: () => navigation,+ useSearchParams: () =>+ new URLSearchParams({+ metalake: 'demo',+ catalog: 'sales',+ schema: 'mart',+ semanticModel: navigation.name,+ catalogType: 'relational'+ })+}))+vi.mock('@/components/GetOwner', () => ({ default: () => null }))+vi.mock('@/components/CustomTags', () => ({ default: () => null }))++let root+let container+let store+let downloads++beforeEach(() => {+ vi.clearAllMocks()+ navigation.name = 'sales model'+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ const getComputedStyle = window.getComputedStyle++ // jsdom has no pseudo-element layout; Ant Design uses this to measure scrollbars.+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => getComputedStyle(element))+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }))+ })+ downloads = []+ vi.stubGlobal(+ 'URL',+ class extends URL {+ static createObjectURL = vi.fn(() => 'blob:ossie')+ static revokeObjectURL = vi.fn()+ }+ )+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function () {+ downloads.push({ href: this.href, filename: this.download })+ })+ store = configureStore({ reducer: { metalakes: reducer, auth: () => ({ anthEnable: false }) } })+ defHttp.get+ .mockReset()+ .mockImplementation(() =>+ Promise.resolve({ semanticModel: store.getState().metalakes.activatedDetails, identifiers: [] })+ )+ defHttp.put.mockReset()+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++const definitionWith = context => ({+ aiContext: context('model'),+ datasets: [+ {+ name: 'orders',+ source: { namespace: ['sales', 'mart'], name: 'orders' },+ aiContext: context('dataset'),+ fields: [+ {+ name: 'amount',+ expression: { dialects: [{ dialect: 'ANSI_SQL', expression: 'amount' }] },+ aiContext: context('field')+ }+ ]+ }+ ],+ relationships: [+ {+ name: 'customers',+ from: 'orders',+ to: 'orders',+ fromColumns: ['amount'],+ toColumns: ['amount'],+ aiContext: context('relationship')+ }+ ],+ metrics: [+ {+ name: 'revenue',+ expression: { dialects: [{ dialect: 'ANSI_SQL', expression: 'SUM(amount)' }] },+ aiContext: context('metric')+ }+ ]+})++const renderDetails = async (definition, details = {}) => {+ const args = { init: true, metalake: 'demo', catalog: 'sales', schema: 'mart', semanticModel: navigation.name }+ store.dispatch(getSemanticModelDetails.pending('load', args))+ store.dispatch(+ getSemanticModelDetails.fulfilled(+ { semanticModel: { name: navigation.name, definition, properties: {}, ...details }, init: true },+ 'load',+ args+ )+ )+ await act(async () =>+ root.render(+ <Provider store={store}>+ <SemanticModelDetailsPage />+ </Provider>+ )+ )+}++const click = async element => {+ expect(element).toBeTruthy()+ await act(async () => {+ element.click()+ await new Promise(resolve => setTimeout(resolve, 50))+ })+}++const findText = (selector, text) =>+ [...document.querySelectorAll(selector)].find(element => element.textContent === text)+const expandContext = async label => click(findText('.ant-collapse-header-text', label))+const selectTab = async name => click(findText('[role="tab"]', name))++const exportDocument = async format => {+ await click(findText('button', 'Export OSSIE'))+ await click(findText('[role="menuitem"]', `Download ${format.toUpperCase()}`))+}++const readBlob = blob =>+ new Promise(resolve => {+ const reader = new FileReader()+ reader.onload = () => resolve(reader.result)+ reader.readAsText(blob)+ })++describe('Semantic Model AI guidance', () => {+ it.each(['text', 'structured'])('shows %s context next to all five metadata levels', async form => {+ const context = label =>+ form === 'text'+ ? `${label} guidance\nSecond line`+ : {+ instructions: `${label} guidance`,+ synonyms: [`${label} alias`],+ examples: [`${label} example`],+ extra: { scope: label }+ }+ await renderDetails(definitionWith(context))++ const verify = label => {+ expect(document.body.textContent).toContain(`${label} guidance`)+ if (form === 'structured') {+ expect(document.body.textContent).toContain(`${label} alias`)+ expect(document.body.textContent).toContain(`${label} example`)+ expect(document.body.textContent).toContain(`"scope": "${label}"`)+ }+ }+ await selectTab('Overview')+ await expandContext('Model AI Context')+ verify('model')+ await selectTab('Datasets')+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ await click(findText('button', 'View dataset details'))+ await expandContext('orders AI Context')+ verify('dataset')+ await click(document.querySelector('.ant-modal-close'))+ await click(document.querySelector('[aria-label="amount AI Context"]'))+ verify('field')+ expect(document.querySelector('.ant-modal .ant-collapse')).toBeNull()+ await click(document.querySelector('.ant-modal-close'))+ await selectTab('Relationships')+ await click(+ document.querySelector('[data-refer="semantic-model-relationships-grid"] button.ant-table-row-expand-icon')+ )+ await expandContext('customers AI Context')+ verify('relationship')+ await selectTab('Metrics')+ await click(document.querySelector('[data-refer="semantic-model-metrics-grid"] button.ant-table-row-expand-icon'))+ await expandContext('revenue AI Context')+ verify('metric')+ expect(document.querySelector('[data-refer="semantic-model-definition"]')).toBeNull()+ })++ it('supports a dataset with context and no fields', async () => {+ await renderDetails({ datasets: [{ name: 'orders', aiContext: 'Dataset only' }] })+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ await click(findText('button', 'View dataset details'))+ await expandContext('orders AI Context')+ expect(document.body.textContent).toContain('Dataset only')+ })+})++describe('OSSIE downloads', () => {+ it.each([+ ['yaml', 'name: sales model\nai_context: Guide\n'],+ ['json', '{ "name": "sales model", "ai_context": "Guide" }']+ ])('downloads the server %s document unchanged', async (format, content) => {+ defHttp.get.mockResolvedValue(content)+ await renderDetails({ datasets: [] })+ await exportDocument(format)+ expect(defHttp.get).toHaveBeenCalledWith(+ {+ url: '/api/metalakes/demo/catalogs/sales/schemas/mart/semantic-models/sales%20model/ossie',+ params: { format },+ responseType: 'text'+ },+ { errorMessageMode: 'none' }+ )+ expect(downloads).toEqual([{ href: 'blob:ossie', filename: `sales_model.ossie.${format}` }])+ const blob = URL.createObjectURL.mock.calls[0][0]+ expect(blob.type).toBe(format === 'json' ? 'application/json' : 'application/yaml')+ expect(await readBlob(blob)).toBe(content)+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:ossie')+ })++ it('shows a server error instead of downloading it and supports retry', async () => {+ defHttp.get+ .mockRejectedValueOnce({ response: { data: '{"message":"Model no longer exists"}' } })+ .mockResolvedValue('name: sales model')+ await renderDetails({ datasets: [] })+ await exportDocument('yaml')+ expect(document.querySelector('.ant-alert-description').textContent).toBe('Model no longer exists')+ expect(downloads).toEqual([])+ await exportDocument('yaml')+ expect(downloads).toHaveLength(1)+ expect(document.querySelector('.ant-alert')).toBeNull()+ })+})++describe('Semantic Model metadata', () => {+ it('keeps composite unique keys grouped and shows labels alongside field names', async () => {+ await renderDetails({+ datasets: [+ {+ name: 'orders',+ uniqueKeys: [['customer_id', 'order_id'], ['external_id']],+ fields: [{ name: 'amount', label: 'Order Amount (USD)' }, { name: 'id' }]+ }+ ]+ })+ const tags = document.querySelectorAll('[data-refer="semantic-model-datasets-grid"] .ant-table-tbody .ant-tag')+ expect([...tags].map(tag => tag.textContent)).toEqual(['customer_id, order_id', 'external_id'])+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ const fields = document.querySelector('[data-refer="semantic-model-fields-grid"]')+ expect(fields.textContent).toContain('amount')+ expect(fields.textContent).toContain('Order Amount (USD)')+ expect(fields.textContent).toContain('id')+ expect(fields.textContent).not.toContain('undefined')+ })++ it('exposes complete vendor extensions at all levels, independently of AI context', async () => {+ const extension = name => [+ { vendorName: `${name} vendor`, data: `line 1\n{"private":"${name}","nested":{"flag":true}}` }+ ]+ const definition = definitionWith(() => undefined)+ definition.customExtensions = extension('model')+ definition.datasets[0].customExtensions = extension('dataset')+ definition.datasets[0].fields[0].customExtensions = extension('field')+ definition.relationships[0].customExtensions = extension('relationship')+ definition.metrics[0].customExtensions = extension('metric')+ await renderDetails(definition)++ const verify = async name => {+ const label = {+ model: 'Model',+ dataset: 'orders',+ field: 'amount',+ relationship: 'customers',+ metric: 'revenue'+ }[name]+ await expandContext(`${label} Vendor Extensions`)+ expect([...document.querySelectorAll('pre')].some(pre => pre.textContent === extension(name)[0].data)).toBe(true)+ }+ await selectTab('Overview')+ await verify('model')+ await selectTab('Datasets')+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ await click(findText('button', 'View dataset details'))+ await verify('dataset')+ await click(document.querySelector('.ant-modal-close'))+ await click(document.querySelector('[aria-label="amount Vendor Extensions"]'))+ await verify('field')+ await click(document.querySelector('.ant-modal-close'))+ await selectTab('Relationships')+ await click(+ document.querySelector('[data-refer="semantic-model-relationships-grid"] button.ant-table-row-expand-icon')+ )+ await verify('relationship')+ await selectTab('Metrics')+ await click(document.querySelector('[data-refer="semantic-model-metrics-grid"] button.ant-table-row-expand-icon'))+ await verify('metric')+ })++ it('displays modification audit values when present', async () => {+ await renderDetails(+ { datasets: [] },+ { audit: { lastModifier: 'editor', lastModifiedTime: '2026-10-13T05:00:00Z' } }+ )+ await selectTab('Overview')+ expect(document.querySelector('[data-refer="semantic-model-last-modifier"]').textContent).toBe('editor')+ expect(document.querySelector('[data-refer="semantic-model-last-modified-time"]').textContent).not.toBe('-')+ })++ it('omits absent modification audit values', async () => {+ await renderDetails({ datasets: [] })+ await selectTab('Overview')+ expect(document.querySelector('[data-refer="semantic-model-last-modifier"]')).toBeNull()+ expect(document.querySelector('[data-refer="semantic-model-last-modified-time"]')).toBeNull()+ })+})++describe('editing from Semantic Model details', () => {+ it.each([false, true])(+ 'preserves failed edits, then refreshes or navigates after saving (rename=%s)',+ async rename => {+ navigation.name = 'orders'+ const definition = { datasets: [{ name: 'orders', source: { namespace: ['sales', 'mart'], name: 'orders' } }] }+ let model = { name: 'orders', definition, properties: {}, comment: 'original' }++ const updated = {+ ...model,+ name: rename ? 'orders_v2' : 'orders',+ comment: 'saved comment',+ audit: { lastModifier: 'editor' }+ }+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve(url.endsWith('/semantic-models') ? { identifiers: [] } : { semanticModel: model })+ )+ defHttp.put.mockRejectedValueOnce(new Error('Invalid source')).mockImplementation(() => {+ model = updated++ return Promise.resolve({ semanticModel: updated })+ })+ await renderDetails(definition, model)+ await click(document.querySelector('[aria-label="Edit Semantic Model"]'))+ await act(async () => {+ Simulate.change(document.querySelector('[data-refer="semantic-model-comment-field"]'), {+ target: { value: 'saved comment' }+ })+ if (rename)+ Simulate.change(document.querySelector('[data-refer="semantic-model-name-field"]'), {+ target: { value: 'orders_v2' }+ })+ })+ await click(document.querySelector('[data-refer="handle-submit-semantic-model"]'))+ expect(document.querySelector('[data-refer="semantic-model-comment-field"]').value).toBe('saved comment')+ expect(navigation.replace).not.toHaveBeenCalled()+ expect(store.getState().metalakes.activatedDetails.comment).toBe('original')+ await click(document.querySelector('[data-refer="handle-submit-semantic-model"]'))+ expect(defHttp.put).toHaveBeenCalledTimes(2)+ if (rename) {+ const destination = new URL(navigation.replace.mock.calls[0][0], 'http://localhost')+ expect(destination.searchParams.get('semanticModel')).toBe('orders_v2')+ expect(destination.searchParams.get('catalogType')).toBe('relational')+ expect(destination.searchParams.get('schema')).toBe('mart')+ } else {+ expect(navigation.replace).not.toHaveBeenCalled()+ expect(store.getState().metalakes.activatedDetails.comment).toBe('saved comment')+ await selectTab('Overview')+ expect(document.querySelector('[data-refer="semantic-model-last-modifier"]').textContent).toBe('editor')+ }+ expect(document.querySelector('[data-refer="handle-submit-semantic-model"]')).toBeNull()+ }+ )+})++describe('Semantic Model accessible details', () => {+ it.each(['sales%20model', 'margin%'])('preserves the already decoded name %s', async name => {+ navigation.name = name+ await renderDetails({ datasets: [] })+ expect(container.querySelector('h3 span[title]').textContent).toBe(name)+ })++ it('labels the copy action', async () => {+ await renderDetails({ datasets: [] })+ await selectTab('Definition')+ expect(container.querySelector('button[aria-label="Copy definition"]')).not.toBeNull()+ })+})++describe('focused semantic metadata editing', () => {+ const selectOption = async (id, label) => {+ await act(async () =>+ Simulate.mouseDown(document.querySelector(id).closest('.ant-select').querySelector('.ant-select-selector'))+ )+ await click(findText('.ant-select-item-option-content', label))+ }++ it.each(['field', 'metric'])('selects and clears the optional %s data type', async kind => {+ const definition = definitionWith(() => null)+ const entity = kind === 'field' ? definition.datasets[0].fields[0] : definition.metrics[0]+ entity.datatype = 'Decimal'+ await renderDetails(definition)+ if (kind === 'field') {+ await click(+ document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon')+ )+ await click(document.querySelector('[aria-label="Edit field amount"]'))+ } else {+ await selectTab('Metrics')+ await click(document.querySelector('[aria-label="Edit metric revenue"]'))+ }+ await selectOption('#semanticMetadata_datatype', 'DateTimeTz')+ const selector = document.querySelector('#semanticMetadata_datatype').closest('.ant-select')+ expect(selector.textContent).toContain('DateTimeTz')+ const expected = structuredClone(definition)+ const updatedEntity = kind === 'field' ? expected.datasets[0].fields[0] : expected.metrics[0]+ updatedEntity.datatype = 'DateTimeTz'++ // Keep the editor open after a failed request so the same draft can also be cleared.+ defHttp.put.mockRejectedValueOnce(new Error('Save rejected'))+ await click(findText('.ant-modal button', 'Save'))+ expect(defHttp.put.mock.lastCall[0].data).toEqual({+ updates: [{ '@type': 'replaceDefinition', definition: expected }]+ })+ await act(async () => Simulate.mouseDown(selector.querySelector('.ant-select-clear')))+ updatedEntity.datatype = null+ const model = { name: navigation.name, definition: expected, properties: {} }+ defHttp.put.mockResolvedValue({ semanticModel: model })+ defHttp.get+ .mockResolvedValue({ semanticModel: model, identifiers: [] })+ .mockResolvedValueOnce({ semanticModel: { ...model, definition } })+ await click(findText('.ant-modal button', 'Save'))+ expect(defHttp.put.mock.lastCall[0].data).toEqual({+ updates: [{ '@type': 'replaceDefinition', definition: expected }]+ })+ expect(document.querySelector('.ant-modal')).toBeNull()+ })++ it('preserves text and structured drafts through repeated format switches before saving', async () => {+ const definition = definitionWith(() => 'Original guidance')+ await renderDetails(definition)+ await selectTab('Overview')+ await click(findText('button', 'Edit Model AI Context'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_contextText'), {+ target: { value: 'Text draft before conversion' }+ })+ )+ await selectOption('#semanticMetadata_contextFormat', 'Structured')+ expect(document.querySelector('#semanticMetadata_instructions').value).toBe('Text draft before conversion')+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_instructions'), {+ target: { value: 'Edited structured instructions' }+ })+ )+ await click(findText('.ant-modal button', 'Add example'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_examples_0'), {+ target: { value: 'Keep my example' }+ })+ )+ for (let i = 0; i < 2; i++) {+ await selectOption('#semanticMetadata_contextFormat', 'Text')+ expect(document.querySelector('#semanticMetadata_contextText').value).toBe('Text draft before conversion')+ await selectOption('#semanticMetadata_contextFormat', 'Structured')+ expect(document.querySelector('#semanticMetadata_instructions').value).toBe('Edited structured instructions')+ expect(document.querySelector('#semanticMetadata_examples_0').value).toBe('Keep my example')+ }++ const expected = {+ ...definition,+ aiContext: { instructions: 'Edited structured instructions', examples: ['Keep my example'] }+ }+ const model = { name: navigation.name, definition: expected, properties: {} }+ defHttp.put.mockResolvedValue({ semanticModel: model })+ defHttp.get+ .mockResolvedValue({ semanticModel: model, identifiers: [] })+ .mockResolvedValueOnce({ semanticModel: { ...model, definition } })+ await click(findText('.ant-modal button', 'Save'))+ expect(defHttp.put.mock.lastCall[0].data).toEqual({+ updates: [{ '@type': 'replaceDefinition', definition: expected }]+ })+ expect(document.querySelector('.ant-modal')).toBeNull()+ })++ it.each(['model', 'dataset', 'field', 'relationship', 'metric'])(+ 'edits only the selected %s metadata and preserves unknown keys',+ async kind => {+ navigation.name = 'orders'+ const definition = definitionWith(scope => ({ instructions: `${scope} guidance`, extra: { preserve: scope } }))+ const extension = [{ vendorName: 'vendor', data: '{"keep":true}' }]+ definition.customExtensions = extension+ definition.datasets[0].fields[0].customExtensions = extension+ let model = { name: 'orders', definition, properties: {} }+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve(url.endsWith('/semantic-models') ? { identifiers: [] } : { semanticModel: model })+ )+ defHttp.put.mockImplementation(({ data }) => {+ model = { ...model, definition: data.updates[0].definition }++ return Promise.resolve({ semanticModel: model })+ })+ await renderDetails(definition, model)+ if (kind === 'model') {+ await selectTab('Overview')+ await click(findText('button', 'Edit Model AI Context'))+ }+ if (kind === 'dataset') await click(document.querySelector('[aria-label="Edit dataset orders"]'))+ if (kind === 'field') {+ await click(+ document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon')+ )+ await click(document.querySelector('[aria-label="Edit field amount"]'))+ }+ if (kind === 'relationship') {+ await selectTab('Relationships')+ await click(document.querySelector('[aria-label="Edit relationship customers"]'))+ }+ if (kind === 'metric') {+ await selectTab('Metrics')+ await click(document.querySelector('[aria-label="Edit metric revenue"]'))+ }+ const expected = structuredClone(definition)++ const entity = {+ model: expected,+ dataset: expected.datasets[0],+ field: expected.datasets[0].fields[0],+ relationship: expected.relationships[0],+ metric: expected.metrics[0]+ }[kind]+ entity.aiContext.instructions = 'Edited guidance'+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_instructions'), {+ target: { value: 'Edited guidance' }+ })+ )+ if (kind === 'field') {+ entity.label = 'Order Amount'+ entity.description = 'Field description'+ entity.expression.dialects[0].expression = '-- comment\namount * 2'+ await act(async () => {+ Simulate.change(document.querySelector('#semanticMetadata_label'), { target: { value: entity.label } })+ Simulate.change(document.querySelector('#semanticMetadata_description'), {+ target: { value: entity.description }+ })+ Simulate.change(document.querySelector('#semanticMetadata_dialects_0_expression'), {+ target: { value: entity.expression.dialects[0].expression }+ })+ })+ defHttp.put.mockRejectedValueOnce(new Error('Save rejected'))+ await click(findText('.ant-modal button', 'Save'))+ expect(document.querySelector('#semanticMetadata_label').value).toBe('Order Amount')+ expect(document.body.textContent).toContain('Your edits are retained')+ }+ await click(findText('.ant-modal button', 'Save'))+ expect(defHttp.put.mock.lastCall[0].data).toEqual({+ updates: [{ '@type': 'replaceDefinition', definition: expected }]+ })+ expect(store.getState().metalakes.activatedDetails.definition).toEqual(expected)+ expect(document.querySelector('.ant-modal')).toBeNull()+ }+ )++ it('blocks an empty dialect list and retains the editor for correction', async () => {+ await renderDetails(definitionWith(() => null))+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ await click(document.querySelector('[aria-label="Edit field amount"]'))+ await click(document.querySelector('[aria-label="Remove dialect 1"]'))+ await click(findText('.ant-modal button', 'Save'))+ expect(document.body.textContent).toContain('Add at least one dialect expression.')+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(document.querySelector('.ant-modal')).not.toBeNull()+ })++ it('closes an unchanged focused edit without sending a definition replacement', async () => {+ await renderDetails(definitionWith(() => null))+ await selectTab('Overview')+ await click(findText('button', 'Edit Model AI Context'))+ await click(findText('.ant-modal button', 'Save'))+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(document.querySelector('.ant-modal')).toBeNull()+ })++ it('keeps SQL line breaks in bounded code blocks', async () => {+ const definition = definitionWith(() => null)+ const sql = '-- comment\nSELECT ' + 'x'.repeat(200)+ definition.metrics[0].expression.dialects[0].expression = sql+ await renderDetails(definition)+ await selectTab('Metrics')+ const code = document.querySelector('[data-refer="semantic-model-metrics-grid"] pre')+ expect(code.textContent).toBe(sql)+ expect(code.className).toContain('whitespace-pre-wrap')+ expect(code.className).toContain('overflow-hidden')+ await click(document.querySelector('[aria-label="View expression for revenue"]'))+ const fullSql = document.querySelector('.ant-modal pre')+ expect(fullSql.textContent).toBe(sql)+ expect(fullSql.className).toContain('leading-6')+ expect(fullSql.className).toContain('overflow-auto')+ })++ it('does not show an AI Context action for a field without guidance', async () => {+ await renderDetails(definitionWith(() => null))+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ expect(document.querySelector('[aria-label="amount AI Context"]')).toBeNull()+ })++ it('keeps model metadata in Overview while browsing compact expression rows', async () => {+ const definition = definitionWith(() => 'guidance')+ definition.metrics[0].expression.dialects = ['ANSI_SQL', 'TRINO', 'SPARK_SQL', 'POSTGRESQL'].map(dialect => ({+ dialect,+ expression: `-- ${dialect}\nSUM(amount)`+ }))+ await renderDetails(definition)+ expect(document.body.textContent).not.toContain('Model AI Context')+ await selectTab('Metrics')+ const grid = document.querySelector('[data-refer="semantic-model-metrics-grid"]')+ expect(grid.querySelectorAll('pre')).toHaveLength(1)+ expect(grid.textContent).toContain('4 dialects')+ await click(document.querySelector('[aria-label="View expression for revenue"]'))+ expect(document.querySelector('.ant-modal pre').textContent).toBe('-- ANSI_SQL\nSUM(amount)')+ await selectOption('[aria-label="SQL dialect"]', 'TRINO')+ expect(document.querySelector('.ant-modal pre').textContent).toBe('-- TRINO\nSUM(amount)')+ await selectOption('[aria-label="SQL dialect"]', 'All dialects')+ expect(document.querySelectorAll('.ant-modal pre')).toHaveLength(4)+ await click(document.querySelector('.ant-modal-close'))+ await selectTab('Overview')+ expect(document.body.textContent).toContain('Model AI Context')+ })++ it('filters fields by label, expands matching datasets, and clears both detail filters', async () => {+ const definition = definitionWith(() => null)+ definition.datasets[0].fields[0].label = 'Revenue amount'+ definition.datasets.push({ name: 'other', fields: [{ name: 'cost' }] })+ definition.metrics.push({ name: 'profit' })+ await renderDetails(definition)+ await act(async () =>+ Simulate.change(document.querySelector('[aria-label="Search fields"]'), { target: { value: 'REVENUE' } })+ )+ const grid = document.querySelector('[data-refer="semantic-model-datasets-grid"]')+ expect(grid.textContent).toContain('Revenue amount')+ expect(grid.textContent).not.toContain('other')+ expect(grid.querySelectorAll('[data-refer="semantic-model-fields-grid"]')).toHaveLength(1)+ await click(findText('button', 'Clear field search'))+ expect(grid.textContent).toContain('other')+ await selectTab('Metrics')+ await act(async () =>+ Simulate.change(document.querySelector('[aria-label="Search metrics"]'), { target: { value: 'PROF' } })+ )+ const metrics = document.querySelector('[data-refer="semantic-model-metrics-grid"]')+ expect(metrics.textContent).toContain('profit')+ expect(metrics.textContent).not.toContain('revenue')+ await click(findText('button', 'Clear metric search'))+ expect(metrics.textContent).toContain('revenue')+ })++ it('uses the existing type palette in fields and metrics with a neutral fallback', async () => {+ const definition = definitionWith(() => null)+ definition.datasets[0].fields[0].datatype = 'String'+ definition.metrics[0].datatype = 'Decimal'+ definition.metrics.push({ name: 'unknown', datatype: 'FutureType' })+ await renderDetails(definition)+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ expect(findText('.ant-tag', 'String').className).toContain('ant-tag-orange')+ await selectTab('Metrics')+ expect(findText('.ant-tag', 'Decimal').className).toContain('ant-tag-blue')+ expect(findText('.ant-tag', 'FutureType').className).not.toMatch(/ant-tag-(blue|orange)/)+ })++ it('formats structured extension data and still exposes the exact raw value', async () => {+ const definition = definitionWith(() => null)+ const raw = '{ "nested": {"flag":true}, "values":[1,2] }'+ definition.customExtensions = [+ { vendorName: 'json', data: raw },+ { vendorName: 'text', data: 'arbitrary text' }+ ]+ await renderDetails(definition)+ await selectTab('Overview')+ await expandContext('Model Vendor Extensions')+ const json = document.querySelector('section[aria-label="json"]')+ expect(json.querySelector('pre').textContent).toBe(JSON.stringify(JSON.parse(raw), null, 2))+ await click(findText('button', 'Show raw value'))+ expect(json.querySelector('pre').textContent).toBe(raw)+ expect(document.querySelector('section[aria-label="text"] pre').textContent).toBe('arbitrary text')+ expect(definition.customExtensions[0].data).toBe(raw)+ })++ it('opens field guidance editing directly and retains drafts across all editor tabs', async () => {+ const definition = definitionWith(() => ({ instructions: 'Original' }))+ await renderDetails(definition)+ await click(document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon'))+ await click(document.querySelector('[aria-label="amount AI Context"]'))+ await click(findText('.ant-modal button', 'Edit AI Context'))+ expect(findText('.ant-modal [role="tab"]', 'AI Context').getAttribute('aria-selected')).toBe('true')+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_instructions'), {+ target: { value: 'Keep guidance draft' }+ })+ )+ await click(findText('.ant-modal [role="tab"]', 'Expressions'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_dialects_0_expression'), {+ target: { value: '-- draft\namount * 2' }+ })+ )+ await click(findText('.ant-modal [role="tab"]', 'Basic information'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_description'), {+ target: { value: 'Keep description draft' }+ })+ )+ await click(findText('.ant-modal button', 'Cancel'))+ expect(document.body.textContent).toContain('Discard unsaved changes?')+ await click(findText('.ant-modal button', 'Keep editing'))+ expect(document.querySelector('#semanticMetadata_description').value).toBe('Keep description draft')+ await click(findText('.ant-modal [role="tab"]', 'Expressions'))+ expect(document.querySelector('#semanticMetadata_dialects_0_expression').value).toBe('-- draft\namount * 2')+ await click(findText('.ant-modal [role="tab"]', 'AI Context'))+ expect(document.querySelector('#semanticMetadata_instructions').value).toBe('Keep guidance draft')+ await click(findText('.ant-modal button', 'Cancel'))+ await click(findText('.ant-modal button', 'Discard changes'))+ expect(document.querySelector('.ant-modal')).toBeNull()+ expect(defHttp.put).not.toHaveBeenCalled()+ })++ it('closes an unchanged editor immediately on Cancel', async () => {+ await renderDetails(definitionWith(() => null))+ await click(document.querySelector('[aria-label="Edit dataset orders"]'))+ await click(findText('.ant-modal button', 'Cancel'))+ expect(document.querySelector('.ant-modal')).toBeNull()+ expect(document.body.textContent).not.toContain('Discard unsaved changes?')+ })++ it('reveals and focuses invalid SQL even when saving from another section', async () => {+ await renderDetails(definitionWith(() => null))+ await selectTab('Metrics')+ await click(document.querySelector('[aria-label="Edit metric revenue"]'))+ await click(findText('.ant-modal [role="tab"]', 'Expressions'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_dialects_0_expression'), { target: { value: '' } })+ )+ await click(findText('.ant-modal [role="tab"]', 'Basic information'))+ await click(findText('.ant-modal button', 'Save'))+ expect(findText('.ant-modal [role="tab"]', 'Expressions').getAttribute('aria-selected')).toBe('true')+ await act(async () => new Promise(resolve => requestAnimationFrame(resolve)))+ expect(document.activeElement.id).toBe('semanticMetadata_dialects_0_expression')+ expect(document.querySelector('.ant-form-item-explain-error').textContent).toContain('required')+ expect(defHttp.put).not.toHaveBeenCalled()+ })++ it('keeps the server permission reason beside the unsaved draft', async () => {+ await renderDetails(definitionWith(() => null))+ await click(document.querySelector('[aria-label="Edit dataset orders"]'))+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_description'), { target: { value: 'My draft' } })+ )+ defHttp.put.mockRejectedValue({+ response: { data: { message: 'Permission denied: MODIFY_SEMANTIC_MODEL is required' } }+ })+ await click(findText('.ant-modal button', 'Save'))+ expect(document.querySelector('.ant-modal .ant-alert').textContent).toContain(+ 'Permission denied: MODIFY_SEMANTIC_MODEL is required'+ )+ expect(document.querySelector('#semanticMetadata_description').value).toBe('My draft')+ expect(document.querySelector('.ant-modal')).not.toBeNull()+ })+ it('protects an edited structured draft even after switching back to unchanged text', async () => {+ await renderDetails(definitionWith(() => 'Original text'))+ await selectTab('Overview')+ await click(findText('button', 'Edit Model AI Context'))+ await selectOption('#semanticMetadata_contextFormat', 'Structured')+ await act(async () =>+ Simulate.change(document.querySelector('#semanticMetadata_instructions'), { target: { value: 'Hidden draft' } })+ )+ await selectOption('#semanticMetadata_contextFormat', 'Text')+ expect(document.querySelector('#semanticMetadata_contextText').value).toBe('Original text')+ await click(findText('.ant-modal button', 'Cancel'))+ expect(document.body.textContent).toContain('Discard unsaved changes?')+ await click(findText('.ant-modal button', 'Keep editing'))+ await selectOption('#semanticMetadata_contextFormat', 'Structured')+ expect(document.querySelector('#semanticMetadata_instructions').value).toBe('Hidden draft')+ })+})++it('preserves precise vendor numbers in both formatted and raw views', async () => {+ const raw = '{"external_id":9007199254740993,"threshold":0.10000000000000000001}'+ await renderDetails({ datasets: [], customExtensions: [{ vendorName: 'precise', data: raw }] })+ await selectTab('Overview')+ await expandContext('Model Vendor Extensions')+ const pre = document.querySelector('section[aria-label="precise"] pre')+ expect(pre.textContent).toContain('9007199254740993')+ expect(pre.textContent).toContain('0.10000000000000000001')+ await click(findText('button', 'Show raw value'))+ expect(pre.textContent).toBe(raw)+})++it.each(['field', 'metric'])(+ 'keeps the %s preview dialect local to the row and shares it with View SQL',+ async kind => {+ const definition = definitionWith(() => null)+ const entities = kind === 'field' ? definition.datasets[0].fields : definition.metrics+ entities[0].expression.dialects = [+ { dialect: 'TRINO', expression: 'trino_sql' },+ { dialect: 'ANSI_SQL', expression: 'ansi_sql' }+ ]+ entities.push({ name: 'second', expression: structuredClone(entities[0].expression) })+ const original = structuredClone(definition)+ await renderDetails(definition)+ if (kind === 'field')+ await click(+ document.querySelector('[data-refer="semantic-model-datasets-grid"] button.ant-table-row-expand-icon')+ )+ else await selectTab('Metrics')+ const name = entities[0].name++ const select = async (selector, label) => {+ await act(async () =>+ Simulate.mouseDown(+ document.querySelector(selector).closest('.ant-select').querySelector('.ant-select-selector')+ )+ )+ await click(+ [+ ...document.querySelectorAll(+ '.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option-content'+ )+ ].find(element => element.textContent === label)+ )+ }+ await select(`[aria-label="Preview dialect for ${name}"]`, 'ANSI_SQL')+ const grid = document.querySelector(`[data-refer="semantic-model-${kind === 'field' ? 'fields' : 'metrics'}-grid"]`)+ expect([...grid.querySelectorAll('pre')].map(pre => pre.textContent)).toEqual(['ansi_sql', 'trino_sql'])+ await click(document.querySelector(`[aria-label="View expression for ${name}"]`))+ expect(document.querySelector('.ant-modal pre').textContent).toBe('ansi_sql')+ await select('[aria-label="SQL dialect"]', 'TRINO')+ await click(document.querySelector('.ant-modal-close'))+ expect(grid.querySelector('pre').textContent).toBe('trino_sql')+ expect(definition).toEqual(original)+ }+)++it('expands the complete definition and returns to the same tab', async () => {+ await renderDetails(definitionWith(() => null))+ await selectTab('Definition')+ const definitionText = document.querySelector('[data-refer="semantic-model-definition"]').textContent+ await click(findText('button', 'Expand definition'))+ expect(document.querySelector('.ant-modal pre').textContent).toBe(definitionText)+ expect(findText('.ant-modal button', 'Copy definition')).toBeTruthy()+ await click(document.querySelector('.ant-modal-close'))+ expect(findText('[role="tab"]', 'Definition').getAttribute('aria-selected')).toBe('true')+})++it.each([false, true])(+ 'does not refresh or navigate for a save completed after leaving the model (rename=%s)',+ async rename => {+ navigation.name = 'orders'+ const definition = definitionWith(() => null)+ let finish+ defHttp.put.mockImplementation(+ () =>+ new Promise(resolve => {+ finish = resolve+ })+ )+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve(+ url.endsWith('/semantic-models')+ ? { identifiers: [] }+ : { semanticModel: { name: navigation.name, definition, properties: {} } }+ )+ )+ await renderDetails(definition)+ await click(document.querySelector('[aria-label="Edit Semantic Model"]'))+ await act(async () =>+ Simulate.change(document.querySelector('[data-refer="semantic-model-comment-field"]'), {+ target: { value: 'Updated' }+ })+ )+ await click(document.querySelector('[data-refer="handle-submit-semantic-model"]'))+ expect(finish).toBeTypeOf('function')+ await act(async () => root.render(null))+ defHttp.get.mockClear()+ await act(async () =>+ finish({ semanticModel: { name: rename ? 'renamed' : navigation.name, definition, properties: {} } })+ )+ expect(navigation.replace).not.toHaveBeenCalled()+ expect(defHttp.get.mock.calls.every(([request]) => request.url.endsWith('/semantic-models'))).toBe(true)+ }+)++it.each(['table', 'other schema'])('never displays same-named %s metadata as the routed model', async source => {+ await renderDetails(definitionWith(() => null))+ const thunk = source === 'table' ? getTableDetails : getSemanticModelDetails++ const args = {+ init: true,+ metalake: 'demo',+ catalog: 'sales',+ schema: source === 'table' ? 'mart' : 'other',+ ...(source === 'table' ? { table: navigation.name } : { semanticModel: navigation.name })+ }+ await act(async () => {+ store.dispatch(thunk.pending('other', args))+ store.dispatch(+ thunk.fulfilled(+ {+ init: true,+ [source === 'table' ? 'table' : 'semanticModel']: {+ name: navigation.name,+ comment: 'Unrelated comment',+ columns: [],+ definition: definitionWith(() => 'unrelated')+ }+ },+ 'other',+ args+ )+ )+ })+ expect(document.body.textContent).not.toContain('Unrelated comment')+ expect(document.querySelector('[aria-label="Edit dataset orders"]')).toBeNull()+})++it.each(['field', 'dataset'])('closes the %s snapshot modal when the definition is cleared', async kind => {+ await renderDetails(definitionWith(() => 'guidance'))+ await click(document.querySelector('button.ant-table-row-expand-icon'))+ if (kind === 'dataset') await click(findText('button', 'View dataset details'))+ else {+ await click(document.querySelector('[aria-label="amount AI Context"]'))+ }+ expect(document.querySelector('.ant-modal')).not.toBeNull()+ await act(async () => store.dispatch(resetActivatedDetails()))+ expect(document.querySelector('.ant-modal')).toBeNull()+ expect(defHttp.put).not.toHaveBeenCalled()+})++it.each([+ [undefined, { kind: 'model' }],+ [undefined, { kind: 'field', datasetName: 'orders', name: 'amount' }],+ [{ datasets: [] }, { kind: 'dataset', name: 'orders' }],+ [{ datasets: [{ name: 'orders', fields: [] }] }, { kind: 'field', datasetName: 'orders', name: 'amount' }]+])('renders a closable error when the editor mounts with unavailable metadata', async (definition, target) => {+ const close = vi.fn()+ await act(async () =>+ root.render(+ <Provider store={store}>+ <SemanticMetadataEditor definition={definition} target={target} onClose={close} />+ </Provider>+ )+ )+ expect(document.body.textContent).toContain('The selected metadata no longer exists')+ expect(findText('.ant-modal button', 'Save')).toBeUndefined()+ await click(findText('.ant-modal button', 'Close'))+ expect(close).toHaveBeenCalledOnce()+ expect(defHttp.put).not.toHaveBeenCalled()+})++it.each(['rename', 'remove'])('clears duplicate dialect errors immediately after %s', async correction => {+ const definition = definitionWith(() => null)+ definition.datasets[0].fields[0].expression.dialects = [+ { dialect: 'ANSI_SQL', expression: 'amount' },+ { dialect: 'TRINO', expression: 'amount' }+ ]+ await renderDetails(definition)+ await click(document.querySelector('button.ant-table-row-expand-icon'))+ await click(document.querySelector('[aria-label="Edit field amount"]'))++ const changeDialect = async value =>+ act(async () => {+ Simulate.change(document.querySelector('#semanticMetadata_dialects_1_dialect'), { target: { value } })+ await new Promise(resolve => setTimeout(resolve, 300))+ })+ await changeDialect('ANSI_SQL')+ await click(findText('.ant-modal button', 'Save'))+ expect(document.body.textContent).toContain('Dialect names must be unique')+ if (correction === 'rename') await changeDialect('TRINO')+ else await click(document.querySelector('[aria-label="Remove dialect 2"]'))+ await act(async () => new Promise(resolve => setTimeout(resolve, 400)))+ expect(document.body.textContent).not.toContain('Dialect names must be unique')+ expect(defHttp.put).not.toHaveBeenCalled()+})++it.each(['focused', 'JSON'])(+ 'retains the %s draft without overwriting a concurrently edited definition',+ async editor => {+ navigation.name = 'orders'+ const definition = definitionWith(() => null)+ let serverModel = { name: navigation.name, definition, properties: {} }+ defHttp.get.mockImplementation(() => Promise.resolve({ semanticModel: serverModel }))+ await renderDetails(definition)+ let input+ if (editor === 'focused') {+ await click(document.querySelector('[aria-label="Edit dataset orders"]'))+ input = document.querySelector('#semanticMetadata_description')+ await act(async () => Simulate.change(input, { target: { value: 'My draft' } }))+ } else {+ await click(document.querySelector('[aria-label="Edit Semantic Model"]'))+ input = document.querySelector('[data-refer="semantic-model-definition-field"]')+ await act(async () =>+ Simulate.change(input, { target: { value: JSON.stringify({ ...definition, aiContext: 'My draft' }) } })+ )+ }+ serverModel = { ...serverModel, definition: { ...definition, aiContext: 'Concurrent edit' } }+ await click(findText('.ant-modal button', editor === 'focused' ? 'Save' : 'Submit'))+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(document.querySelector('.ant-modal .ant-alert').textContent).toContain('changed since')+ expect(input.value).toContain('My draft')+ expect(store.getState().metalakes.activatedDetails.definition).toEqual(definition)+ }+)++it('edits the time dimension through the field form', async () => {+ let model = { name: navigation.name, definition: definitionWith(() => null), properties: {} }+ model.definition.datasets[0].fields[0].dimension = { isTime: true }+ defHttp.get.mockImplementation(() => Promise.resolve({ semanticModel: model, identifiers: [] }))+ defHttp.put.mockImplementation(({ data }) => {+ model = { ...model, definition: data.updates[0].definition }++ return Promise.resolve({ semanticModel: model })+ })+ await renderDetails(model.definition)+ await click(document.querySelector('button.ant-table-row-expand-icon'))+ await click(document.querySelector('[aria-label="Edit field amount"]'))+ const input = document.querySelector('#semanticMetadata_timeDimension')+ expect(input.closest('.ant-select').textContent).toContain('Yes')+ await act(async () => Simulate.mouseDown(input.closest('.ant-select').querySelector('.ant-select-selector')))+ await click(findText('.ant-select-item-option-content', 'No'))+ await click(findText('.ant-modal button', 'Save'))+ expect(model.definition.datasets[0].fields[0].dimension).toEqual({ isTime: false })+ expect(document.querySelector('.ant-modal')).toBeNull()+})++it.each([true, false])('shows inherited=%s policies without editing or navigation', async inherited => {+ await renderDetails(definitionWith(() => null))+ await selectTab('Overview')+ const policies = [{ name: 'retention', enabled: true, inherited }]+ defHttp.get.mockResolvedValue({ policies })+ await act(async () =>+ store.dispatch(+ getCurrentEntityPolicies({+ init: true,+ metalake: 'demo',+ metadataObjectType: 'semantic_model',+ metadataObjectFullName: `sales.mart.${navigation.name}`,+ details: true+ })+ )+ )+ const link = document.querySelector('[aria-label="View Semantic Model policies"]')+ expect(link.textContent).toBe('1')+ await act(async () => {+ Simulate.mouseEnter(link)+ await new Promise(resolve => setTimeout(resolve, 200))+ })+ expect(document.querySelector('.ant-popover').textContent).toContain('retention')+ expect(document.querySelector('.ant-popover .ant-tag-close-icon')).toBeNull()+ expect(document.querySelector('.ant-popover').textContent).not.toContain('Associate Policy')+ expect(defHttp.get.mock.lastCall[0].url).toContain('/semantic_model/')+ const requestsBeforeClick = defHttp.get.mock.calls.length+ await click(findText('.ant-popover span', 'retention'))+ expect(navigation.push).not.toHaveBeenCalled()+ expect(navigation.replace).not.toHaveBeenCalled()+ expect(defHttp.get).toHaveBeenCalledTimes(requestsBeforeClick)+ expect(link.textContent).toBe('1')+ expect(document.querySelector('.ant-popover').textContent).toContain('retention')+})diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExport.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExport.jsnew file mode 100644index 0000000000..15297fe2c3--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExport.js@@ -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.+ */++import { useState } from 'react'+import { Alert, Button, Dropdown, Space } from 'antd'+import { DownloadOutlined } from '@ant-design/icons'+import { exportSemanticModelApi } from '@/lib/api/semanticModels'+import { semanticModelErrorMessage } from '@/lib/utils/semanticModel'++export default function SemanticModelExport({ metalake, catalog, schema, semanticModel, disabled }) {+ const [loading, setLoading] = useState(false)+ const [error, setError] = useState('')++ const exportDocument = async ({ key: format }) => {+ setLoading(true)+ setError('')+ try {+ const content = await exportSemanticModelApi({ metalake, catalog, schema, semanticModel, format })+ if (typeof content !== 'string' || !content.trim()) throw new Error('Export returned an empty document.')+ const blob = new Blob([content], { type: format === 'json' ? 'application/json' : 'application/yaml' })+ const url = URL.createObjectURL(blob)+ const link = document.createElement('a')+ link.href = url+ link.download = `${semanticModel.replace(/[^A-Za-z0-9._-]/g, '_')}.ossie.${format}`+ document.body.appendChild(link)+ link.click()+ link.remove()+ setTimeout(() => URL.revokeObjectURL(url), 0)+ } catch (err) {+ setError(semanticModelErrorMessage(err, 'Failed to export the OSSIE document.'))+ } finally {+ setLoading(false)+ }+ }++ return (+ <Space direction='vertical' align='end' className='mb-3 flex'>+ <Dropdown+ trigger={['click']}+ disabled={disabled || loading}+ menu={{+ items: [+ { key: 'yaml', label: 'Download YAML' },+ { key: 'json', label: 'Download JSON' }+ ],+ onClick: exportDocument+ }}+ >+ <Button aria-label='Export OSSIE' icon={<DownloadOutlined />} loading={loading} disabled={disabled}>+ Export OSSIE+ </Button>+ </Dropdown>+ {error && <Alert type='error' showIcon message='Export failed' description={error} />}+ </Space>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExpression.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExpression.jsnew file mode 100644index 0000000000..98c74daefb--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExpression.js@@ -0,0 +1,95 @@+/*+ * 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 { useState } from 'react'+import { Button, Modal, Select, Tag, theme } from 'antd'++export default function SemanticModelExpression({ expression, name }) {+ const { token } = theme.useToken()+ const [open, setOpen] = useState(false)+ const [selected, setSelected] = useState(0)+ const [all, setAll] = useState(false)+ const dialects = expression?.dialects || []+ if (!dialects.length) return <span>-</span>+ const current = dialects[selected] ? selected : 0+ const visible = all ? dialects : [dialects[current]]++ return (+ <div className='min-w-0'>+ {dialects.length > 1 ? (+ <Select+ aria-label={`Preview dialect for ${name}`}+ size='small'+ className='mb-1 min-w-28'+ value={current}+ onChange={setSelected}+ options={dialects.map((dialect, index) => ({ value: index, label: dialect.dialect }))}+ />+ ) : (+ <Tag>{dialects[0].dialect}</Tag>+ )}+ <pre className='m-0 max-h-8 overflow-hidden whitespace-pre-wrap break-words font-mono text-xs [overflow-wrap:anywhere]'>+ {dialects[current].expression}+ </pre>+ <Button+ size='small'+ type='link'+ aria-label={`View expression for ${name}`}+ onClick={() => {+ setAll(false)+ setOpen(true)+ }}+ >+ View SQL ({dialects.length} {dialects.length === 1 ? 'dialect' : 'dialects'})+ </Button>+ <Modal open={open} title={`${name} SQL expressions`} width={900} footer={null} onCancel={() => setOpen(false)}>+ <Select+ aria-label='SQL dialect'+ className='mb-3 w-full'+ value={all ? 'all' : current}+ onChange={value => {+ setAll(value === 'all')+ if (value !== 'all') setSelected(value)+ }}+ options={[+ ...dialects.map((dialect, index) => ({ value: index, label: dialect.dialect })),+ { value: 'all', label: 'All dialects' }+ ]}+ />+ <div className='space-y-3 overflow-auto' style={{ maxHeight: '60vh' }}>+ {visible.map((dialect, index) => (+ <div key={index}>+ <Tag className='mb-2'>{dialect.dialect}</Tag>+ <pre+ style={{+ background: token.colorFillQuaternary,+ borderColor: token.colorBorderSecondary,+ borderStyle: 'solid'+ }}+ className='m-0 overflow-auto whitespace-pre-wrap break-words rounded border border-borderColor p-3 font-mono text-sm leading-6 [overflow-wrap:anywhere]'+ >+ {dialect.expression}+ </pre>+ </div>+ ))}+ </div>+ </Modal>+ </div>+ )+}diff --git a/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExtensions.js b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExtensions.jsnew file mode 100644index 0000000000..0587b7a990--- /dev/null+++ b/web-v2/web/src/app/catalogs/rightContent/entitiesContent/SemanticModelExtensions.js@@ -0,0 +1,60 @@+/*+ * 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 { useState } from 'react'+import { Button, Typography } from 'antd'+import { formatVendorJson } from '@/lib/utils/formatVendorJson'+import SemanticMetadataSection from './SemanticMetadataSection'++function ExtensionData({ data }) {+ const [raw, setRaw] = useState(false)+ const formatted = formatVendorJson(data)++ return (+ <>+ {formatted && (+ <Button size='small' className='mb-2' onClick={() => setRaw(!raw)}>+ {raw ? 'Show formatted JSON' : 'Show raw value'}+ </Button>+ )}+ <pre className='m-0 max-h-64 overflow-auto whitespace-pre-wrap break-words font-mono text-xs'>+ {formatted && !raw ? formatted : data}+ </pre>+ </>+ )+}++export default function SemanticModelExtensions({ extensions, label }) {+ if (!extensions?.length) return null++ return (+ <SemanticMetadataSection label={label}>+ <div className='space-y-3'>+ {extensions.map((extension, index) => (+ <section key={index} aria-label={extension.vendorName}>+ <Typography.Text type='secondary' className='mb-2 block text-xs font-medium'>+ {extension.vendorName}+ </Typography.Text>+ <ExtensionData data={extension.data} />+ </section>+ ))}+ </div>+ </SemanticMetadataSection>+ )+}diff --git a/web-v2/web/src/app/catalogs/semanticModelNavigation.test.jsx b/web-v2/web/src/app/catalogs/semanticModelNavigation.test.jsxnew file mode 100644index 0000000000..bbf9302317--- /dev/null+++ b/web-v2/web/src/app/catalogs/semanticModelNavigation.test.jsx@@ -0,0 +1,232 @@+/*+ * 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 { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer from '@/lib/store/metalakes'+import CatalogsListPage from './page'+import { catalogEntityKey } from '@/lib/utils/catalogEntity'++const navigation = vi.hoisted(() => ({ params: null }))+vi.mock('next/navigation', () => ({ useSearchParams: () => navigation.params }))+vi.mock('./rightContent/RightContent', () => ({ default: () => null }))+vi.mock('./TreeComponent', async () => ({ TreeComponent: (await import('react')).forwardRef(() => null) }))+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++let store+let root+let container+let responses+beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+ store = configureStore({+ reducer: { metalakes: reducer },+ preloadedState: {+ metalakes: {+ ...reducer(undefined, { type: 'init' }),+ catalogs: [{ name: 'sales', provider: 'jdbc-mysql' }],+ semanticModels: [{ name: 'first' }, { name: 'second' }]+ }+ }+ })+ responses = new Map()+ defHttp.get.mockImplementation(({ url }) => {+ if (/semantic-models\/(first|second)$/.test(url))+ return new Promise(resolve => responses.set(url.split('/').at(-1), resolve))++ return Promise.resolve({ tags: [], policies: [], identifiers: [], schema: { name: 'mart' } })+ })+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})+afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.unstubAllGlobals()+})++const navigate = async model => {+ navigation.params = new URLSearchParams({+ metalake: 'demo',+ catalog: 'sales',+ catalogType: 'relational',+ schema: 'mart',+ ...(typeof model === 'object' ? model : model ? { semanticModel: model } : {})+ })+ await act(async () =>+ root.render(+ <Provider store={store}>+ <CatalogsListPage />+ </Provider>+ )+ )+}++it.each(['second', null])('ignores old detail follow-ups while navigating to %s', async destination => {+ await navigate('first')+ expect(responses.has('first')).toBe(true)+ await navigate(destination)+ const before = store.getState().metalakes+ const callsBefore = defHttp.get.mock.calls.length+ await act(async () => responses.get('first')({ semanticModel: { name: 'first', definition: { datasets: [] } } }))+ expect(store.getState().metalakes.activatedDetails).toEqual(before.activatedDetails)+ expect(store.getState().metalakes.activatedDetailsLoading).toBe(before.activatedDetailsLoading)+ expect(defHttp.get.mock.calls.length).toBe(callsBefore)+ if (destination) {+ expect(store.getState().metalakes.activatedDetailsLoading).toBe(true)+ await act(async () => responses.get('second')({ semanticModel: { name: 'second', definition: { datasets: [] } } }))+ expect(store.getState().metalakes.activatedDetails.name).toBe('second')+ expect(store.getState().metalakes.activatedDetailsLoading).toBe(false)+ }+})++it.each(['table', 'schema'])('cancels %s details and all follow-ups when opening a model', async kind => {+ let resolveOld+ defHttp.get.mockImplementation(({ url }) => {+ if (url.endsWith(kind === 'table' ? '/tables/orders' : '/schemas/mart'))+ return new Promise(resolve => {+ resolveOld = resolve+ })++ return Promise.resolve({+ identifiers: [],+ tags: [],+ policies: [],+ semanticModel: { name: 'orders', definition: { datasets: [] } }+ })+ })+ await navigate(kind === 'table' ? { table: 'orders' } : null)+ expect(resolveOld).toBeTypeOf('function')+ await navigate('orders')+ const before = store.getState().metalakes+ const calls = defHttp.get.mock.calls.length+ await act(async () =>+ resolveOld({ table: { name: 'orders', columns: [], distribution: { funcArgs: [] } }, schema: { name: 'mart' } })+ )+ expect(store.getState().metalakes).toEqual(before)+ expect(defHttp.get.mock.calls).toHaveLength(calls)+})++it('ignores a canceled table list and its loading writes after opening a model', async () => {+ let resolveTables+ defHttp.get.mockImplementation(({ url }) => {+ if (url.endsWith('/tables'))+ return new Promise(resolve => {+ resolveTables = resolve+ })++ return Promise.resolve({+ identifiers: [],+ tags: [],+ policies: [],+ schema: { name: 'mart' },+ semanticModel: { name: 'orders', definition: { datasets: [] } }+ })+ })+ await navigate(null)+ expect(resolveTables).toBeTypeOf('function')+ await navigate('orders')+ const before = store.getState().metalakes+ await act(async () => resolveTables({ identifiers: [{ name: 'old_table' }] }))+ expect(store.getState().metalakes).toEqual(before)+})++it.each(['direct link', 'from model'])(+ 'loads the parent model header and versions on a version route: %s',+ async entry => {+ const model = { name: 'forecast', comment: 'Model header', properties: { framework: 'pytorch' } }+ defHttp.get.mockResolvedValue({+ model,+ identifiers: [],+ versions: [1, 2],+ tags: [{ name: 'model_tag' }],+ policies: []+ })+ const route = { catalogType: 'model', model: 'forecast' }+ if (entry === 'from model') await navigate(route)+ await navigate({ ...route, version: '1' })+ const state = store.getState().metalakes+ expect(state.activatedDetails).toEqual(model)+ expect(state.activatedDetailsKey).toBe(+ catalogEntityKey({ metalake: 'demo', catalog: 'sales', schema: 'mart', ...route, version: '1' })+ )+ expect(state.activatedDetailsLoading).toBe(false)+ expect(state.tableData.map(item => item.name)).toEqual([1, 2])+ expect(state.currentEntityTags).toEqual([{ name: 'model_tag' }])+ expect(defHttp.get.mock.calls.some(([request]) => request.url.endsWith('/versions/1'))).toBe(false)+ }+)++it('ignores a version route header response after navigating to a Semantic Model', async () => {+ let finishModel+ defHttp.get.mockImplementation(({ url }) => {+ if (url.endsWith('/models/forecast'))+ return new Promise(resolve => {+ finishModel = resolve+ })++ return Promise.resolve({+ identifiers: [],+ versions: [1],+ tags: [],+ policies: [],+ semanticModel: { name: 'orders', definition: { datasets: [] } }+ })+ })+ await navigate({ catalogType: 'model', model: 'forecast', version: '1' })+ expect(finishModel).toBeTypeOf('function')+ await navigate('orders')+ const before = store.getState().metalakes+ const calls = defHttp.get.mock.calls.length+ await act(async () => finishModel({ model: { name: 'forecast', comment: 'Old version route' } }))+ expect(store.getState().metalakes).toEqual(before)+ expect(defHttp.get.mock.calls).toHaveLength(calls)+})++it('loads policies for the active Semantic Model', async () => {+ const policies = [{ name: 'retention', enabled: true, inherited: true }]+ defHttp.get.mockResolvedValue({+ semanticModel: { name: 'orders', definition: { datasets: [] } },+ identifiers: [],+ tags: [],+ policies+ })+ await navigate('orders')+ expect(store.getState().metalakes.currentEntityPolicies).toEqual(policies)+ expect(+ defHttp.get.mock.calls.some(+ ([request]) => request.url.includes('/semantic_model/') && request.url.endsWith('/policies')+ )+ ).toBe(true)+})diff --git a/web-v2/web/src/components/PolicyTag.js b/web-v2/web/src/components/PolicyTag.jsindex b795f53596..8e59cb85cf 100644--- a/web-v2/web/src/components/PolicyTag.js+++ b/web-v2/web/src/components/PolicyTag.js@@ -154,7 +154,7 @@ export default function PolicyTag({ ...props }) {<Tagkey={policy.name + index}color={color}- closable={!policy.inherited}+ closable={!readOnly && !policy.inherited}icon={policy.inherited ? <LockOutlined /> : null}onClick={handleClick(policy.name)}className='cursor-pointer'diff --git a/web-v2/web/src/components/PolicyTag.test.jsx b/web-v2/web/src/components/PolicyTag.test.jsxnew file mode 100644index 0000000000..a5760a2197--- /dev/null+++ b/web-v2/web/src/components/PolicyTag.test.jsx@@ -0,0 +1,93 @@+/*+ * 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 { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { Provider } from 'react-redux'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import metalakes from '@/lib/store/metalakes'+import policies from '@/lib/store/policies'+import PolicyTag from './PolicyTag'++const navigation = vi.hoisted(() => ({ push: vi.fn() }))++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn() } }))+vi.mock('next/navigation', () => ({+ useRouter: () => navigation,+ useSearchParams: () => new URLSearchParams({ metalake: 'demo' })+}))++let root+let container++beforeEach(() => {+ vi.clearAllMocks()+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+})++afterEach(async () => {+ await act(async () => root.unmount())+ container.remove()+ vi.unstubAllGlobals()+})++it.each([true, false])('respects readOnly=%s while retaining policy navigation', async readOnly => {+ const directPolicy = { name: 'direct', enabled: true, inherited: false }+ const inheritedPolicy = { name: 'inherited', enabled: true, inherited: true }+ defHttp.get.mockResolvedValue({ policies: [directPolicy, inheritedPolicy] })+ const store = configureStore({ reducer: { metalakes, policies } })+ await act(async () =>+ root.render(+ <Provider store={store}>+ <PolicyTag readOnly={readOnly} metadataObjectType='table' metadataObjectFullName='sales.mart.orders' />+ </Provider>+ )+ )+ const [directTag, inheritedTag] = container.querySelectorAll('.ant-tag')+ expect(directTag.textContent).toBe('direct')+ expect(inheritedTag.textContent).toBe('inherited')+ expect(inheritedTag.querySelector('.ant-tag-close-icon')).toBeNull()+ expect(container.textContent.includes('Associate Policy')).toBe(!readOnly)++ const close = directTag.querySelector('.ant-tag-close-icon')+ if (readOnly) {+ expect(close).toBeNull()+ } else {+ expect(close).not.toBeNull()+ defHttp.post.mockResolvedValue({ code: 0 })+ defHttp.get.mockResolvedValue({ policies: [inheritedPolicy] })+ await act(async () => close.click())+ expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({+ url: '/api/metalakes/demo/objects/table/sales.mart.orders/policies',+ data: { policiesToRemove: ['direct'] }+ })+ expect(container.textContent).not.toContain('direct')+ expect(navigation.push).not.toHaveBeenCalled()+ }++ const policyLink = [...container.querySelectorAll('.ant-tag')].find(tag => tag.textContent === 'inherited')+ await act(async () => policyLink.click())+ expect(navigation.push).toHaveBeenCalledExactlyOnceWith('/metadataObjectsForPolicy?policy=inherited&metalake=demo')+ if (readOnly) expect(defHttp.post).not.toHaveBeenCalled()+})diff --git a/web-v2/web/src/lib/api/semanticModels/index.js b/web-v2/web/src/lib/api/semanticModels/index.jsnew file mode 100644index 0000000000..64d6dc7b6e--- /dev/null+++ b/web-v2/web/src/lib/api/semanticModels/index.js@@ -0,0 +1,94 @@+/*+ * 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 { defHttp } from '@/lib/utils/axios'++const Apis = {+ GET: ({ metalake, catalog, schema }) =>+ `/api/metalakes/${encodeURIComponent(metalake)}/catalogs/${encodeURIComponent(+ catalog+ )}/schemas/${encodeURIComponent(schema)}/semantic-models`,+ GET_DETAIL: ({ metalake, catalog, schema, semanticModel }) =>+ `/api/metalakes/${encodeURIComponent(metalake)}/catalogs/${encodeURIComponent(+ catalog+ )}/schemas/${encodeURIComponent(schema)}/semantic-models/${encodeURIComponent(semanticModel)}`+}++export const getSemanticModelsApi = (params, options) => {+ return defHttp.get(+ {+ url: `${Apis.GET(params)}`+ },++ // The schema tab and tree load this list independently and must not cancel each other.+ { ...options, ignoreCancelToken: true }+ )+}++export const getSemanticModelDetailsApi = ({ metalake, catalog, schema, semanticModel }, options) => {+ return defHttp.get(+ {+ url: `${Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })}`+ },+ options+ )+}++export const createSemanticModelApi = ({ metalake, catalog, schema, data }) => {+ return defHttp.post({+ url: `${Apis.GET({ metalake, catalog, schema })}`,+ data+ })+}++export const updateSemanticModelApi = ({ metalake, catalog, schema, semanticModel, data }) => {+ return defHttp.put({+ url: `${Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })}`,+ data+ })+}++export const deleteSemanticModelApi = ({ metalake, catalog, schema, semanticModel }) => {+ return defHttp.delete({+ url: `${Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })}`+ })+}++export const importSemanticModelApi = ({ metalake, catalog, schema, document, format }) => {+ return defHttp.post(+ {+ url: `${Apis.GET({ metalake, catalog, schema })}/ossie`,+ data: document,+ headers: { 'Content-Type': format === 'json' ? 'application/json' : 'application/yaml' },+ transformRequest: [data => data]+ },+ { errorMessageMode: 'none' }+ )+}++export const exportSemanticModelApi = ({ metalake, catalog, schema, semanticModel, format }) => {+ return defHttp.get(+ {+ url: `${Apis.GET_DETAIL({ metalake, catalog, schema, semanticModel })}/ossie`,+ params: { format },+ responseType: 'text'+ },+ { errorMessageMode: 'none' }+ )+}diff --git a/web-v2/web/src/lib/store/metalakes/catalogDetails.test.js b/web-v2/web/src/lib/store/metalakes/catalogDetails.test.jsnew file mode 100644index 0000000000..09b2b8bf62--- /dev/null+++ b/web-v2/web/src/lib/store/metalakes/catalogDetails.test.js@@ -0,0 +1,131 @@+/*+ * 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 { beforeEach, expect, it, vi } from 'vitest'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import { catalogEntityKey } from '@/lib/utils/catalogEntity'+import reducer, {+ getTableDetails,+ getFilesetDetails,+ getTopicDetails,+ getModelDetails,+ setActiveCatalogEntity,+ updateModel+} from './index'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), put: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))+const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+let store+beforeEach(() => {+ vi.resetAllMocks()+ store = configureStore({ reducer: { metalakes: reducer } })+})++it.each([undefined, '0'])('refreshes a saved parent model comment and properties for version %s', async version => {+ let model = { name: 'forecast', comment: 'Original', properties: { framework: 'pytorch' } }+ const args = { ...namespace, model: 'forecast', version, init: true }+ store.dispatch(setActiveCatalogEntity(args))+ defHttp.get.mockImplementation(() => Promise.resolve({ model }))+ await store.dispatch(getModelDetails(args))+ defHttp.put.mockImplementation(() => {+ model = { ...model, comment: 'Updated', properties: { framework: 'tensorflow' } }++ return Promise.resolve({ model })+ })+ await store.dispatch(+ updateModel({+ ...args,+ data: {+ updates: [+ { '@type': 'updateComment', newComment: 'Updated' },+ { '@type': 'setProperty', property: 'framework', value: 'tensorflow' }+ ]+ }+ })+ )+ expect(store.getState().metalakes.activatedDetails).toEqual(model)+ expect(store.getState().metalakes.activatedDetailsKey).toBe(catalogEntityKey(args))+})++it.each([+ { model: 'other', version: '0' },+ { model: 'forecast', schema: 'other', version: '0' }+])('does not overwrite another active model after a delayed version-route save: %j', async destination => {+ const args = { ...namespace, model: 'forecast', version: '0', init: true }+ store.dispatch(setActiveCatalogEntity(args))+ let finish+ defHttp.put.mockImplementation(+ () =>+ new Promise(resolve => {+ finish = resolve+ })+ )+ const save = store.dispatch(updateModel({ ...args, data: { updates: [] } }))+ const next = { ...args, ...destination }+ store.dispatch(setActiveCatalogEntity(next))+ const current = { name: next.model, comment: 'Current model', properties: { keep: 'yes' } }+ defHttp.get+ .mockResolvedValueOnce({ model: current })+ .mockResolvedValue({ model: { name: 'forecast', comment: 'Old save' } })+ await store.dispatch(getModelDetails(next))+ finish({ model: { name: 'forecast' } })+ await save+ expect(store.getState().metalakes.activatedDetails).toEqual(current)+ expect(store.getState().metalakes.activatedDetailsKey).toBe(catalogEntityKey(next))+})++it.each([+ [getTableDetails, 'table', 'relational'],+ [getFilesetDetails, 'fileset', 'fileset'],+ [getTopicDetails, 'topic', 'messaging']+])('populates active $typePrefix details and finishes loading', async (fetch, kind, catalogType) => {+ const args = { ...namespace, [kind]: 'orders', init: true }+ const details = { name: 'orders', comment: 'Active entity', properties: { retained: 'yes' } }+ if (kind === 'table')+ Object.assign(details, {+ columns: [{ name: 'id', type: 'long' }],+ partitioning: [{ strategy: 'identity', fieldName: ['id'] }],+ distribution: { strategy: 'hash', number: 4, funcArgs: [{ fieldName: ['id'] }] }+ })+ store.dispatch(setActiveCatalogEntity(args))+ let respond+ defHttp.get.mockImplementation(+ () =>+ new Promise(resolve => {+ respond = resolve+ })+ )+ const request = store.dispatch(fetch(args))+ expect(store.getState().metalakes.tableLoading).toBe(true)+ respond({ [kind]: details })+ await request+ const state = store.getState().metalakes+ expect(state.activatedDetails.comment).toBe('Active entity')+ expect(state.activatedDetails.properties).toEqual({ retained: 'yes' })+ expect(state.activatedDetailsKey).toBe(catalogEntityKey(args))+ expect(state.tableLoading).toBe(false)+ expect(state.expandedNodes).toContain(`{{demo}}{{sales}}{{${catalogType}}}{{mart}}`)+ if (kind === 'table') {+ expect(state.tableData).toEqual([{ name: 'id', type: 'long', node: 'tableColumn' }])+ expect(state.tableProps.find(prop => prop.type === 'partitioning').items[0].text).toBe('identity(id)')+ expect(state.tableProps.find(prop => prop.type === 'distribution').items[0].text).toBe('hash[4](id)')+ }+})diff --git a/web-v2/web/src/lib/store/metalakes/index.js b/web-v2/web/src/lib/store/metalakes/index.jsindex 49283333f9..2b5cddf02a 100644--- a/web-v2/web/src/lib/store/metalakes/index.js+++ b/web-v2/web/src/lib/store/metalakes/index.js@@ -17,11 +17,13 @@* under the License.*/+import { catalogEntityKey } from '@/lib/utils/catalogEntity'import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'import { to, extractPlaceholder, updateTreeData, findInTree } from '@/lib/utils'import { isUnsupportedOperationError } from '@/lib/utils/axios/unsupportedOperation'import toast from 'react-hot-toast'+import { semanticModelErrorMessage, semanticModelNodeKey } from '@/lib/utils/semanticModel'import _ from 'lodash-es'@@ -80,6 +82,13 @@ import {} from '@/lib/api/models'import { getFunctionsApi, getFunctionDetailsApi } from '@/lib/api/functions'import { getViewsApi, getViewDetailsApi, deleteViewApi } from '@/lib/api/views'+import {+ getSemanticModelsApi,+ getSemanticModelDetailsApi,+ createSemanticModelApi,+ updateSemanticModelApi,+ deleteSemanticModelApi+} from '@/lib/api/semanticModels'const remapExpandedAndLoadedNodes = ({ getState, mapNode }) => {const expandedNodes = getState().metalakes.expandedNodes.map(mapNode)@@ -96,8 +105,9 @@ const mergeWithFunctionNodes = ({ tree, key, entities }) => {const subSchemas = existingNode?.children?.filter(child => child?.node === 'schema') || []const functions = existingNode?.children?.filter(child => child?.node === 'function') || []const views = existingNode?.children?.filter(child => child?.node === 'view') || []+ const semanticModels = existingNode?.children?.filter(child => child?.node === 'semanticModel') || []- return _.uniqBy([...subSchemas, ...entities, ...functions, ...views], 'key')+ return _.uniqBy([...subSchemas, ...entities, ...functions, ...views, ...semanticModels], 'key')}const mergeWithViewNodes = ({ tree, key, entities }) => {@@ -105,10 +115,24 @@ const mergeWithViewNodes = ({ tree, key, entities }) => {const subSchemas = existingNode?.children?.filter(child => child?.node === 'schema') || []const tables = existingNode?.children?.filter(child => child?.node === 'table') || []const functions = existingNode?.children?.filter(child => child?.node === 'function') || []+ const semanticModels = existingNode?.children?.filter(child => child?.node === 'semanticModel') || []++ return _.uniqBy([...subSchemas, ...tables, ...functions, ...entities, ...semanticModels], 'key')+}++const mergeWithSemanticModelNodes = ({ tree, key, entities }) => {+ const existingNode = findInTree(tree, 'key', key)+ const subSchemas = existingNode?.children?.filter(child => child?.node === 'schema') || []+ const tables = existingNode?.children?.filter(child => child?.node === 'table') || []+ const functions = existingNode?.children?.filter(child => child?.node === 'function') || []+ const views = existingNode?.children?.filter(child => child?.node === 'view') || []- return _.uniqBy([...subSchemas, ...tables, ...functions, ...entities], 'key')+ return _.uniqBy([...subSchemas, ...tables, ...functions, ...views, ...entities], 'key')}+const semanticModelSchemaKey = ({ metalake, catalog, schema }) =>+ `{{${metalake}}}{{${catalog}}}{{relational}}{{${schema}}}`+const isAuthReady = state => {const { authType, authToken } = state.auth@@ -216,6 +240,7 @@ export const setIntoTreeNodeWithFetch = createAsyncThunk(async ({ key, reload }, { getState, dispatch }) => {let result = {key,+ semanticModelRequestId: getState().metalakes.semanticModelRequests[key]?.requestId,data: [],tree: getState().metalakes.metalakeTree}@@ -327,10 +352,16 @@ export const setIntoTreeNodeWithFetch = createAsyncThunk(? getViewsApi({ metalake, catalog, schema }, { errorMessageMode: 'none' }): Promise.resolve(null)- const [funcResult, entityResult, viewResult, childSchemasResult] = await Promise.allSettled([+ const semanticModelsPromise =+ type === 'relational'+ ? getSemanticModelsApi({ metalake, catalog, schema }, { errorMessageMode: 'none' })+ : Promise.resolve(null)++ const [funcResult, entityResult, viewResult, semanticModelResult, childSchemasResult] = await Promise.allSettled([getFunctionsApi({ metalake, catalog, schema, details: false }),entityPromise,viewsPromise,+ semanticModelsPromise,childSchemasPromise])@@ -390,6 +421,23 @@ export const setIntoTreeNodeWithFetch = createAsyncThunk(}): []+ const semanticModels =+ semanticModelResult.status === 'fulfilled' && semanticModelResult.value+ ? (semanticModelResult.value?.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: type, schema, semanticModel: semanticModelItem.name }).toString()}`,+ name: semanticModelItem.name,+ title: semanticModelItem.name,+ isLeaf: true,+ children: []+ }+ })+ : []+let entities = []if (entityResult.status === 'fulfilled' && entityResult.value) {switch (type) {@@ -464,7 +512,7 @@ export const setIntoTreeNodeWithFetch = createAsyncThunk(}}- result.data = [...childSchemas, ...entities, ...functions, ...views]+ result.data = [...childSchemas, ...entities, ...functions, ...views, ...semanticModels]result.entities = entities}@@ -540,13 +588,14 @@ export const getMetadataObjectsForPolicy = createAsyncThunk(export const fetchCatalogs = createAsyncThunk('appMetalakes/fetchCatalogs',- async ({ init, update, page, metalake }, { getState, dispatch }) => {+ async ({ init, update, page, metalake }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTree())await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getCatalogsApi({ metalake }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (err || !res) {@@ -880,12 +929,13 @@ export const switchInUseCatalog = createAsyncThunk(export const fetchSchemas = createAsyncThunk('appMetalakes/fetchSchemas',- async ({ init, page, metalake, catalog, catalogType, parentSchema }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, catalogType, parentSchema }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getSchemasApi({ metalake, catalog, parentSchema }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (err || !res) {@@ -1113,12 +1163,13 @@ export const deleteSchema = createAsyncThunk(export const fetchTables = createAsyncThunk('appMetalakes/fetchTables',- async ({ init, page, metalake, catalog, schema }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, schema }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getTablesApi({ metalake, catalog, schema }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (init && (err || !res)) {@@ -1176,13 +1227,8 @@ export const fetchTables = createAsyncThunk(export const getTableDetails = createAsyncThunk('appMetalakes/getTableDetails',- async ({ init, metalake, catalog, schema, table }, { getState, dispatch }) => {- if (init) {- await dispatch(resetTableData())- await dispatch(setTableLoading(true))- }+ async ({ init, metalake, catalog, schema, table }) => {const [err, res] = await to(getTableDetailsApi({ metalake, catalog, schema, table }))- await dispatch(setTableLoading(false))if (err || !res) {throw new Error(err)}@@ -1283,17 +1329,7 @@ export const getTableDetails = createAsyncThunk(node: 'tableColumn'}))- dispatch(setTableProps(tableProps))-- dispatch(- setExpandedNodes([- `{{${metalake}}}`,- `{{${metalake}}}{{${catalog}}}{{${'relational'}}}`,- `{{${metalake}}}{{${catalog}}}{{${'relational'}}}{{${schema}}}`- ])- )-- return { table: resTable, init }+ return { table: resTable, tableProps, init }})@@ -1433,13 +1469,14 @@ export const deleteTable = createAsyncThunk(export const fetchFilesets = createAsyncThunk('appMetalakes/fetchFilesets',- async ({ init, page, metalake, catalog, schema }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, schema }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getFilesetsApi({ metalake, catalog, schema }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (init && (err || !res)) {@@ -1495,13 +1532,8 @@ export const fetchFilesets = createAsyncThunk(export const getFilesetDetails = createAsyncThunk('appMetalakes/getFilesetDetails',- async ({ init, metalake, catalog, schema, fileset }, { getState, dispatch }) => {- if (init) {- await dispatch(resetTableData())- await dispatch(setTableLoading(true))- }+ async ({ init, metalake, catalog, schema, fileset }) => {const [err, res] = await to(getFilesetDetailsApi({ metalake, catalog, schema, fileset }))- init && (await dispatch(setTableLoading(false)))if (err || !res) {throw new Error(err)@@ -1509,14 +1541,6 @@ export const getFilesetDetails = createAsyncThunk(const { fileset: resFileset } = res- await dispatch(- setExpandedNodes([- `{{${metalake}}}`,- `{{${metalake}}}{{${catalog}}}{{${'fileset'}}}`,- `{{${metalake}}}{{${catalog}}}{{${'fileset'}}}{{${schema}}}`- ])- )-return { fileset: resFileset, init }})@@ -1675,13 +1699,14 @@ export const getFilesetFiles = createAsyncThunk(export const fetchTopics = createAsyncThunk('appMetalakes/fetchTopics',- async ({ init, page, metalake, catalog, schema }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, schema }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getTopicsApi({ metalake, catalog, schema }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (init && (err || !res)) {await dispatch(resetTableData())@@ -1736,12 +1761,8 @@ export const fetchTopics = createAsyncThunk(export const getTopicDetails = createAsyncThunk('appMetalakes/getTopicDetails',- async ({ init, metalake, catalog, schema, topic }, { getState, dispatch }) => {- if (init) {- await dispatch(setTableLoading(true))- }+ async ({ init, metalake, catalog, schema, topic }) => {const [err, res] = await to(getTopicDetailsApi({ metalake, catalog, schema, topic }))- await dispatch(setTableLoading(false))if (err || !res) {throw new Error(err)@@ -1749,14 +1770,6 @@ export const getTopicDetails = createAsyncThunk(const { topic: resTopic } = res- await dispatch(- setExpandedNodes([- `{{${metalake}}}`,- `{{${metalake}}}{{${catalog}}}{{${'messaging'}}}`,- `{{${metalake}}}{{${catalog}}}{{${'messaging'}}}{{${schema}}}`- ])- )-return { topic: resTopic, init }})@@ -1894,13 +1907,14 @@ export const deleteTopic = createAsyncThunk(export const fetchModels = createAsyncThunk('appMetalakes/fetchModels',- async ({ init, page, metalake, catalog, schema }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, schema }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getModelsApi({ metalake, catalog, schema }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (init && (err || !res)) {@@ -1998,14 +2012,14 @@ export const registerModel = createAsyncThunk(export const updateModel = createAsyncThunk('appMetalakes/updateModel',- async ({ init, metalake, catalog, catalogType, schema, model, data }, { getState, dispatch }) => {+ async ({ init, metalake, catalog, catalogType, schema, model, version, data }, { getState, dispatch }) => {const [err, res] = await to(updateModelApi({ metalake, catalog, schema, model, data }))if (err || !res) {return { err: true }}if (init) {- await dispatch(getModelDetails({ init, metalake, catalog, schema, model }))+ await dispatch(getModelDetails({ init, metalake, catalog, schema, model, version }))} else {dispatch(updateModelInStore({ metalake, catalog, catalogType, schema, model, newModel: res.model }))@@ -2100,13 +2114,14 @@ export const deleteModel = createAsyncThunk(export const fetchModelVersions = createAsyncThunk('appMetalakes/fetchModelVersions',- async ({ init, page, metalake, catalog, schema, model }, { getState, dispatch }) => {+ async ({ init, page, metalake, catalog, schema, model }, { getState, dispatch, signal }) => {if (init) {await dispatch(resetTableData())await dispatch(setTableLoading(true))}const [err, res] = await to(getModelVersionsApi({ metalake, catalog, schema, model }))+ if (signal.aborted) returnawait dispatch(setTableLoading(false))if (err || !res) {throw new Error(err)@@ -2212,8 +2227,9 @@ export const deleteVersion = createAsyncThunk(export const fetchFunctions = createAsyncThunk('appMetalakes/fetchFunctions',- async ({ init, metalake, catalog, schema }, { dispatch }) => {+ async ({ init, metalake, catalog, schema }, { dispatch, signal }) => {const [err, res] = await to(getFunctionsApi({ metalake, catalog, schema, details: true }))+ if (signal.aborted) returnif (init && (err || !res)) {throw new Error(err)@@ -2247,8 +2263,9 @@ export const getFunctionDetails = createAsyncThunk(export const fetchViews = createAsyncThunk('appMetalakes/fetchViews',- async ({ init, metalake, catalog, schema }, { getState, dispatch }) => {+ async ({ init, metalake, catalog, schema }, { getState, dispatch, signal }) => {const [err, res] = await to(getViewsApi({ metalake, catalog, schema }, { errorMessageMode: 'none' }))+ if (signal.aborted) returnif (err || !res) {// Catalog doesn't support views (HTTP 501, or legacy 405 with code 1006) — return empty views silently@@ -2333,6 +2350,176 @@ export const deleteView = createAsyncThunk(})+export const fetchSemanticModels = createAsyncThunk(+ 'appMetalakes/fetchSemanticModels',+ async ({ init, metalake, catalog, schema }, { getState, requestId }) => {+ const schemaKey = semanticModelSchemaKey({ metalake, catalog, schema })+ const [err, res] = await to(getSemanticModelsApi({ metalake, catalog, schema }, { errorMessageMode: 'none' }))++ if (getState().metalakes.semanticModelRequests[schemaKey]?.requestId !== requestId) {+ return { stale: true }+ }++ 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, schemaKey }+ }+ 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: []+ }+ })++ return { semanticModels, init, schemaKey }+ }+)++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, getState }) => {+ const activeEntity = getState().metalakes.activeCatalogEntity+ await dispatch(setTableLoading(true))+ const [err, res] = await to(createSemanticModelApi({ data, metalake, catalog, schema }))+ if (getState().metalakes.activeCatalogEntity === activeEntity) 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, expectedDefinition }, { dispatch, getState }) => {+ const activeEntity = getState().metalakes.activeCatalogEntity+ if (data.updates.some(update => update['@type'] === 'replaceDefinition')) {+ // Detect intervening edits; atomic protection still requires a server-side version token.+ const [err, current] = await to(+ getSemanticModelDetailsApi(+ { metalake, catalog, schema, semanticModel },+ { errorMessageMode: 'none', ignoreCancelToken: true }+ )+ )+ if (err || !current?.semanticModel?.definition || !expectedDefinition) {+ return {+ err: true,+ message: semanticModelErrorMessage(+ err,+ 'Unable to verify the current definition. Reload the model and try again.'+ )+ }+ }+ if (!_.isEqual(current.semanticModel.definition, expectedDefinition)) {+ return {+ err: true,+ message:+ 'The definition has changed since this editor was opened. Copy your edits, then refresh the page and reapply them to the latest definition.'+ }+ }+ }+ if (getState().metalakes.activeCatalogEntity === activeEntity) await dispatch(setTableLoading(true))+ const [err, res] = await to(updateSemanticModelApi({ metalake, catalog, schema, semanticModel, data }))+ if (getState().metalakes.activeCatalogEntity === activeEntity) await dispatch(setTableLoading(false))++ if (err || !res?.semanticModel) {+ return { err: true, message: semanticModelErrorMessage(err, 'Failed to update the Semantic Model.') }+ }++ await dispatch(fetchSemanticModels({ metalake, catalog, schema, init: true }))++ return res.semanticModel+ }+)++export const deleteSemanticModel = createAsyncThunk(+ 'appMetalakes/deleteSemanticModel',+ async ({ metalake, catalog, schema, semanticModel }, { dispatch, getState }) => {+ const activeEntity = getState().metalakes.activeCatalogEntity+ await dispatch(setTableLoading(true))+ const [err, res] = await to(deleteSemanticModelApi({ metalake, catalog, schema, semanticModel }))+ if (getState().metalakes.activeCatalogEntity === activeEntity) await dispatch(setTableLoading(false))++ if (err) {+ throw err instanceof Error ? err : new Error(err?.message ?? String(err))+ }++ if (!res) {+ throw new Error('Semantic Model deletion returned an empty response')+ }++ await dispatch(fetchSemanticModels({ metalake, catalog, schema, init: true }))++ return res+ }+)++// Keep the latest list generation only until all overlapping list/tree loads have settled.+const trackSemanticModelRequest = (state, key, requestId, list = false) => {+ const request = (state.semanticModelRequests[key] ??= { inFlight: [] })+ request.inFlight.push(requestId)+ if (list) request.requestId = requestId+}++const finishSemanticModelRequest = (state, key, requestId) => {+ const request = state.semanticModelRequests[key]+ if (!request) return+ request.inFlight = request.inFlight.filter(id => id !== requestId)+ if (!request.inFlight.length) delete state.semanticModelRequests[key]+}+export const appMetalakesSlice = createSlice({name: 'appMetalakes',initialState: {@@ -2346,6 +2533,15 @@ export const appMetalakesSlice = createSlice({tables: [],functions: [],views: [],+ semanticModels: [],+ semanticModelRequests: {},+ semanticModelListRequestId: null,+ entityDetailRequestId: null,+ entityTagsRequestId: null,+ entityPoliciesRequestId: null,+ activeCatalogEntity: null,+ activeSemanticModelSchema: null,+ activatedDetailsKey: null,columns: [],filesets: [],topics: [],@@ -2364,6 +2560,25 @@ export const appMetalakesSlice = createSlice({currentEntityPolicies: []},reducers: {+ setActiveCatalogEntity(state, action) {+ const key = catalogEntityKey(action.payload)+ const schemaKey = action.payload.schema ? semanticModelSchemaKey(action.payload) : null+ if (state.activeSemanticModelSchema !== schemaKey) state.semanticModels = []+ state.activeSemanticModelSchema = schemaKey+ if (state.activeCatalogEntity === key) return+ state.activeCatalogEntity = key+ state.activatedDetails = null+ state.activatedDetailsKey = null+ state.entityDetailRequestId = null+ state.entityTagsRequestId = null+ state.entityPoliciesRequestId = null+ state.currentEntityTags = []+ state.currentEntityPolicies = []+ state.activatedDetailsLoading = false+ state.tableLoading = false+ state.tableData = []+ state.tableProps = []+ },setFilteredMetalakes(state, action) {state.filteredMetalakes = action.payload},@@ -2377,6 +2592,13 @@ export const appMetalakesSlice = createSlice({state.loadedNodes = action.payload},setSelectedNodes(state, action) {+ if (state.selectedNodes.join() !== action.payload.join()) {+ state.entityDetailRequestId = null+ state.entityTagsRequestId = null+ state.entityPoliciesRequestId = null+ state.currentEntityPolicies = []+ state.currentEntityTags = []+ }state.selectedNodes = action.payload},setExpanded(state, action) {@@ -2412,6 +2634,13 @@ export const appMetalakesSlice = createSlice({state.tables = []state.functions = []state.views = []+ state.semanticModels = []+ state.activatedDetailsKey = null+ state.entityPoliciesRequestId = null+ state.semanticModelRequests = {}+ state.semanticModelListRequestId = null+ state.entityDetailRequestId = null+ state.entityTagsRequestId = nullstate.columns = []state.filesets = []state.topics = []@@ -2429,6 +2658,8 @@ export const appMetalakesSlice = createSlice({},resetActivatedDetails(state, action) {state.activatedDetails = null+ state.entityDetailRequestId = null+ state.activatedDetailsKey = null// Also clear table-related data to avoid stale content when switching detailsstate.tableData = []@@ -2698,6 +2929,15 @@ export const appMetalakesSlice = createSlice({state.schemas = []state.tables = []state.views = []+ state.semanticModels = []+ state.activeCatalogEntity = null+ state.activeSemanticModelSchema = null+ state.activatedDetailsKey = null+ state.entityPoliciesRequestId = null+ state.semanticModelRequests = {}+ state.semanticModelListRequestId = null+ state.entityDetailRequestId = null+ state.entityTagsRequestId = nullstate.columns = []state.filesets = []state.topics = []@@ -2717,33 +2957,102 @@ export const appMetalakesSlice = createSlice({}},extraReducers: builder => {+ const detailThunks = [+ [getMetalakeDetails, 'metalake'],+ [getCatalogDetails, 'catalog'],+ [getSchemaDetails, 'schema'],+ [getTableDetails, 'table'],+ [getFilesetDetails, 'fileset'],+ [getTopicDetails, 'topic'],+ [getModelDetails, 'model'],+ [getFunctionDetails, 'function'],+ [getViewDetails, 'view'],+ [getSemanticModelDetails, 'semanticModel']+ ]+ for (const [thunk, kind] of detailThunks) {+ const keyFor = arg => catalogEntityKey({ ...arg, function: arg.functionName || arg.function })++ const isVisible = (state, action) =>+ (kind === 'metalake' || action.meta.arg?.init) &&+ (!state.activeCatalogEntity || state.activeCatalogEntity === keyFor(action.meta.arg))+ builder.addCase(thunk.pending, (state, action) => {+ if (!isVisible(state, action)) return+ state.entityDetailRequestId = action.meta.requestId+ state.activatedDetails = null+ state.activatedDetailsKey = null+ if (['table', 'fileset', 'topic'].includes(kind)) {+ state.tableLoading = true+ state.tableData = []+ state.tableProps = []+ }+ })+ builder.addCase(thunk.fulfilled, (state, action) => {+ if (!isVisible(state, action) || state.entityDetailRequestId !== action.meta.requestId) return+ state.activatedDetails = kind === 'metalake' ? action.payload : action.payload[kind]+ state.activatedDetailsKey = keyFor(action.meta.arg)+ if (['table', 'fileset', 'topic'].includes(kind)) {+ state.tableLoading = false+ const { metalake, catalog, schema } = action.meta.arg+ const type = { table: 'relational', fileset: 'fileset', topic: 'messaging' }[kind]+ state.expandedNodes = [+ ...new Set([+ ...state.expandedNodes,+ `{{${metalake}}}`,+ `{{${metalake}}}{{${catalog}}}{{${type}}}`,+ `{{${metalake}}}{{${catalog}}}{{${type}}}{{${schema}}}`+ ])+ ]+ }+ if (kind === 'table') {+ state.tableData = action.payload.table.columns || []+ state.tableProps = action.payload.tableProps+ }+ })+ builder.addCase(thunk.rejected, (state, action) => {+ if (action.meta.aborted) return+ if (action.meta.arg.init || kind === 'metalake') {+ if (!isVisible(state, action) || state.entityDetailRequestId !== action.meta.requestId) return+ state.tableLoading = false+ }+ if (action.error.name !== 'CanceledError' && !action.error.message.includes('CanceledError'))+ toast.error(action.error.message)+ })+ }builder.addCase(fetchMetalakes.fulfilled, (state, action) => {state.metalakes = action.payload.metalakes})builder.addCase(fetchMetalakes.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})+ builder.addCase(setIntoTreeNodeWithFetch.pending, (state, action) => {+ if (extractPlaceholder(action.meta.arg.key).length === 4)+ trackSemanticModelRequest(state, action.meta.arg.key, action.meta.requestId)+ })builder.addCase(setIntoTreeNodeWithFetch.fulfilled, (state, action) => {- const { key, data, entities } = action.payload+ const { key, data, entities, semanticModelRequestId } = action.payload+ const latest = state.semanticModelRequests[key]- state.metalakeTree = updateTreeData(state.metalakeTree, key, data)+ // A pre-refresh tree load must not restore an older Semantic Model list either.+ const currentModels =+ findInTree(state.metalakeTree, 'key', key)?.children?.filter(node => node.node === 'semanticModel') ?? []++ const children =+ latest && latest.requestId !== semanticModelRequestId+ ? [...data.filter(node => node.node !== 'semanticModel'), ...currentModels]+ : data++ state.metalakeTree = updateTreeData(state.metalakeTree, key, children)+ finishSemanticModelRequest(state, key, action.meta.requestId)if (entities && state.selectedNodes.includes(key)) {state.tableData = entities}})builder.addCase(setIntoTreeNodeWithFetch.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getMetalakeDetails.fulfilled, (state, action) => {- state.activatedDetails = action.payload- })- builder.addCase(getMetalakeDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ finishSemanticModelRequest(state, action.meta.arg.key, action.meta.requestId)+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2753,58 +3062,66 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(getCurrentEntityOwner.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}state.currentMetalakeOwner = null})builder.addCase(setEntityOwner.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})+ builder.addCase(getCurrentEntityTags.pending, (state, action) => {+ if (action.meta.arg.init) state.entityTagsRequestId = action.meta.requestId+ })builder.addCase(getCurrentEntityTags.fulfilled, (state, action) => {- if (action.payload.init) {+ if (action.payload.init && state.entityTagsRequestId === action.meta.requestId) {state.currentEntityTags = action.payload.tags}})builder.addCase(getCurrentEntityTags.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (action.meta.aborted || (action.meta.arg.init && state.entityTagsRequestId !== action.meta.requestId)) return+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})+ builder.addCase(getCurrentEntityPolicies.pending, (state, action) => {+ if (action.meta.arg.init) state.entityPoliciesRequestId = action.meta.requestId+ })builder.addCase(getCurrentEntityPolicies.fulfilled, (state, action) => {- if (action.payload.init) {+ if (action.payload.init && state.entityPoliciesRequestId === action.meta.requestId) {state.currentEntityPolicies = action.payload.policies}})builder.addCase(getCurrentEntityPolicies.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (action.meta.arg.init && state.entityPoliciesRequestId !== action.meta.requestId) return+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(getMetadataObjectsForTag.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(getMetadataObjectsForPolicy.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(createCatalog.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(testCatalogConnection.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateCatalog.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2820,22 +3137,12 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchCatalogs.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getCatalogDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.catalog- }- })- builder.addCase(getCatalogDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteCatalog.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2850,32 +3157,22 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchSchemas.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getSchemaDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.schema- }- })- builder.addCase(getSchemaDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(createSchema.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateSchema.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteSchema.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2886,33 +3183,22 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchTables.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getTableDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.table- state.tableData = action.payload.columns || []- }- })- builder.addCase(getTableDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(createTable.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateTable.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteTable.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2923,34 +3209,22 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchFilesets.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getFilesetDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.fileset- }-- // state.tableData = []- })- builder.addCase(getFilesetDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(createFileset.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateFileset.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteFileset.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2958,7 +3232,7 @@ export const appMetalakesSlice = createSlice({state.tableData = action.payload.files})builder.addCase(getFilesetFiles.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -2969,32 +3243,22 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchTopics.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getTopicDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.topic- }- })- builder.addCase(getTopicDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(createTopic.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateTopic.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteTopic.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -3005,32 +3269,22 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchModels.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getModelDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.model- }- })- builder.addCase(getModelDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(registerModel.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateModel.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteModel.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -3041,25 +3295,15 @@ export const appMetalakesSlice = createSlice({}})builder.addCase(fetchModelVersions.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(fetchFunctions.fulfilled, (state, action) => {state.functions = action.payload.functions})- builder.addCase(getFunctionDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.function- }- })builder.addCase(fetchFunctions.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {- toast.error(action.error.message)- }- })- builder.addCase(getFunctionDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -3067,42 +3311,74 @@ export const appMetalakesSlice = createSlice({state.views = action.payload.views})builder.addCase(fetchViews.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})- builder.addCase(getViewDetails.fulfilled, (state, action) => {- if (action.payload.init) {- state.activatedDetails = action.payload.view+ builder.addCase(deleteView.rejected, (state, action) => {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {+ toast.error(action.error.message)}})- builder.addCase(getViewDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ builder.addCase(fetchSemanticModels.pending, (state, action) => {+ const key = semanticModelSchemaKey(action.meta.arg)+ trackSemanticModelRequest(state, key, action.meta.requestId, true)+ if (!state.activeCatalogEntity || state.activeSemanticModelSchema === key)+ state.semanticModelListRequestId = action.meta.requestId+ })+ builder.addCase(fetchSemanticModels.fulfilled, (state, action) => {+ const key = semanticModelSchemaKey(action.meta.arg)+ const request = state.semanticModelRequests[key]+ if (!action.payload.stale && request?.requestId === action.meta.requestId) {+ // A model list is only a partial set of schema children; leave unloaded nodes expandable.+ if (action.meta.arg.init && state.loadedNodes.includes(key)) {+ const data = mergeWithSemanticModelNodes({+ tree: state.metalakeTree,+ key,+ entities: action.payload.semanticModels+ })+ state.metalakeTree = updateTreeData(state.metalakeTree, key, data)+ }+ if (+ (!state.activeCatalogEntity || state.activeSemanticModelSchema === key) &&+ state.semanticModelListRequestId === action.meta.requestId+ )+ state.semanticModels = action.payload.semanticModels+ }+ finishSemanticModelRequest(state, key, action.meta.requestId)+ })+ builder.addCase(fetchSemanticModels.rejected, (state, action) => {+ finishSemanticModelRequest(state, semanticModelSchemaKey(action.meta.arg), action.meta.requestId)+ if (+ !action.meta.aborted &&+ action.error.name !== 'CanceledError' &&+ !action.error.message.includes('CanceledError')+ ) {toast.error(action.error.message)}})- builder.addCase(deleteView.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ builder.addCase(deleteSemanticModel.rejected, (state, action) => {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(getVersionDetails.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(linkVersion.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(updateVersion.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})builder.addCase(deleteVersion.rejected, (state, action) => {- if (!action.error.message.includes('CanceledError')) {+ if (!action.meta.aborted && !action.error.message.includes('CanceledError')) {toast.error(action.error.message)}})@@ -3113,6 +3389,7 @@ export const {setFilteredMetalakes,setMetalakeTree,setSelectedNodes,+ setActiveCatalogEntity,removeExpandedNode,resetMetalakeStore,resetExpandNode,diff --git a/web-v2/web/src/lib/store/metalakes/semanticModelConcurrency.test.js b/web-v2/web/src/lib/store/metalakes/semanticModelConcurrency.test.jsnew file mode 100644index 0000000000..09d7e496cd--- /dev/null+++ b/web-v2/web/src/lib/store/metalakes/semanticModelConcurrency.test.js@@ -0,0 +1,279 @@+/*+ * 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 { afterEach, expect, it, vi } from 'vitest'+import { configureStore } from '@reduxjs/toolkit'+import { defHttp } from '@/lib/utils/axios'+import reducer, {+ fetchSemanticModels,+ setIntoTreeNodeWithFetch,+ setMetalakeTree,+ setLoadedNodes,+ setSelectedNodes,+ getSemanticModelDetails,+ getCurrentEntityTags,+ getCurrentEntityPolicies,+ getSchemaDetails,+ getTableDetails,+ getCatalogDetails,+ getFilesetDetails,+ getTopicDetails,+ getModelDetails,+ getFunctionDetails,+ getViewDetails,+ getMetalakeDetails,+ setActiveCatalogEntity,+ updateSemanticModel+} from './index'++const adapter = defHttp.getAxios().defaults.adapter++afterEach(() => {+ defHttp.getAxios().defaults.adapter = adapter+})++it.each([0, 1])('loads both the schema tab and tree when concurrent response %s finishes first', async first => {+ const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ const key = '{{demo}}{{sales}}{{relational}}{{mart}}'+ const store = configureStore({ reducer: { metalakes: reducer } })+ store.dispatch(setMetalakeTree([{ key, node: 'schema', children: [] }]))+ const responses = []++ // Replace only the transport, keeping the real Axios cancellation and response interceptors.+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ const semanticModels = config.url.split('?')[0].endsWith('/semantic-models')++ const respond = () =>+ resolve({+ config,+ status: 200,+ statusText: 'OK',+ headers: {},+ data: {+ code: 0,+ identifiers: semanticModels ? [{ namespace: ['demo', 'sales', 'mart'], name: 'orders' }] : []+ }+ })+ if (semanticModels) responses.push(respond)+ else respond()+ })++ const list = store.dispatch(fetchSemanticModels({ ...namespace, init: true }))+ await vi.waitFor(() => expect(responses).toHaveLength(1))+ const tree = store.dispatch(setIntoTreeNodeWithFetch({ key }))+ await vi.waitFor(() => expect(responses).toHaveLength(2))+ responses[first]()+ await (first === 0 ? list : tree)+ responses[1 - first]()++ const [listResult, treeResult] = await Promise.all([list, tree])+ expect(listResult.meta.requestStatus).toBe('fulfilled')+ expect(treeResult.meta.requestStatus).toBe('fulfilled')+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['orders'])+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+ expect(treeResult.payload.data.some(node => node.node === 'semanticModel' && node.name === 'orders')).toBe(true)+})++it.each(['list', 'tree'])('ignores an older %s response after a successful list refresh', async consumer => {+ const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ const key = '{{demo}}{{sales}}{{relational}}{{mart}}'+ const store = configureStore({ reducer: { metalakes: reducer } })+ store.dispatch(setMetalakeTree([{ key, node: 'schema', children: [] }]))+ store.dispatch(setLoadedNodes([key]))+ const responses = []+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ const respond = names =>+ resolve({+ config,+ status: 200,+ statusText: 'OK',+ headers: {},+ data: {+ code: 0,+ identifiers: names.map(name => ({ namespace: ['demo', 'sales', 'mart'], name }))+ }+ })+ if (config.url.split('?')[0].endsWith('/semantic-models')) responses.push(respond)+ else respond([])+ })++ const initial = store.dispatch(+ consumer === 'tree' ? setIntoTreeNodeWithFetch({ key }) : fetchSemanticModels({ ...namespace, init: true })+ )+ await vi.waitFor(() => expect(responses).toHaveLength(1))+ const refresh = store.dispatch(fetchSemanticModels({ ...namespace, init: true }))+ await vi.waitFor(() => expect(responses).toHaveLength(2))+ responses[1](['orders', 'imported'])+ await refresh+ responses[0](['orders'])+ await initial+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['orders', 'imported'])+ expect(store.getState().metalakes.metalakeTree[0].children.map(model => model.name)).toEqual(['orders', 'imported'])+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+})++it.each(['model', 'schema', 'pending model'])(+ 'ignores late model details after navigating to %s',+ async destination => {+ const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ const store = configureStore({ reducer: { metalakes: reducer } })+ const responses = []+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ responses.push(value =>+ resolve({ config, status: 200, statusText: 'OK', headers: {}, data: { code: 0, ...value } })+ )+ })+ const first = store.dispatch(getSemanticModelDetails({ ...namespace, semanticModel: 'first', init: true }))+ await vi.waitFor(() => expect(responses).toHaveLength(1))+ store.dispatch(setSelectedNodes([destination]))++ const next = store.dispatch(+ destination === 'schema'+ ? getSchemaDetails({ ...namespace, init: true })+ : getSemanticModelDetails({ ...namespace, semanticModel: 'second', init: true })+ )+ await vi.waitFor(() => expect(responses).toHaveLength(2))+ if (destination !== 'pending model') {+ responses[1]({ semanticModel: { name: 'second' }, schema: { name: 'mart' } })+ await next+ }+ const before = store.getState().metalakes.activatedDetails+ responses[0]({ semanticModel: { name: 'first' } })+ await first+ expect(store.getState().metalakes.activatedDetails).toEqual(before)+ if (destination === 'pending model') {+ responses[1]({ semanticModel: { name: 'second' } })+ await next+ expect(store.getState().metalakes.activatedDetails.name).toBe('second')+ }+ }+)++it.each([getCurrentEntityTags, getCurrentEntityPolicies])(+ 'ignores old entity tags/policies before the next request',+ async fetch => {+ const store = configureStore({ reducer: { metalakes: reducer } })+ let respond+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ respond = () =>+ resolve({+ config,+ status: 200,+ statusText: 'OK',+ headers: {},+ data: { code: 0, tags: [{ name: 'old' }], policies: [{ name: 'old' }] }+ })+ })++ const request = store.dispatch(+ fetch({+ init: true,+ metalake: 'demo',+ metadataObjectType: 'semantic_model',+ metadataObjectFullName: 'sales.mart.old'+ })+ )+ await vi.waitFor(() => expect(respond).toBeTypeOf('function'))+ store.dispatch(setSelectedNodes(['new']))+ respond()+ await request+ expect(store.getState().metalakes.currentEntityTags).toEqual([])+ expect(store.getState().metalakes.currentEntityPolicies).toEqual([])+ }+)++it.each([+ [getMetalakeDetails, { metalake: 'demo' }, { name: 'demo' }],+ [getCatalogDetails, { metalake: 'demo', catalog: 'sales' }, { catalog: { name: 'sales' } }],+ [getSchemaDetails, {}, { schema: { name: 'mart' } }],+ [getTableDetails, { table: 'orders' }, { table: { name: 'orders', columns: [], distribution: { funcArgs: [] } } }],+ [getFilesetDetails, { fileset: 'orders' }, { fileset: { name: 'orders' } }],+ [getTopicDetails, { topic: 'orders' }, { topic: { name: 'orders' } }],+ [getModelDetails, { model: 'orders' }, { model: { name: 'orders' } }],+ [getFunctionDetails, { functionName: 'orders' }, { function: { name: 'orders' } }],+ [getViewDetails, { view: 'orders' }, { view: { name: 'orders' } }]+])('rejects a late $typePrefix writer after model navigation', async (thunk, args, payload) => {+ const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ const store = configureStore({ reducer: { metalakes: reducer } })+ const responses = []+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ responses.push(data =>+ resolve({ config, status: 200, statusText: 'OK', headers: {}, data: { code: 0, ...data } })+ )+ })+ const old = store.dispatch(thunk({ ...namespace, ...args, init: true }))+ await vi.waitFor(() => expect(responses).toHaveLength(1))+ const nextArgs = { ...namespace, semanticModel: 'orders', init: true }+ store.dispatch(setActiveCatalogEntity(nextArgs))+ const next = store.dispatch(getSemanticModelDetails(nextArgs))+ await vi.waitFor(() => expect(responses).toHaveLength(2))+ responses[1]({ semanticModel: { name: 'orders', definition: { datasets: [] } } })+ await next+ const before = store.getState().metalakes+ responses[0](payload)+ await old+ expect(store.getState().metalakes).toEqual(before)+})++it('refreshes the saved schema tree without replacing the newly selected schema list', async () => {+ const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+ const key = '{{demo}}{{sales}}{{relational}}{{mart}}'+ const store = configureStore({ reducer: { metalakes: reducer } })+ store.dispatch(setMetalakeTree([{ key, node: 'schema', children: [] }]))+ store.dispatch(setLoadedNodes([key]))+ store.dispatch(setActiveCatalogEntity({ ...namespace, semanticModel: 'orders' }))+ let finishSave+ defHttp.getAxios().defaults.adapter = config =>+ new Promise(resolve => {+ const respond = data =>+ resolve({ config, status: 200, statusText: 'OK', headers: {}, data: { code: 0, ...data } })+ if (config.method === 'put') finishSave = () => respond({ semanticModel: { name: 'renamed' } })+ else respond({ identifiers: [{ name: config.url.includes('/mart/') ? 'renamed' : 'schema_b_model' }] })+ })+ const save = store.dispatch(updateSemanticModel({ ...namespace, semanticModel: 'orders', data: { updates: [] } }))+ await vi.waitFor(() => expect(finishSave).toBeTypeOf('function'))+ store.dispatch(setActiveCatalogEntity({ ...namespace, schema: 'other' }))+ await store.dispatch(fetchSemanticModels({ ...namespace, schema: 'other', init: true }))+ finishSave()+ await save+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['schema_b_model'])+ expect(store.getState().metalakes.metalakeTree[0].children.map(model => model.name)).toEqual(['renamed'])+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+})++it.each(['success', 'failure', 'abort'])('releases request records after %s across many schemas', async result => {+ const store = configureStore({ reducer: { metalakes: reducer } })+ defHttp.getAxios().defaults.adapter = config => {+ if (result === 'failure') return Promise.reject(new Error('Unavailable'))+ if (result === 'abort') return new Promise(() => {})++ return Promise.resolve({ config, status: 200, statusText: 'OK', headers: {}, data: { code: 0, identifiers: [] } })+ }+ for (let i = 0; i < 20; i++) {+ const request = store.dispatch(fetchSemanticModels({ metalake: 'demo', catalog: 'sales', schema: 'schema_' + i }))+ if (result === 'abort') request.abort()+ await request+ }+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+})diff --git a/web-v2/web/src/lib/store/metalakes/semanticModels.test.js b/web-v2/web/src/lib/store/metalakes/semanticModels.test.jsnew file mode 100644index 0000000000..87c8c9f923--- /dev/null+++ b/web-v2/web/src/lib/store/metalakes/semanticModels.test.js@@ -0,0 +1,345 @@+/*+ * 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 { beforeEach, describe, expect, it, vi } from 'vitest'+import { configureStore } from '@reduxjs/toolkit'+import toast from 'react-hot-toast'+import { defHttp } from '@/lib/utils/axios'+import reducer, {+ resetMetalakeStore,+ deleteSemanticModel,+ fetchSemanticModels,+ fetchTables,+ fetchViews,+ getSemanticModelDetails,+ updateSemanticModel,+ setIntoTreeNodeWithFetch,+ setLoadedNodes,+ setMetalakeTree,+ setActiveCatalogEntity+} from './index'++vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), delete: vi.fn(), put: vi.fn() } }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++const namespace = { metalake: 'demo', catalog: 'sales', schema: 'mart' }+const schemaKey = '{{demo}}{{sales}}{{relational}}{{mart}}'+let store++beforeEach(() => {+ vi.clearAllMocks()+ store = configureStore({ reducer: { metalakes: reducer } })+})++describe('definition replacement conflict checks', () => {+ const original = { datasets: [], aiContext: 'Original guidance' }+ const updated = { ...original, aiContext: 'My draft' }++ const args = {+ ...namespace,+ semanticModel: 'orders',+ expectedDefinition: original,+ data: { updates: [{ '@type': 'replaceDefinition', definition: updated }] }+ }++ it('does not change another page loading state after a delayed verification read', async () => {+ store.dispatch(setActiveCatalogEntity({ ...namespace, semanticModel: 'orders' }))+ let verify+ let finishSave+ defHttp.get.mockImplementation(({ url }) =>+ url.endsWith('/orders')+ ? new Promise(resolve => {+ verify = resolve+ })+ : Promise.resolve({ identifiers: [] })+ )+ defHttp.put.mockImplementation(+ () =>+ new Promise(resolve => {+ finishSave = resolve+ })+ )+ const save = store.dispatch(updateSemanticModel(args))+ store.dispatch(setActiveCatalogEntity({ ...namespace, schema: 'other' }))+ verify({ semanticModel: { definition: original } })+ await vi.waitFor(() => expect(finishSave).toBeTypeOf('function'))+ expect(store.getState().metalakes.tableLoading).toBe(false)+ finishSave({ semanticModel: { name: 'orders', definition: updated } })+ await save+ expect(store.getState().metalakes.tableLoading).toBe(false)+ expect(store.getState().metalakes.semanticModels).toEqual([])+ })++ it('refuses to overwrite a definition changed since the editor opened', async () => {+ defHttp.get.mockResolvedValue({ semanticModel: { definition: { ...original, aiContext: 'Other writer' } } })+ const result = await store.dispatch(updateSemanticModel(args))+ expect(result.payload.err).toBe(true)+ expect(result.payload.message).toContain('changed since')+ expect(defHttp.put).not.toHaveBeenCalled()+ expect(store.getState().metalakes.tableLoading).toBe(false)+ })++ it('compares definitions independently of object key order before saving', async () => {+ defHttp.get+ .mockResolvedValueOnce({ semanticModel: { definition: { aiContext: 'Original guidance', datasets: [] } } })+ .mockResolvedValue({ identifiers: [] })+ defHttp.put.mockResolvedValue({ semanticModel: { name: 'orders', definition: updated } })+ const result = await store.dispatch(updateSemanticModel(args))+ expect(result.payload.definition).toEqual(updated)+ expect(defHttp.put.mock.calls[0][0].data).toEqual(args.data)+ expect(defHttp.get.mock.invocationCallOrder[0]).toBeLessThan(defHttp.put.mock.invocationCallOrder[0])+ })++ it.each(['error', 'missing definition', 'missing snapshot'])(+ 'does not save when verification fails: %s',+ async reason => {+ if (reason === 'error') defHttp.get.mockRejectedValue(new Error('Read denied'))+ else+ defHttp.get.mockResolvedValue({+ semanticModel: reason === 'missing definition' ? {} : { definition: original }+ })++ const result = await store.dispatch(+ updateSemanticModel({ ...args, expectedDefinition: reason === 'missing snapshot' ? undefined : original })+ )+ expect(result.payload.err).toBe(true)+ expect(defHttp.put).not.toHaveBeenCalled()+ }+ )+})++describe('semantic model tree identity', () => {+ it('keeps a same-named table and model through expansion and list refreshes', async () => {+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve({ identifiers: url.endsWith('/functions') || url.endsWith('/views') ? [] : [{ name: 'orders' }] })+ )+ store.dispatch(setMetalakeTree([{ key: schemaKey, node: 'schema', children: [] }]))+ store.dispatch(setLoadedNodes([schemaKey]))++ const loaded = await store.dispatch(setIntoTreeNodeWithFetch({ key: schemaKey }))+ const children = loaded.payload.data+ const model = children.find(node => node.node === 'semanticModel')+ const table = children.find(node => node.node === 'table')+ expect(model.key).not.toBe(table.key)+ expect(model.id).not.toBe(table.id)++ for (const fetch of [fetchSemanticModels, fetchTables, fetchViews]) {+ await store.dispatch(fetch({ ...namespace, init: true }))+ const refreshed = store.getState().metalakes.metalakeTree[0].children+ expect(+ refreshed+ .filter(node => node.name === 'orders')+ .map(node => node.node)+ .sort()+ ).toEqual(['semanticModel', 'table'])+ expect(refreshed.find(node => node.node === 'semanticModel').key).toBe(model.key)+ }+ })+})++describe('semantic model load errors', () => {+ it.each([true, false])('rejects list failures and retains previous data when init=%s', async init => {+ store.dispatch(fetchSemanticModels.pending('old', namespace))+ store.dispatch(fetchSemanticModels.fulfilled({ semanticModels: [{ name: 'existing' }] }, 'old', namespace))+ defHttp.get.mockRejectedValue({ message: 'Server unavailable', response: { status: 500 } })+ const result = await store.dispatch(fetchSemanticModels({ ...namespace, init }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(result.error.message).toBe('Server unavailable')+ expect(store.getState().metalakes.semanticModels).toEqual([{ name: 'existing' }])+ })++ it.each([fetchSemanticModels, getSemanticModelDetails])(+ 'keeps canceled requests quiet for $typePrefix',+ async fetch => {+ defHttp.get.mockRejectedValue(Object.assign(new Error('canceled'), { name: 'CanceledError' }))+ const result = await store.dispatch(fetch({ ...namespace, semanticModel: 'orders' }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(toast.error).not.toHaveBeenCalled()+ }+ )++ it.each([404, 405])('treats unsupported list endpoints (%s) as empty', async status => {+ defHttp.get.mockRejectedValue({ response: { status } })+ const result = await store.dispatch(fetchSemanticModels(namespace))+ expect(result.payload.semanticModels).toEqual([])+ })++ it.each([fetchSemanticModels, getSemanticModelDetails])(+ 'preserves useful error messages for $typePrefix',+ async fetch => {+ defHttp.get.mockRejectedValue({ message: 'Permission denied', response: { status: 403 } })+ const result = await store.dispatch(fetch({ ...namespace, semanticModel: 'orders', init: true }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(result.error.message).toBe('Permission denied')+ }+ )++ it.each([fetchSemanticModels, getSemanticModelDetails])('reports empty responses for $typePrefix', async fetch => {+ defHttp.get.mockResolvedValue(undefined)+ const result = await store.dispatch(fetch({ ...namespace, semanticModel: 'orders' }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(result.error.message).toMatch(/empty response/i)+ })+})++describe('semantic model deletion errors', () => {+ it.each([new Error('Permission denied'), { message: 'Permission denied' }])(+ 'preserves a deletion error: %j',+ async error => {+ defHttp.delete.mockRejectedValue(error)+ const result = await store.dispatch(deleteSemanticModel({ ...namespace, semanticModel: 'orders' }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(result.error.message).toBe('Permission denied')+ expect(store.getState().metalakes.tableLoading).toBe(false)+ expect(defHttp.get).not.toHaveBeenCalled()+ }+ )++ it('reports an empty deletion response', async () => {+ defHttp.delete.mockResolvedValue(undefined)+ const result = await store.dispatch(deleteSemanticModel({ ...namespace, semanticModel: 'orders' }))+ expect(result.meta.requestStatus).toBe('rejected')+ expect(result.error.message).toMatch(/empty response/i)+ expect(defHttp.get).not.toHaveBeenCalled()+ })+})++describe('superseded Semantic Model lists', () => {+ it('ignores an old failure after a successful refresh', async () => {+ let rejectInitial+ defHttp.get.mockImplementationOnce(+ () =>+ new Promise((resolve, reject) => {+ rejectInitial = reject+ })+ )+ const initial = store.dispatch(fetchSemanticModels(namespace))+ defHttp.get.mockResolvedValueOnce({ identifiers: [{ name: 'new' }] })+ await store.dispatch(fetchSemanticModels(namespace))+ rejectInitial(new Error('Old request failed'))+ await initial+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['new'])+ expect(toast.error).not.toHaveBeenCalled()+ })++ it('does not replace a newly selected schema with an older schema response', async () => {+ let resolveInitial+ defHttp.get.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ resolveInitial = resolve+ })+ )+ const initial = store.dispatch(fetchSemanticModels(namespace))+ defHttp.get.mockResolvedValueOnce({ identifiers: [{ name: 'other_model' }] })+ await store.dispatch(fetchSemanticModels({ ...namespace, schema: 'other' }))+ resolveInitial({ identifiers: [{ name: 'old_model' }] })+ await initial+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['other_model'])+ })++ it('clears request tracking and ignores in-flight results when resetting the store', async () => {+ let resolveInitial+ defHttp.get.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ resolveInitial = resolve+ })+ )+ const initial = store.dispatch(fetchSemanticModels(namespace))+ store.dispatch(resetMetalakeStore())+ resolveInitial({ identifiers: [{ name: 'old_model' }] })+ await initial+ expect(store.getState().metalakes.semanticModels).toEqual([])+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+ expect(store.getState().metalakes.semanticModelListRequestId).toBeNull()+ })+})++describe('semantic metadata update errors', () => {+ it.each([+ [{ response: { data: { message: 'Permission denied for this model' } } }, 'Permission denied for this model'],+ [{ response: { data: { error: { message: 'Unknown source column amount' } } } }, 'Unknown source column amount'],+ [new Error('Network unavailable'), 'Network unavailable']+ ])('retains the actionable server reason', async (error, message) => {+ defHttp.put.mockRejectedValueOnce(error)++ const result = await store.dispatch(+ updateSemanticModel({ ...namespace, semanticModel: 'orders', data: { updates: [] } })+ )+ expect(result.payload).toEqual({ err: true, message })+ expect(store.getState().metalakes.tableLoading).toBe(false)+ expect(defHttp.get).not.toHaveBeenCalled()+ })+ it('reports an empty update response instead of closing the editor', async () => {+ defHttp.put.mockResolvedValue({})++ const result = await store.dispatch(+ updateSemanticModel({ ...namespace, semanticModel: 'orders', data: { updates: [] } })+ )+ expect(result.payload).toEqual({ err: true, message: 'Failed to update the Semantic Model.' })+ expect(defHttp.get).not.toHaveBeenCalled()+ })+})++describe('Semantic Model lists before full schema tree loading', () => {+ it.each([[[]], [['sales_model', 'other_model']]])('preserves an unloaded schema with models %j', async names => {+ const catalogKey = '{{demo}}{{sales}}{{relational}}'+ const schemaNode = { key: schemaKey, node: 'schema', children: [] }+ store.dispatch(setMetalakeTree([{ key: catalogKey, node: 'catalog', children: [schemaNode] }]))+ defHttp.get.mockImplementation(({ url }) =>+ Promise.resolve({+ identifiers: (url.endsWith('/semantic-models')+ ? names+ : url.endsWith('/tables')+ ? ['orders', 'customers']+ : url.endsWith('/views')+ ? ['recent_orders']+ : ['revenue']+ ).map(name => ({ name }))+ })+ )++ await store.dispatch(fetchSemanticModels({ ...namespace, init: true }))+ const unloaded = store.getState().metalakes.metalakeTree[0].children[0]+ expect(unloaded).toEqual(schemaNode)+ expect(unloaded.isLeaf).toBeUndefined()+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(names)++ // TreeComponent marks the node loaded before starting the full children request.+ store.dispatch(setLoadedNodes([schemaKey]))+ await store.dispatch(setIntoTreeNodeWithFetch({ key: schemaKey }))+ const loaded = store.getState().metalakes.metalakeTree[0].children[0]+ expect(loaded.isLeaf).toBe(false)+ expect(loaded.children.map(child => child.name).sort()).toEqual(+ ['orders', 'customers', 'recent_orders', 'revenue', ...names].sort()+ )+ expect(store.getState().metalakes.semanticModelRequests).toEqual({})+ })++ it('keeps a list-only request from modifying an already loaded tree', async () => {+ const schemaNode = { key: schemaKey, node: 'schema', children: [{ name: 'orders', node: 'table' }] }+ store.dispatch(setMetalakeTree([schemaNode]))+ store.dispatch(setLoadedNodes([schemaKey]))+ defHttp.get.mockResolvedValue({ identifiers: [{ name: 'sales_model' }] })+ await store.dispatch(fetchSemanticModels({ ...namespace, init: false }))+ expect(store.getState().metalakes.metalakeTree).toEqual([schemaNode])+ expect(store.getState().metalakes.semanticModels.map(model => model.name)).toEqual(['sales_model'])+ })+})diff --git a/web-v2/web/src/lib/utils/catalogEntity.js b/web-v2/web/src/lib/utils/catalogEntity.jsnew file mode 100644index 0000000000..68b4ec2967--- /dev/null+++ b/web-v2/web/src/lib/utils/catalogEntity.js@@ -0,0 +1,44 @@+/*+ * 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.+ */++/** Identifies catalog details by kind and full namespace, including same-named entities. */+export const catalogEntityKey = params => {+ const kind = [+ 'version',+ 'semanticModel',+ 'view',+ 'function',+ 'table',+ 'fileset',+ 'topic',+ 'model',+ 'schema',+ 'catalog',+ 'metalake'+ ].find(key => params[key] != null)++ return JSON.stringify([+ kind,+ params.metalake,+ params.catalog,+ params.schema,+ kind === 'version' ? params.model : null,+ params[kind]+ ])+}diff --git a/web-v2/web/src/lib/utils/formatVendorJson.js b/web-v2/web/src/lib/utils/formatVendorJson.jsnew file mode 100644index 0000000000..5ff49a4417--- /dev/null+++ b/web-v2/web/src/lib/utils/formatVendorJson.js@@ -0,0 +1,47 @@+/*+ * 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.+ */++// Format tokens rather than parsed values to preserve numbers, key order, and duplicate keys.+export const formatVendorJson = data => {+ try {+ const parsed = JSON.parse(data)+ if (!parsed || typeof parsed !== 'object') return null+ } catch {+ return null+ }+ const tokens = data.match(/"(?:\\.|[^"\\])*"|[{}\[\],:]|[^\s{}\[\],:]+/g)+ let depth = 0+ let formatted = ''+ const newline = () => '\n' + ' '.repeat(depth)+ tokens.forEach((token, index) => {+ if (token === '{' || token === '[') {+ depth+++ formatted += token+ if (!['}', ']'].includes(tokens[index + 1])) formatted += newline()+ } else if (token === '}' || token === ']') {+ depth--+ if (!['{', '['].includes(tokens[index - 1])) formatted += newline()+ formatted += token+ } else if (token === ',') formatted += ',' + newline()+ else if (token === ':') formatted += ': '+ else formatted += token+ })++ return formatted+}diff --git a/web-v2/web/src/lib/utils/formatVendorJson.test.js b/web-v2/web/src/lib/utils/formatVendorJson.test.jsnew file mode 100644index 0000000000..f46c8bf29a--- /dev/null+++ b/web-v2/web/src/lib/utils/formatVendorJson.test.js@@ -0,0 +1,47 @@+/*+ * 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 { expect, it } from 'vitest'+import { formatVendorJson } from './formatVendorJson'++it('preserves large integers, precise decimals, exponents, and negative zero', () => {+ expect(formatVendorJson('{"id":9007199254740993,"threshold":0.10000000000000000001,"large":1e400,"zero":-0}')).toBe(+ '{\n "id": 9007199254740993,\n "threshold": 0.10000000000000000001,\n "large": 1e400,\n "zero": -0\n}'+ )+})++it('preserves string tokens and duplicate keys while indenting nested structures', () => {+ const raw = String.raw`{"2": [], "1": {}, "2": ["escaped \" quote, { } :", {"unicode":"\u0061"}]}`+ const formatted = formatVendorJson(raw)+ expect(formatted).toBe(String.raw`{+ "2": [],+ "1": {},+ "2": [+ "escaped \" quote, { } :",+ {+ "unicode": "\u0061"+ }+ ]+}`)+ expect(JSON.parse(formatted)).toEqual(JSON.parse(raw))+})++it.each(['text', '{ invalid }', '', 'null', '123', '"text"'])('leaves non-object data raw: %s', raw => {+ expect(formatVendorJson(raw)).toBeNull()+})diff --git a/web-v2/web/src/lib/utils/ossiePreview.js b/web-v2/web/src/lib/utils/ossiePreview.jsnew file mode 100644index 0000000000..3fd6857b18--- /dev/null+++ b/web-v2/web/src/lib/utils/ossiePreview.js@@ -0,0 +1,55 @@+/*+ * 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 { load, JSON_SCHEMA } from 'js-yaml'+import { isPlainObject } from 'lodash-es'++/** Reads only the import preview; the original document is sent unchanged for server validation. */+export const parseOssiePreview = (document, format) => {+ if (!document.trim()) throw new Error('The selected file is empty.')+ const model = format === 'json' ? JSON.parse(document) : load(document, { schema: JSON_SCHEMA })+ if (!isPlainObject(model)) throw new Error('The OSSIE document must be an object.')+ if (typeof model.name !== 'string' || !model.name.trim()) throw new Error('The document must declare a model name.')++ if (typeof model.version !== 'string' || !model.version.trim())+ throw new Error('The document must declare a non-empty string version.')++ const count = (values, path) => {+ if (values == null) return 0+ if (!Array.isArray(values)) throw new Error(`${path} must be an array.`)++ return values.length+ }+ const datasets = count(model.datasets, 'datasets')++ const fields = (model.datasets || []).reduce((sum, dataset, index) => {+ if (!isPlainObject(dataset)) throw new Error(`datasets[${index}] must be an object.`)++ return sum + count(dataset.fields, `datasets[${index}].fields`)+ }, 0)++ return {+ name: model.name,+ version: model.version,+ datasets,+ fields,+ relationships: count(model.relationships, 'relationships'),+ metrics: count(model.metrics, 'metrics')+ }+}diff --git a/web-v2/web/src/lib/utils/ossiePreview.test.js b/web-v2/web/src/lib/utils/ossiePreview.test.jsnew file mode 100644index 0000000000..de1f842f44--- /dev/null+++ b/web-v2/web/src/lib/utils/ossiePreview.test.js@@ -0,0 +1,68 @@+/*+ * 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 { describe, expect, it } from 'vitest'+import { parseOssiePreview } from './ossiePreview'++describe('OSSIE preview', () => {+ it.each(['json', 'yaml'])('counts nested fields and metadata in %s', format => {+ const json =+ '{"version":"0.2.0","name":"reporting","datasets":[{"fields":[{},{}]},{"fields":[{}]}],"relationships":[{}],"metrics":[{},{}]}'++ const yaml =+ 'version: 0.2.0\nname: reporting\ndatasets:\n - fields: [{}, {}]\n - fields: [{}]\nrelationships: [{}]\nmetrics: [{}, {}]\n'+ expect(parseOssiePreview(format === 'json' ? json : yaml, format)).toEqual({+ name: 'reporting',+ version: '0.2.0',+ datasets: 2,+ fields: 3,+ relationships: 1,+ metrics: 2+ })+ })+ it('allows optional omitted or null collections without rewriting source text', () => {+ expect(parseOssiePreview('version: 0.2.0\nname: model\nmetrics: null', 'yaml')).toEqual({+ name: 'model',+ version: '0.2.0',+ datasets: 0,+ fields: 0,+ relationships: 0,+ metrics: 0+ })+ })+ it.each([+ ['', 'yaml'],+ ['{ invalid }', 'json'],+ ['name: [', 'yaml'],+ ['[]', 'json'],+ ['name: 42', 'yaml'],+ ['version: 0.2.0\nname: model\ndatasets: bad', 'yaml'],+ ['version: 0.2.0\nname: model\ndatasets: [null]', 'yaml'],+ ['version: 0.2.0\nname: model\ndatasets: [{fields: bad}]', 'yaml'],+ ['version: 0.2.0\nname: model\n---\nname: other', 'yaml']+ ])('rejects unparseable or uncountable documents: %s', (text, format) => {+ expect(() => parseOssiePreview(text, format)).toThrow()+ })+})++it.each([undefined, null, 2, {}, [], '', ' '])('rejects invalid OSSIE version %j', version => {+ expect(() => parseOssiePreview(JSON.stringify({ name: 'model', version }), 'json')).toThrow(+ 'non-empty string version'+ )+})diff --git a/web-v2/web/src/lib/utils/semanticMetadata.js b/web-v2/web/src/lib/utils/semanticMetadata.jsnew file mode 100644index 0000000000..8a41f16b11--- /dev/null+++ b/web-v2/web/src/lib/utils/semanticMetadata.js@@ -0,0 +1,117 @@+/*+ * 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 { cloneDeep, isEqual } from 'lodash-es'++const editableProperties = {+ model: [],+ dataset: ['description'],+ field: ['label', 'description', 'datatype'],+ metric: ['description', 'datatype'],+ relationship: ['from', 'to', 'fromColumns', 'toColumns']+}++const missingMetadataMessage = 'The selected metadata no longer exists. Reload the model and try again.'++/** Finds the selected entity without flattening dataset-scoped field names. */+export const getSemanticMetadataEntity = (definition, target) => {+ const entity =+ target.kind === 'model'+ ? definition+ : target.kind === 'field'+ ? definition?.datasets+ ?.find(dataset => dataset.name === target.datasetName)+ ?.fields?.find(field => field.name === target.name)+ : definition?.[`${target.kind}s`]?.find(item => item.name === target.name)+ if (!entity) throw new Error(missingMetadataMessage)++ return entity+}++/** Supplies form values while keeping the original wire representation separate. */+export const semanticMetadataFormValues = entity => {+ if (!entity) throw new Error(missingMetadataMessage)++ return {+ ...cloneDeep(entity),+ timeDimension: entity.dimension?.isTime ?? undefined,+ dialects: cloneDeep(entity.expression?.dialects || []),+ contextFormat: typeof entity.aiContext === 'string' ? 'text' : 'structured',+ contextText: typeof entity.aiContext === 'string' ? entity.aiContext : '',+ instructions: typeof entity.aiContext === 'string' ? entity.aiContext : entity.aiContext?.instructions || '',+ synonyms: cloneDeep(entity.aiContext?.synonyms || []),+ examples: cloneDeep(entity.aiContext?.examples || [])+ }+}++/** Applies only edited form values, preserving every other entity and extension in the definition. */+export const updateSemanticMetadata = (definition, target, values) => {+ const updated = cloneDeep(definition)+ const entity = getSemanticMetadataEntity(updated, target)+ const initial = semanticMetadataFormValues(entity)+ for (const key of editableProperties[target.kind]) {+ const value = key === 'datatype' && values[key] === '' ? null : values[key]+ if (!isEqual(initial[key], value)) {+ if (['label', 'description'].includes(key) && (value == null || !value.trim())) delete entity[key]+ else entity[key] = value ?? null+ }+ }+ if (target.kind === 'field' && initial.timeDimension !== values.timeDimension) {+ const dimension = { ...entity.dimension }+ if (values.timeDimension == null) delete dimension.isTime+ else dimension.isTime = values.timeDimension+ if (Object.keys(dimension).length) entity.dimension = dimension+ else delete entity.dimension+ }+ if (['field', 'metric'].includes(target.kind) && !isEqual(initial.dialects, values.dialects)) {+ entity.expression = { ...entity.expression, dialects: cloneDeep(values.dialects) }+ }++ if (values.contextFormat === 'text') {+ if (initial.contextFormat !== 'text' || initial.contextText !== values.contextText) {+ // Existing structured guidance stays structured so its extra keys cannot be discarded.+ if (entity.aiContext && typeof entity.aiContext === 'object') {+ if (values.contextText?.trim()) entity.aiContext.instructions = values.contextText+ else delete entity.aiContext.instructions+ if (!Object.keys(entity.aiContext).length) delete entity.aiContext+ } else {+ if (values.contextText?.trim()) entity.aiContext = values.contextText+ else delete entity.aiContext+ }+ }+ } else {+ const changedFormat = initial.contextFormat !== values.contextFormat++ const changedKeys = ['instructions', 'synonyms', 'examples'].filter(+ key => changedFormat || !isEqual(initial[key], values[key])+ )+ if (changedKeys.length) {+ entity.aiContext = typeof entity.aiContext === 'object' && entity.aiContext ? entity.aiContext : {}+ for (const key of changedKeys) entity.aiContext[key] = cloneDeep(values[key])+ for (const key of ['instructions', 'synonyms', 'examples']) {+ const value = entity.aiContext[key]+ if (value == null || (typeof value === 'string' ? !value.trim() : value.length === 0))+ delete entity.aiContext[key]+ }+ if (!Object.keys(entity.aiContext).length) delete entity.aiContext+ }+ }++ return updated+}diff --git a/web-v2/web/src/lib/utils/semanticMetadata.test.js b/web-v2/web/src/lib/utils/semanticMetadata.test.jsnew file mode 100644index 0000000000..29f66546cd--- /dev/null+++ b/web-v2/web/src/lib/utils/semanticMetadata.test.js@@ -0,0 +1,227 @@+/*+ * 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 { describe, expect, it } from 'vitest'+import { getSemanticMetadataEntity, semanticMetadataFormValues, updateSemanticMetadata } from './semanticMetadata'++const metadata = {+ aiContext: { instructions: 'Original', synonyms: ['one'], examples: ['question'], extra: { keep: true } },+ customExtensions: [{ vendorName: 'vendor', data: 'keep exactly' }]+}++const expression = {+ dialects: [+ { dialect: 'ANSI_SQL', expression: '-- comment\nSUM(amount)' },+ { dialect: 'SPARK_SQL', expression: 'SUM(amount)' }+ ]+}++const makeDefinition = () => ({+ ...structuredClone(metadata),+ datasets: [+ {+ name: 'orders',+ description: 'Orders',+ ...structuredClone(metadata),+ source: { namespace: ['sales', 'mart'], name: 'orders' },+ primaryKey: ['id'],+ uniqueKeys: [['amount']],+ fields: [{ name: 'amount', label: 'Amount', expression, ...structuredClone(metadata) }]+ },+ { name: 'other', source: { namespace: ['sales', 'mart'], name: 'other' }, fields: [{ name: 'amount', expression }] }+ ],+ relationships: [+ {+ name: 'join',+ from: 'orders',+ to: 'other',+ fromColumns: ['amount'],+ toColumns: ['amount'],+ ...structuredClone(metadata)+ }+ ],+ metrics: [{ name: 'revenue', description: 'Revenue', expression, ...structuredClone(metadata) }]+})++const targets = [+ { kind: 'model' },+ { kind: 'dataset', name: 'orders' },+ { kind: 'field', name: 'amount', datasetName: 'orders' },+ { kind: 'relationship', name: 'join' },+ { kind: 'metric', name: 'revenue' }+]++describe('focused metadata updates', () => {+ it.each(targets)('preserves every untouched value when editing $kind guidance', target => {+ const definition = makeDefinition()+ const original = structuredClone(definition)+ const initial = semanticMetadataFormValues(getSemanticMetadataEntity(definition, target))+ const updated = updateSemanticMetadata(definition, target, { ...initial, instructions: 'New guidance' })+ const expected = structuredClone(definition)+ getSemanticMetadataEntity(expected, target).aiContext.instructions = 'New guidance'+ expect(updated).toEqual(expected)+ expect(definition).toEqual(original)+ expect(updateSemanticMetadata(definition, target, initial)).toEqual(definition)+ })++ it('edits only the selected field even when another dataset has the same field name', () => {+ const definition = makeDefinition()+ const target = targets[2]+ const values = semanticMetadataFormValues(getSemanticMetadataEntity(definition, target))+ values.label = 'Order amount'+ values.description = 'Updated description'+ values.dialects[0].expression = '-- new comment\nSUM(amount * 2)'+ values.examples.push('Another question')+ const updated = updateSemanticMetadata(definition, target, values)+ expect(updated.datasets[1]).toEqual(definition.datasets[1])+ expect(updated.datasets[0].fields[0]).toEqual({+ ...definition.datasets[0].fields[0],+ label: values.label,+ description: values.description,+ expression: { dialects: values.dialects },+ aiContext: { ...metadata.aiContext, examples: values.examples }+ })+ expect(definition.datasets[0].fields[0].expression.dialects[0].expression).toBe('-- comment\nSUM(amount)')+ })++ it('supports text guidance and conversion to structured guidance without losing the text', () => {+ const definition = makeDefinition()+ definition.aiContext = 'Text guidance'+ const values = semanticMetadataFormValues(definition)+ expect(updateSemanticMetadata(definition, targets[0], { ...values, contextText: 'Updated' }).aiContext).toBe(+ 'Updated'+ )+ expect(+ updateSemanticMetadata(definition, targets[0], { ...values, contextFormat: 'structured' }).aiContext+ ).toEqual({ instructions: 'Text guidance' })+ })++ it.each([targets[2], targets[4]])('clears an optional $kind data type without changing other metadata', target => {+ for (const cleared of ['', undefined, null]) {+ const definition = makeDefinition()+ const entity = getSemanticMetadataEntity(definition, target)+ entity.datatype = 'Decimal'+ const values = { ...semanticMetadataFormValues(entity), datatype: cleared }+ const expected = structuredClone(definition)+ getSemanticMetadataEntity(expected, target).datatype = null+ expect(updateSemanticMetadata(definition, target, values)).toEqual(expected)+ expect(entity.datatype).toBe('Decimal')+ }+ })++ it('adds context only when the guidance is edited', () => {+ const definition = makeDefinition()+ delete definition.aiContext+ const values = semanticMetadataFormValues(definition)+ expect(updateSemanticMetadata(definition, targets[0], values)).not.toHaveProperty('aiContext')+ expect(updateSemanticMetadata(definition, targets[0], { ...values, instructions: 'New' }).aiContext).toEqual({+ instructions: 'New'+ })+ })++ it('preserves additional context keys even if a text edit is applied to structured context', () => {+ const definition = makeDefinition()++ const updated = updateSemanticMetadata(definition, targets[0], {+ ...semanticMetadataFormValues(definition),+ contextFormat: 'text',+ contextText: 'New'+ })+ expect(updated.aiContext).toEqual({ ...metadata.aiContext, instructions: 'New' })+ })++ it('rejects a missing target instead of updating another entity', () => {+ expect(() => updateSemanticMetadata(makeDefinition(), { kind: 'metric', name: 'missing' }, {})).toThrow(+ 'no longer exists'+ )+ })++ it.each([true, false, undefined])('edits or clears the time dimension without losing other metadata: %s', value => {+ const definition = makeDefinition()+ const target = targets[2]+ const field = getSemanticMetadataEntity(definition, target)+ field.dimension = { isTime: !value, extra: 'preserve' }+ const initial = semanticMetadataFormValues(field)++ const updated = getSemanticMetadataEntity(+ updateSemanticMetadata(definition, target, { ...initial, timeDimension: value }),+ target+ )+ expect(updated.dimension).toEqual(value == null ? { extra: 'preserve' } : { isTime: value, extra: 'preserve' })+ expect(updated.expression).toEqual(field.expression)+ })++ it('leaves an absent dimension alone and removes an explicitly cleared dimension', () => {+ const definition = makeDefinition()+ const target = targets[2]+ const field = getSemanticMetadataEntity(definition, target)+ expect(updateSemanticMetadata(definition, target, semanticMetadataFormValues(field))).toEqual(definition)+ field.dimension = { isTime: true }++ const updated = updateSemanticMetadata(definition, target, {+ ...semanticMetadataFormValues(field),+ timeDimension: undefined+ })+ expect(getSemanticMetadataEntity(updated, target)).not.toHaveProperty('dimension')+ })++ it.each(['', ' '])('removes cleared optional text metadata: %j', blank => {+ const definition = makeDefinition()+ const target = targets[2]+ const field = getSemanticMetadataEntity(definition, target)+ field.description = 'Description'+ field.aiContext = 'Guidance'+ const values = { ...semanticMetadataFormValues(field), label: blank, description: blank, contextText: blank }+ const updated = getSemanticMetadataEntity(updateSemanticMetadata(definition, target, values), target)+ expect(updated).not.toHaveProperty('label')+ expect(updated).not.toHaveProperty('description')+ expect(updated).not.toHaveProperty('aiContext')+ expect(updated.customExtensions).toEqual(field.customExtensions)+ })++ it.each([true, false])('clears structured guidance while preserving additional keys: %s', extra => {+ const definition = makeDefinition()+ definition.aiContext = {+ instructions: 'Guidance',+ synonyms: ['a'],+ examples: ['b'],+ ...(extra ? { vendor: { keep: true } } : {})+ }++ const updated = updateSemanticMetadata(definition, targets[0], {+ ...semanticMetadataFormValues(definition),+ instructions: '',+ synonyms: [],+ examples: []+ })+ if (extra) expect(updated.aiContext).toEqual({ vendor: { keep: true } })+ else expect(updated).not.toHaveProperty('aiContext')+ })++ it('removes structured context when only unchanged empty lists remain after clearing instructions', () => {+ const definition = makeDefinition()+ definition.aiContext = { instructions: 'Guidance', synonyms: [], examples: [] }++ const updated = updateSemanticMetadata(definition, targets[0], {+ ...semanticMetadataFormValues(definition),+ instructions: ''+ })+ expect(updated).not.toHaveProperty('aiContext')+ })+})diff --git a/web-v2/web/src/lib/utils/semanticModel.js b/web-v2/web/src/lib/utils/semanticModel.jsnew file mode 100644index 0000000000..ce8145873b--- /dev/null+++ b/web-v2/web/src/lib/utils/semanticModel.js@@ -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.+ */++import { isEqual, isPlainObject } from 'lodash-es'++const SOURCE_NAMESPACE_LENGTH = 2+const DEFINITION_INDENT = 2++// Wire names accepted by SemanticDTOUtils.DataTypeDeserializer.+export const semanticDataTypes = [+ 'String',+ 'Integer',+ 'Decimal',+ 'Float',+ 'Boolean',+ 'Date',+ 'Time',+ 'DateTime',+ 'DateTimeTz',+ 'Opaque'+]++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 validateStringArray = (values, path, errors, nonBlank = true) => {+ if (values == null) return++ if (+ !Array.isArray(values) ||+ !values.every(value => (nonBlank ? isNonBlankString(value) : typeof value === 'string'))+ ) {+ errors.push(`${path} must be an array of ${nonBlank ? 'non-empty ' : ''}strings.`)+ }+}++const validateExpression = (expression, path, errors) => {+ const dialects = expression?.dialects+ if (!isPlainObject(expression) || !Array.isArray(dialects) || !dialects.length) {+ errors.push(`${path}.expression must have non-empty dialects.`)++ return+ }++ dialects.forEach((dialect, index) => {+ if (!isPlainObject(dialect) || !isNonBlankString(dialect.dialect) || !isNonBlankString(dialect.expression)) {+ errors.push(`${path}.expression.dialects[${index}] must have a non-empty dialect and expression.`)+ }+ })++ const duplicates = duplicatesOf(dialects.map(dialect => dialect?.dialect).filter(isNonBlankString))+ if (duplicates.length) {+ errors.push(`${path}.expression must have unique dialect names: ${duplicates.join(', ')}.`)+ }+}++const validateMetadata = (entity, path, errors) => {+ const { customExtensions, aiContext } = entity+ if (customExtensions != null) {+ if (!Array.isArray(customExtensions)) {+ errors.push(`${path}.customExtensions must be an array.`)+ } else {+ customExtensions.forEach((extension, index) => {+ if (+ !isPlainObject(extension) ||+ typeof extension.vendorName !== 'string' ||+ typeof extension.data !== 'string'+ ) {+ errors.push(`${path}.customExtensions[${index}] must have vendorName and data strings.`)+ }+ })+ }+ }++ if (aiContext != null && typeof aiContext !== 'string') {+ if (!isPlainObject(aiContext)) {+ errors.push(`${path}.aiContext must be a string or object.`)+ } else {+ validateStringArray(aiContext.synonyms, `${path}.aiContext.synonyms`, errors, false)+ validateStringArray(aiContext.examples, `${path}.aiContext.examples`, errors, false)+ }+ }+}++const validateDataType = (datatype, path, errors) => {+ if (datatype != null && !semanticDataTypes.includes(datatype)) {+ errors.push(`${path}.datatype must be null or one of: ${semanticDataTypes.join(', ')}.`)+ }+}++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)+ validateMetadata(dataset, `datasets[${index}]`, errors)+ validateStringArray(dataset.primaryKey, `datasets[${index}].primaryKey`, errors)++ if (dataset.uniqueKeys != null) {+ if (!Array.isArray(dataset.uniqueKeys)) {+ errors.push(`datasets[${index}].uniqueKeys must be an array.`)+ } else {+ dataset.uniqueKeys.forEach((key, keyIndex) => {+ const path = `datasets[${index}].uniqueKeys[${keyIndex}]`+ if (!Array.isArray(key) || !key.length) {+ errors.push(`${path} must be a non-empty array.`)+ } else {+ validateStringArray(key, path, errors)+ }+ })+ }+ }++ const fields = dataset.fields+ if (fields != null && !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.`)++ return+ }+ const path = `datasets[${index}].fields[${fieldIndex}]`+ validateExpression(field.expression, path, errors)+ validateDataType(field.datatype, path, errors)+ validateMetadata(field, path, errors)+ })++ 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+ validateMetadata(relationship, `relationships[${index}]`, errors)+ ;[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.`)+ }+ validateStringArray(fromColumns, `relationships[${index}].fromColumns`, errors)+ validateStringArray(toColumns, `relationships[${index}].toColumns`, errors)+ })++ 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.`)++ return+ }+ validateExpression(metric.expression, `metrics[${index}]`, errors)+ validateDataType(metric.datatype, `metrics[${index}]`, errors)+ validateMetadata(metric, `metrics[${index}]`, errors)+ })++ 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 => {+ const errors = []++ if (!isPlainObject(definition)) {+ return ['The definition must be a JSON object.']+ }++ const { datasets, relationships, metrics } = definition++ if (!Array.isArray(datasets) || !datasets.length) {+ return ['The definition must declare at least one dataset.']+ }++ validateDatasets(datasets, errors)+ validateMetadata(definition, 'definition', errors)++ const datasetNames = new Set(datasets.map(dataset => dataset?.name).filter(isNonBlankString))++ if (relationships != null) {+ if (Array.isArray(relationships)) {+ validateRelationships(relationships, datasetNames, errors)+ } else {+ errors.push('The definition must declare relationships as an array.')+ }+ }++ if (metrics != null) {+ if (Array.isArray(metrics)) {+ validateMetrics(metrics, errors)+ } else {+ errors.push('The definition must declare metrics as an array.')+ }+ }++ return errors+}++/**+ * Parses the definition authored in the dialog and validates it.+ *+ * @param {string} text The raw JSON text.+ * @returns {{ definition: object|null, errors: string[] }} The definition, or the problems found.+ */+export const parseSemanticModelDefinition = text => {+ if (!isNonBlankString(text)) {+ return { definition: null, errors: ['The definition is required.'] }+ }++ let parsed+ try {+ parsed = JSON.parse(text)+ } catch (err) {+ return { definition: null, errors: [`The definition is not valid JSON: ${err.message}`] }+ }++ const errors = validateSemanticModelDefinition(parsed)++ return errors.length ? { definition: null, errors } : { definition: parsed, errors: [] }+}++/**+ * Renders a definition for the JSON editor.+ *+ * @param {object|null|undefined} definition The definition to render.+ * @returns {string} The pretty-printed definition, or an empty string when there is none.+ */+export const formatSemanticModelDefinition = definition => {+ if (!definition) {+ return ''+ }++ return JSON.stringify(definition, null, DEFINITION_INDENT)+}++/**+ * Builds the atomic alter batch from what actually changed, so an unchanged definition is not+ * revalidated against its sources.+ *+ * @param {object} originalData The loaded semantic model.+ * @param {object} newData The edited semantic model.+ * @returns {object[]} The ordered updates, empty when nothing changed.+ */+export const genSemanticModelUpdates = (originalData, newData) => {+ const updates = []++ if (originalData.name !== newData.name) {+ updates.push({ '@type': 'rename', newName: newData.name })+ }++ const originalComment = originalData.comment || ''+ const newComment = newData.comment || ''++ if (originalComment !== newComment) {+ updates.push({ '@type': 'updateComment', newComment: newComment === '' ? null : newComment })+ }++ const originalProperties = originalData.properties || {}+ const newProperties = newData.properties || {}++ for (const key of Object.keys(originalProperties)) {+ if (!Object.hasOwn(newProperties, key)) {+ updates.push({ '@type': 'removeProperty', property: key })+ }+ }++ for (const key of Object.keys(newProperties)) {+ if (originalProperties[key] !== newProperties[key]) {+ updates.push({ '@type': 'setProperty', property: key, value: newProperties[key] })+ }+ }++ if (newData.definition && !isEqual(originalData.definition, newData.definition)) {+ updates.push({ '@type': 'replaceDefinition', definition: newData.definition })+ }++ return updates+}++/** Returns the tree key for a Semantic Model, distinct from other schema entities. */+export const semanticModelNodeKey = ({ metalake, catalog, schema, semanticModel }) =>+ `{{${metalake}}}{{${catalog}}}{{relational}}{{${schema}}}{{semanticModel}}{{${semanticModel}}}`++/** Extracts API validation errors, including text responses from OSSIE downloads. */+export const semanticModelErrorMessage = (error, fallback) => {+ let data = error?.response?.data+ if (typeof data === 'string') {+ try {+ data = JSON.parse(data)+ } catch {+ data = null+ }+ }++ return data?.error?.message || data?.message || error?.message || fallback+}diff --git a/web-v2/web/src/lib/utils/semanticModel.test.js b/web-v2/web/src/lib/utils/semanticModel.test.jsnew file mode 100644index 0000000000..3b39d35bbd--- /dev/null+++ b/web-v2/web/src/lib/utils/semanticModel.test.js@@ -0,0 +1,486 @@+/*+ * 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 { describe, expect, test } from 'vitest'+import {+ formatSemanticModelDefinition,+ genSemanticModelUpdates,+ semanticModelErrorMessage,+ parseSemanticModelDefinition,+ validateSemanticModelDefinition+} from './semanticModel'++const orders = {+ name: 'orders',+ source: { namespace: ['sales', 'mart'], name: 'orders' },+ fields: [{ name: 'order_id', expression: { dialects: [{ dialect: 'ANSI_SQL', expression: 'order_id' }] } }]+}++const customers = {+ name: 'customers',+ source: { namespace: ['sales', 'mart'], name: 'customers' }+}++const definitionOf = overrides => ({ datasets: [orders], ...overrides })++describe('validateSemanticModelDefinition', () => {+ test('accepts a minimal definition with a single dataset', () => {+ expect(validateSemanticModelDefinition(definitionOf())).toEqual([])+ })++ test('rejects a definition that is not an object', () => {+ expect(validateSemanticModelDefinition([orders])).toEqual(['The definition must be a JSON object.'])+ })++ test('rejects a definition without datasets', () => {+ expect(validateSemanticModelDefinition({})).toEqual(['The definition must declare at least one dataset.'])+ })++ test('rejects an empty datasets array', () => {+ expect(validateSemanticModelDefinition({ datasets: [] })).toEqual([+ 'The definition must declare at least one dataset.'+ ])+ })++ test('rejects a dataset without a name', () => {+ const errors = validateSemanticModelDefinition({ datasets: [{ source: orders.source }] })++ expect(errors).toEqual(['datasets[0] must have a non-empty name.'])+ })++ test('rejects a dataset whose source namespace is not catalog.schema', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [{ name: 'orders', source: { namespace: ['sales'], name: 'orders' } }]+ })++ expect(errors).toEqual(['Dataset "orders" must have a source namespace of exactly [catalog, schema].'])+ })++ test('rejects a dataset source without a name', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [{ name: 'orders', source: { namespace: ['sales', 'mart'] } }]+ })++ expect(errors).toEqual(['Dataset "orders" must have a source with a non-empty name.'])+ })++ test('rejects duplicate dataset names', () => {+ const errors = validateSemanticModelDefinition({ datasets: [orders, orders] })++ expect(errors).toEqual(['Dataset names must be unique within the semantic model: orders.'])+ })++ test.each([null, 'field', {}, { name: '' }, { name: ' ' }, { name: 42 }])('rejects an invalid field %j', field => {+ const errors = validateSemanticModelDefinition({ datasets: [{ ...orders, fields: [field] }] })+ expect(errors).toEqual(['datasets[0].fields[0] must have a non-empty name.'])+ })++ test('reports invalid field names without calling them duplicates', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [{ ...orders, fields: [{}, {}, { name: '' }, { name: '' }, ...orders.fields, ...orders.fields] }]+ })+ expect(errors).toEqual([+ ...[0, 1, 2, 3].map(index => `datasets[0].fields[${index}] must have a non-empty name.`),+ 'Field names must be unique within dataset "orders": order_id.'+ ])+ })++ test('rejects duplicate field names within one dataset', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [{ ...orders, fields: [...orders.fields, ...orders.fields] }]+ })++ expect(errors).toEqual(['Field names must be unique within dataset "orders": order_id.'])+ })++ test('accepts the same field name in two different datasets', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [orders, { ...customers, fields: orders.fields }]+ })++ expect(errors).toEqual([])+ })++ test('rejects a relationship endpoint that is not a declared dataset', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [orders],+ relationships: [+ { name: 'orders_customers', from: 'orders', to: 'customers', fromColumns: ['a'], toColumns: ['b'] }+ ]+ })++ expect(errors).toEqual(['Relationship "orders_customers" references an unknown dataset "customers".'])+ })++ test('rejects a relationship whose column counts do not match', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [orders, customers],+ relationships: [+ { name: 'orders_customers', from: 'orders', to: 'customers', fromColumns: ['a'], toColumns: ['b', 'c'] }+ ]+ })++ expect(errors).toEqual(['Relationship "orders_customers" must have the same number of fromColumns and toColumns.'])+ })++ test('rejects a relationship with empty columns', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [orders, customers],+ relationships: [{ name: 'orders_customers', from: 'orders', to: 'customers', fromColumns: [], toColumns: [] }]+ })++ expect(errors).toEqual(['Relationship "orders_customers" must have non-empty fromColumns and toColumns.'])+ })++ test('rejects duplicate relationship names', () => {+ const relationship = {+ name: 'orders_customers',+ from: 'orders',+ to: 'customers',+ fromColumns: ['customer_id'],+ toColumns: ['id']+ }++ const errors = validateSemanticModelDefinition({+ datasets: [orders, customers],+ relationships: [relationship, relationship]+ })++ expect(errors).toEqual(['Relationship names must be unique within the semantic model: orders_customers.'])+ })++ test('rejects duplicate metric names', () => {+ const metric = { name: 'revenue', expression: { dialects: [{ dialect: 'ANSI_SQL', expression: 'sum(amount)' }] } }+ const errors = validateSemanticModelDefinition({ datasets: [orders], metrics: [metric, metric] })++ expect(errors).toEqual(['Metric names must be unique within the semantic model: revenue.'])+ })++ test('reports every problem it finds rather than only the first', () => {+ const errors = validateSemanticModelDefinition({+ datasets: [{ source: orders.source }, { name: 'customers' }]+ })++ expect(errors).toEqual([+ 'datasets[0] must have a non-empty name.',+ 'Dataset "customers" must have a source with a namespace and a name.'+ ])+ })+})++describe('nested Semantic Model contract validation', () => {+ const expression = { dialects: [{ dialect: 'ANSI_SQL', expression: 'amount' }] }+ const relationship = { name: 'self', from: 'orders', to: 'orders', fromColumns: ['id'], toColumns: ['id'] }++ test.each(['field', 'metric'])('accepts only the server-supported optional %s data types', kind => {+ const withType = datatype =>+ kind === 'field'+ ? { datasets: [{ ...orders, fields: [{ ...orders.fields[0], datatype }] }] }+ : definitionOf({ metrics: [{ name: 'revenue', expression, datatype }] })+ for (const datatype of [+ undefined,+ null,+ 'String',+ 'Integer',+ 'Decimal',+ 'Float',+ 'Boolean',+ 'Date',+ 'Time',+ 'DateTime',+ 'DateTimeTz',+ 'Opaque'+ ]) {+ expect(validateSemanticModelDefinition(withType(datatype))).toEqual([])+ }+ for (const datatype of ['', ' ', 'decimal', 'Decimal(10,2)', 'Unsupported', 42, {}, []]) {+ const { definition, errors } = parseSemanticModelDefinition(JSON.stringify(withType(datatype)))+ expect(definition).toBeNull()+ expect(errors).toHaveLength(1)+ expect(errors[0]).toContain(kind === 'field' ? 'datasets[0].fields[0].datatype' : 'metrics[0].datatype')+ }+ })++ test.each([+ undefined,+ null,+ {},+ { dialects: [] },+ { dialects: [null] },+ { dialects: [{ dialect: '', expression: 'amount' }] },+ { dialects: [{ dialect: 'ANSI_SQL', expression: '' }] },+ {+ dialects: [+ { dialect: 'ANSI_SQL', expression: 'amount' },+ { dialect: 'ANSI_SQL', expression: 'amount + 1' }+ ]+ }+ ])('rejects malformed field and metric expressions: %j', expression => {+ for (const definition of [+ { datasets: [{ ...orders, fields: [{ name: 'amount', expression }] }] },+ definitionOf({ metrics: [{ name: 'revenue', expression }] })+ ]) {+ expect(validateSemanticModelDefinition(definition).join(' ')).toMatch(/expression|dialect/)+ }+ })++ test.each(['', ' ', null, 42])('rejects invalid relationship column %j on either side', column => {+ for (const side of ['fromColumns', 'toColumns']) {+ const errors = validateSemanticModelDefinition(+ definitionOf({ relationships: [{ ...relationship, [side]: [column] }] })+ )+ expect(errors.join(' ')).toContain(side)+ }+ })++ test.each([+ { primaryKey: [null] },+ { primaryKey: [''] },+ { primaryKey: 'id' },+ { uniqueKeys: [null] },+ { uniqueKeys: [[]] },+ { uniqueKeys: [['']] },+ { uniqueKeys: [['id', null]] },+ { uniqueKeys: 'id' }+ ])('rejects malformed dataset keys: %j', keys => {+ expect(validateSemanticModelDefinition({ datasets: [{ ...orders, ...keys }] }).join(' ')).toMatch(+ /primaryKey|uniqueKeys/+ )+ })++ const withMetadata = (level, metadata) => {+ if (level === 'model') return definitionOf(metadata)+ if (level === 'dataset') return { datasets: [{ ...orders, ...metadata }] }+ if (level === 'field') return { datasets: [{ ...orders, fields: [{ name: 'amount', expression, ...metadata }] }] }+ if (level === 'relationship') return definitionOf({ relationships: [{ ...relationship, ...metadata }] })++ return definitionOf({ metrics: [{ name: 'revenue', expression, ...metadata }] })+ }++ test.each(['model', 'dataset', 'field', 'relationship', 'metric'])(+ 'checks extensions and AI context at %s level',+ level => {+ for (const metadata of [+ { customExtensions: {} },+ { customExtensions: [null] },+ { customExtensions: [{ vendorName: 'vendor' }] },+ { customExtensions: [{ data: '{}' }] },+ { aiContext: [] },+ { aiContext: 42 },+ { aiContext: { synonyms: [null] } },+ { aiContext: { examples: [null] } }+ ]) {+ expect(validateSemanticModelDefinition(withMetadata(level, metadata)).length).toBeGreaterThan(0)+ }+ for (const aiContext of [+ null,+ '',+ {},+ { instructions: 'guide', synonyms: [''], examples: [], extra: { a: 1 } }+ ]) {+ expect(+ validateSemanticModelDefinition(+ withMetadata(level, {+ aiContext,+ customExtensions: [{ vendorName: '', data: '' }]+ })+ )+ ).toEqual([])+ }+ }+ )++ test('allows optional null arrays and valid nested structures', () => {+ expect(+ validateSemanticModelDefinition({+ datasets: [{ ...orders, fields: null, primaryKey: null, uniqueKeys: null }],+ relationships: null,+ metrics: null,+ customExtensions: null+ })+ ).toEqual([])+ expect(+ validateSemanticModelDefinition({+ datasets: [{ ...orders, primaryKey: ['order_id'], uniqueKeys: [['amount'], ['id', 'region']] }],+ relationships: [relationship],+ metrics: [+ {+ name: 'revenue',+ expression: { dialects: [...expression.dialects, { dialect: 'SPARK_SQL', expression: 'sum(amount)' }] }+ }+ ]+ })+ ).toEqual([])+ })+})++describe('parseSemanticModelDefinition', () => {+ test('returns the parsed definition when the text is valid', () => {+ const { definition, errors } = parseSemanticModelDefinition(JSON.stringify(definitionOf()))++ expect(errors).toEqual([])+ expect(definition).toEqual(definitionOf())+ })++ test('reports a parse failure without throwing', () => {+ const { definition, errors } = parseSemanticModelDefinition('{ not json }')++ expect(definition).toBeNull()+ expect(errors).toHaveLength(1)+ expect(errors[0]).toMatch(/^The definition is not valid JSON/)+ })++ test('reports a blank definition', () => {+ expect(parseSemanticModelDefinition(' ')).toEqual({+ definition: null,+ errors: ['The definition is required.']+ })+ })++ test('reports contract errors for well-formed JSON', () => {+ const { definition, errors } = parseSemanticModelDefinition('{"datasets": []}')++ expect(definition).toBeNull()+ expect(errors).toEqual(['The definition must declare at least one dataset.'])+ })+})++describe('formatSemanticModelDefinition', () => {+ test('pretty-prints a definition', () => {+ expect(formatSemanticModelDefinition({ datasets: [] })).toBe('{\n "datasets": []\n}')+ })++ test('returns an empty string for a missing definition', () => {+ expect(formatSemanticModelDefinition(null)).toBe('')+ })+})++describe('genSemanticModelUpdates', () => {+ const original = {+ name: 'sales_model',+ comment: 'Governed sales definitions',+ properties: { domain: 'sales' },+ definition: definitionOf()+ }++ test('returns no updates when nothing changed', () => {+ expect(genSemanticModelUpdates(original, { ...original })).toEqual([])+ })++ test('emits a rename when the name changed', () => {+ expect(genSemanticModelUpdates(original, { ...original, name: 'sales_model_v2' })).toEqual([+ { '@type': 'rename', newName: 'sales_model_v2' }+ ])+ })++ test('emits an updateComment when the comment changed', () => {+ expect(genSemanticModelUpdates(original, { ...original, comment: 'Updated' })).toEqual([+ { '@type': 'updateComment', newComment: 'Updated' }+ ])+ })++ test('clears the comment with a null newComment', () => {+ expect(genSemanticModelUpdates(original, { ...original, comment: '' })).toEqual([+ { '@type': 'updateComment', newComment: null }+ ])+ })++ test('emits removeProperty before setProperty', () => {+ const updates = genSemanticModelUpdates(original, { ...original, properties: { region: 'emea' } })++ expect(updates).toEqual([+ { '@type': 'removeProperty', property: 'domain' },+ { '@type': 'setProperty', property: 'region', value: 'emea' }+ ])+ })++ test.each(['constructor', 'toString', '__proto__'])('removes the own property %s', key => {+ expect(+ genSemanticModelUpdates({ ...original, properties: { [key]: 'value' } }, { ...original, properties: {} })+ ).toEqual([{ '@type': 'removeProperty', property: key }])+ })++ test('ignores inherited properties', () => {+ expect(+ genSemanticModelUpdates(+ { ...original, properties: Object.create({ old: 'value' }) },+ { ...original, properties: Object.create({ next: 'value' }) }+ )+ ).toEqual([])+ })++ test('emits setProperty only for values that actually changed', () => {+ const updates = genSemanticModelUpdates(original, {+ ...original,+ properties: { domain: 'sales', region: 'emea' }+ })++ expect(updates).toEqual([{ '@type': 'setProperty', property: 'region', value: 'emea' }])+ })++ test('emits replaceDefinition when the definition changed', () => {+ const next = definitionOf({ datasets: [orders, customers] })+ const updates = genSemanticModelUpdates(original, { ...original, definition: next })++ expect(updates).toEqual([{ '@type': 'replaceDefinition', definition: next }])+ })++ test('does not emit replaceDefinition when the definition is deeply equal but not identical', () => {+ const updates = genSemanticModelUpdates(original, {+ ...original,+ definition: JSON.parse(JSON.stringify(original.definition))+ })++ expect(updates).toEqual([])+ })++ test('orders a full batch as rename, comment, properties, then definition', () => {+ const next = definitionOf({ datasets: [orders, customers] })++ const updates = genSemanticModelUpdates(original, {+ name: 'sales_model_v2',+ comment: 'Updated',+ properties: { region: 'emea' },+ definition: next+ })++ expect(updates.map(update => update['@type'])).toEqual([+ 'rename',+ 'updateComment',+ 'removeProperty',+ 'setProperty',+ 'replaceDefinition'+ ])+ })+})++describe('semanticModelErrorMessage', () => {+ test.each([+ [{ response: { data: { error: { message: 'Invalid source' } } } }, 'Invalid source'],+ [{ response: { data: '{"message":"Model not found"}' } }, 'Model not found'],+ [{ message: 'Network Error' }, 'Network Error'],+ [+ { response: { data: '<html>Proxy error</html>' }, message: 'Request failed with status code 502' },+ 'Request failed with status code 502'+ ],+ [null, 'Import failed']+ ])('preserves a readable API or transport error', (error, message) => {+ expect(semanticModelErrorMessage(error, 'Import failed')).toBe(message)+ })+})diff --git a/web-v2/web/vitest.config.js b/web-v2/web/vitest.config.jsindex 4c0a75fde3..0b8f9aa6d6 100644--- a/web-v2/web/vitest.config.js+++ b/web-v2/web/vitest.config.js@@ -21,6 +21,7 @@ import { defineConfig } from 'vitest/config'import { resolve } from 'path'export default defineConfig({+ esbuild: { loader: 'tsx', include: /src\/.*\.[jt]sx?$/, exclude: [], jsx: 'automatic' },test: {globals: true,environment: 'jsdom',@@ -44,6 +45,8 @@ export default defineConfig({}},resolve: {+ // Some browser dependencies publish only a module entry, without a main entry.+ mainFields: ['module', 'main'],alias: {'@': resolve(__dirname, './src')}