diff --git a/packages/kumo-api/kumoapi/data_source.py b/packages/kumo-api/kumoapi/data_source.py index 0146447d2..9e21532ec 100644 --- a/packages/kumo-api/kumoapi/data_source.py +++ b/packages/kumo-api/kumoapi/data_source.py @@ -1299,6 +1299,18 @@ class CreateConnectorArgs: description: str = '' +@dataclass(config=_FORBID_EXTRA_CONFIG) +class CopyConnectorArgs: + r"""Copy one connector's configuration and identity into a project. + + ``name`` and ``description`` default to the source connector's values. + The identity must be assigned to the target project's group. + """ + target_project_id: ProjectID + name: Optional[str] = None + description: Optional[str] = None + + @dataclass(config=_FORBID_EXTRA_CONFIG) class UpdateConnectorMetadataArgs: name: Optional[str] = None diff --git a/rest/driver/connector_api_driver.py b/rest/driver/connector_api_driver.py index 9636d43d2..592b76ae1 100644 --- a/rest/driver/connector_api_driver.py +++ b/rest/driver/connector_api_driver.py @@ -101,6 +101,7 @@ TableName, ) from statedb.db.auth import AuthPrincipal +from statedb.db.identities import normalize_display_name from statedb.db.services import ConnectorService, StateServices, TableService from statedb.rest.connector_authorization import ( CONNECTOR_DISCOVERY_ACTIONS, @@ -283,6 +284,38 @@ async def create_project_connector( ) return response + async def copy_project_connector( + self, + project_id: ProjectID, + connector_id: ConnectorID, + args: api.CopyConnectorArgs, + principal: AuthPrincipal, + ) -> api.ConnectorResponse: + target_project_id = ProjectID(args.target_project_id) + if target_project_id == project_id: + raise ValueError( + 'Target project must differ from the source project') + source = await self._connector_service.get_for_project( + project_id, connector_id, principal) + create_args = api.CreateConnectorArgs( + name=args.name if args.name is not None else source.name, + config=source.config, + identity_id=source.identity_id, + description=(args.description if args.description is not None + else source.description), + ) + existing_names = { + normalize_display_name(connector.name) + for connector in await self._connector_service.list_for_project( + target_project_id, principal) + } + if normalize_display_name(create_args.name) in existing_names: + raise ConnectorNameConflictError( + f"Connector named '{create_args.name}' already exists in " + 'this project') + return await self.create_project_connector(target_project_id, + create_args, principal) + async def list_project_connectors( self, project_id: ProjectID, diff --git a/rest/routers/connectors.py b/rest/routers/connectors.py index 6d58ed318..88bcd02ae 100644 --- a/rest/routers/connectors.py +++ b/rest/routers/connectors.py @@ -66,6 +66,9 @@ def __init__(self, auth: Authentication, self.router.add_api_route('/{connector_id}', self.delete_connector, methods=['DELETE'], response_model=api.ConnectorResponse) + self.router.add_api_route('/{connector_id}/copy', self.copy_connector, + methods=['POST'], + response_model=api.ConnectorResponse) self.router.add_api_route('/{connector_id}/validate', self.validate_connector, methods=['POST'], response_model=api.ConnectorResponse) @@ -138,6 +141,24 @@ async def create_connector( project_id, args, principal) return response + async def copy_connector( + self, + project_id: ProjectID, + connector_id: ConnectorID, + args: api.CopyConnectorArgs, + request: Request, + ) -> api.ConnectorResponse: + with wrap_driver_errors({ + ConnectorDoesNotExistError: HTTPStatus.NOT_FOUND, + IdentityForbiddenError: HTTPStatus.FORBIDDEN, + IdentityDoesNotExistError: HTTPStatus.NOT_FOUND, + ConnectorNameConflictError: HTTPStatus.CONFLICT, + ConnectorValidationError: HTTPStatus.UNPROCESSABLE_ENTITY, + ValueError: HTTPStatus.BAD_REQUEST, + }): + return await self._driver.copy_project_connector( + project_id, connector_id, args, self._principal(request)) + async def list_connectors( self, project_id: ProjectID, diff --git a/test/rest/routers/test_connector_copy.py b/test/rest/routers/test_connector_copy.py new file mode 100644 index 000000000..eed540172 --- /dev/null +++ b/test/rest/routers/test_connector_copy.py @@ -0,0 +1,199 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from datetime import datetime, timezone +from http import HTTPStatus +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import kumoapi.data_source as api +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from rest.driver.connector_api_driver import ConnectorApiDriver +from rest.routers.connectors import ConnectorResource +from statedb.config.common import ConnectorID, IdentityID, ProjectID +from statedb.utils.errors import ( + ConnectorDoesNotExistError, + ConnectorNameConflictError, + IdentityForbiddenError, +) + +SOURCE_PROJECT = str(ProjectID.generate()) +TARGET_PROJECT = str(ProjectID.generate()) + + +def _connector(project_id: str, name: str = 'events', + description: str = 'raw events') -> api.ConnectorResponse: + now = datetime.now(timezone.utc) + return api.ConnectorResponse( + id=str(ConnectorID.generate()), + project_id=project_id, + identity_id=str(IdentityID.generate()), + name=name, + description=description, + timestamps=api.ResourceTimestamps(created_at=now, updated_at=now), + config=api.S3ConnectorResourceConfig(target=api.S3RootedConnectorTarget( + bucket='kumo-events', prefix='events', region='us-west-2')), + ) + + +def _driver_with_source(source: api.ConnectorResponse): + driver = SimpleNamespace( + _connector_service=SimpleNamespace( + get_for_project=AsyncMock(return_value=source), + list_for_project=AsyncMock(return_value=[]), + ), + create_project_connector=AsyncMock( + side_effect=lambda project_id, args, principal: _connector( + project_id, args.name, args.description)), + ) + return driver + + +@pytest.mark.asyncio +async def test_copy_reuses_source_config_identity_and_metadata() -> None: + source = _connector(SOURCE_PROJECT) + driver = _driver_with_source(source) + principal = MagicMock() + + copied = await ConnectorApiDriver.copy_project_connector( + driver, ProjectID(SOURCE_PROJECT), ConnectorID(source.id), + api.CopyConnectorArgs(target_project_id=TARGET_PROJECT), principal) + + driver._connector_service.get_for_project.assert_awaited_once_with( + SOURCE_PROJECT, source.id, principal) + target, create_args, _ = driver.create_project_connector.await_args.args + assert target == TARGET_PROJECT + assert create_args == api.CreateConnectorArgs( + name=source.name, + config=source.config, + identity_id=source.identity_id, + description=source.description, + ) + assert copied.project_id == TARGET_PROJECT + + +@pytest.mark.asyncio +async def test_copy_applies_name_and_description_overrides() -> None: + source = _connector(SOURCE_PROJECT) + driver = _driver_with_source(source) + + await ConnectorApiDriver.copy_project_connector( + driver, ProjectID(SOURCE_PROJECT), ConnectorID(source.id), + api.CopyConnectorArgs(target_project_id=TARGET_PROJECT, + name='events_copy', description=''), + MagicMock()) + + create_args = driver.create_project_connector.await_args.args[1] + assert create_args.name == 'events_copy' + assert create_args.description == '' + + +@pytest.mark.asyncio +async def test_copy_into_the_source_project_is_rejected_before_lookup() -> None: + source = _connector(SOURCE_PROJECT) + driver = _driver_with_source(source) + + with pytest.raises(ValueError, match='must differ'): + await ConnectorApiDriver.copy_project_connector( + driver, ProjectID(SOURCE_PROJECT), ConnectorID(source.id), + api.CopyConnectorArgs(target_project_id=SOURCE_PROJECT), + MagicMock()) + + driver._connector_service.get_for_project.assert_not_awaited() + driver.create_project_connector.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_copy_rejects_a_name_already_used_in_the_target() -> None: + source = _connector(SOURCE_PROJECT) + driver = _driver_with_source(source) + driver._connector_service.list_for_project.return_value = [ + _connector(TARGET_PROJECT, name='EVENTS') + ] + + with pytest.raises(ConnectorNameConflictError, match='already exists'): + await ConnectorApiDriver.copy_project_connector( + driver, ProjectID(SOURCE_PROJECT), ConnectorID(source.id), + api.CopyConnectorArgs(target_project_id=TARGET_PROJECT), + MagicMock()) + + driver._connector_service.list_for_project.assert_awaited_once() + driver.create_project_connector.assert_not_awaited() + + +def _client(copy_result) -> tuple[TestClient, MagicMock]: + driver = MagicMock(spec=ConnectorApiDriver) + driver.copy_project_connector = AsyncMock(side_effect=copy_result) \ + if isinstance(copy_result, Exception) else AsyncMock( + return_value=copy_result) + app = FastAPI() + + @app.middleware('http') + async def add_principal(request, call_next): + request.state.user_authorization = MagicMock() + return await call_next(request) + + auth = SimpleNamespace(authenticate_request_header=lambda: None) + app.include_router(ConnectorResource(auth, driver).router) + return TestClient(app), driver + + +def _copy_url(connector_id: str) -> str: + return (f'/v0/projects/{SOURCE_PROJECT}/connectors/' + f'{connector_id}/copy') + + +def test_copy_route_returns_created_connector() -> None: + created = _connector(TARGET_PROJECT) + client, driver = _client(created) + connector_id = str(ConnectorID.generate()) + + with client: + response = client.post(_copy_url(connector_id), json={ + 'target_project_id': TARGET_PROJECT, + 'name': 'events', + }) + + assert response.status_code == HTTPStatus.OK + assert response.json()['project_id'] == TARGET_PROJECT + args = driver.copy_project_connector.await_args.args + assert args[0] == SOURCE_PROJECT + assert args[1] == connector_id + assert args[2] == api.CopyConnectorArgs(target_project_id=TARGET_PROJECT, + name='events') + + +@pytest.mark.parametrize('error, status', [ + (ConnectorDoesNotExistError('missing'), HTTPStatus.NOT_FOUND), + (IdentityForbiddenError('Identity is not mapped to the project group'), + HTTPStatus.FORBIDDEN), + (ConnectorNameConflictError('events'), HTTPStatus.CONFLICT), + (ValueError('Target project must differ from the source project'), + HTTPStatus.BAD_REQUEST), +]) +def test_copy_route_maps_errors(error: Exception, status: HTTPStatus) -> None: + client, _ = _client(error) + + with client: + response = client.post(_copy_url(str(ConnectorID.generate())), + json={'target_project_id': TARGET_PROJECT}) + + assert response.status_code == status + + +def test_copy_route_rejects_unknown_fields() -> None: + client, driver = _client(_connector(TARGET_PROJECT)) + + with client: + response = client.post( + _copy_url(str(ConnectorID.generate())), json={ + 'target_project_id': TARGET_PROJECT, + 'config': {}, + }) + + assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY + driver.copy_project_connector.assert_not_called() diff --git a/test/statedb/db/test_identity_services.py b/test/statedb/db/test_identity_services.py index 8f8ea56de..a0fde2dab 100644 --- a/test/statedb/db/test_identity_services.py +++ b/test/statedb/db/test_identity_services.py @@ -50,6 +50,7 @@ TableDefinition, ) from rest.config.training_job import CustomTrainingTable +from rest.driver.connector_api_driver import ConnectorApiDriver from rest.utils.ambient_identity import ensure_startup_ambient_identities from statedb.config.common import ( ArtifactExportJobID, @@ -4031,3 +4032,186 @@ async def test_connector_delete_blocked_by_a_query_held_graph( with pytest.raises(ConnectorInUseError, match='live table'): await connectors.delete(project_id, connector.id, ADMIN) assert len(await _all_table_rows(db, project_id)) == 1 + + +def _copy_driver(connectors: ConnectorService) -> SimpleNamespace: + async def create(project_id, args, principal): + return await _create_connector(connectors, project_id, args, principal) + + return SimpleNamespace(_connector_service=connectors, + create_project_connector=create) + + +async def _copy(connectors: ConnectorService, source_project: ProjectID, + connector_id: ConnectorID, target_project: ProjectID, + principal: _Principal, **overrides): + return await ConnectorApiDriver.copy_project_connector( + _copy_driver(connectors), + source_project, + connector_id, + api.CopyConnectorArgs(target_project_id=str(target_project), + **overrides), + principal, + ) + + +async def _set_project_status(db: StateDB, project_id: ProjectID, + status: ProjectStatus) -> None: + repo = JsonRepository('projects', ProjectDBEntry) + async with db.write_tx() as tx: + row = await repo.get(tx, str(project_id)) + await repo.upsert(tx, str(project_id), + replace(row.payload, status=status)) + + +@pytest.mark.asyncio +async def test_copy_connector_recreates_config_and_identity_in_target( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + + copied = await _copy(connectors, source_project, source.id, + target_project, user) + + assert copied.id != source.id + assert copied.project_id == target_project + assert copied.identity_id == identity.id + assert copied.name == source.name + assert copied.config == source.config + assert [c.id for c in await connectors.list_for_project( + source_project, user)] == [source.id] + assert [c.id for c in await connectors.list_for_project( + target_project, user)] == [copied.id] + + +@pytest.mark.asyncio +async def test_copy_connector_applies_name_and_description_overrides( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + + copied = await _copy(connectors, source_project, source.id, + target_project, user, name='renamed', + description='copied') + + assert (copied.name, copied.description) == ('renamed', 'copied') + + +@pytest.mark.asyncio +async def test_copy_connector_rejects_the_source_project_as_target( + db: StateDB) -> None: + (_group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + + with pytest.raises(ValueError, match='must differ'): + await _copy(connectors, source_project, source.id, source_project, + user, name='other-name') + assert len(await connectors.list_for_project(source_project, user)) == 1 + + +@pytest.mark.asyncio +async def test_copy_connector_requires_identity_bound_to_target_group( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + other_group = await _create_group(db, 'other-team') + target_project = await _create_project(db, other_group, 'target') + member_of_both = replace(user, + kumo_group_ids=(str(group_id), str(other_group))) + + with pytest.raises(IdentityForbiddenError): + await _copy(connectors, source_project, source.id, target_project, + member_of_both) + assert await connectors.list_for_project(target_project, + member_of_both) == [] + + +@pytest.mark.asyncio +async def test_copy_connector_rejects_archived_target(db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + await _set_project_status(db, target_project, ProjectStatus.ARCHIVED) + + with pytest.raises(ProjectNotFoundError): + await _copy(connectors, source_project, source.id, target_project, + user) + + +@pytest.mark.asyncio +async def test_copy_connector_rejects_target_invisible_to_caller( + db: StateDB) -> None: + (_group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + other_group = await _create_group(db, 'other-team') + hidden_project = await _create_project(db, other_group, 'hidden') + + with pytest.raises(ProjectNotFoundError): + await _copy(connectors, source_project, source.id, hidden_project, + user) + + +@pytest.mark.asyncio +async def test_copy_connector_rejects_project_upload_connector( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + _source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + upload_id = await connectors.register_project_upload_connector( + source_project, '/tmp/uploaded-datasets/source') + + with pytest.raises(ConnectorDoesNotExistError): + await _copy(connectors, source_project, upload_id, target_project, + user) + + +@pytest.mark.asyncio +async def test_repeated_copy_reports_that_the_connector_already_exists( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + + first = await _copy(connectors, source_project, source.id, + target_project, user) + with pytest.raises(ConnectorNameConflictError, match='already exists'): + await _copy(connectors, source_project, source.id, target_project, + user) + + assert [c.id for c in await connectors.list_for_project( + target_project, user)] == [first.id] + + +@pytest.mark.asyncio +async def test_copy_rejects_name_used_by_a_differently_configured_connector( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + existing = await _create_connector( + connectors, target_project, + _connector_args(source.name, identity.id, 'other_schema'), user) + + with pytest.raises(ConnectorNameConflictError, match='already exists'): + await _copy(connectors, source_project, source.id, target_project, + user) + + assert [c.id for c in await connectors.list_for_project( + target_project, user)] == [existing.id] + + +@pytest.mark.asyncio +async def test_copy_from_an_archived_source_project_is_allowed( + db: StateDB) -> None: + (group_id, source_project, user, _identities, connectors, _identity, + source) = await _bound_databricks_connector(db) + target_project = await _create_project(db, group_id, 'target') + await _set_project_status(db, source_project, ProjectStatus.ARCHIVED) + + copied = await _copy(connectors, source_project, source.id, + target_project, user) + + assert copied.project_id == target_project + assert copied.config == source.config diff --git a/ui/.ui-baseline.json b/ui/.ui-baseline.json index 0d1f7072b..5337e5ad8 100644 --- a/ui/.ui-baseline.json +++ b/ui/.ui-baseline.json @@ -11,7 +11,7 @@ }, "neutralPaletteFiles": 0, "catalogAdoptionRatio": 0.6, - "filesRenderingUiWithoutCatalogImport": 138, + "filesRenderingUiWithoutCatalogImport": 139, "classAssertingTestFiles": 7, "indirectClassNameFiles": 7, "bidirectionalUiToFeatureImports": 0, diff --git a/ui/src/components/Connectors/CopyConnector/CopyConnectorDialog.tsx b/ui/src/components/Connectors/CopyConnector/CopyConnectorDialog.tsx new file mode 100644 index 000000000..ab15bab24 --- /dev/null +++ b/ui/src/components/Connectors/CopyConnector/CopyConnectorDialog.tsx @@ -0,0 +1,228 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +// All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { useMemo, useRef, useState } from "react"; + +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogTitle, + Input, + Select +} from "@kumo-ai/kumo-ui-catalog"; +import { ConnectorResponse, ProjectStatus } from "gen/v0/types"; + +import WithErrorBoundary from "components/@hoc/WithErrorBoundary"; + +import { useCopyConnector } from "hooks/connector/connector"; +import { useProjectList } from "hooks/project/projects"; + +import { JsConnector } from "types/connectors"; + +import { getProjectPath } from "utils/Constants"; +import { useCustomNavigation } from "utils/navigator"; + +export interface CopyConnectorDialogProps { + open: boolean; + onClose: () => void; + connector: JsConnector | null; + sourceProjectId: string; +} + +const CopyConnectorDialogComponent = ({ + open, + onClose, + connector, + sourceProjectId +}: CopyConnectorDialogProps) => { + const navigate = useCustomNavigation(); + const { projectListResponse, isLoading: isProjectListLoading } = + useProjectList(); + const { copyConnector, isCopying } = useCopyConnector(); + const [targetProjectId, setTargetProjectId] = useState(""); + const [name, setName] = useState(connector?.name ?? ""); + const [errorMsg, setErrorMsg] = useState(""); + const [copied, setCopied] = useState(null); + const copyInFlightRef = useRef(false); + + const projectOptions = useMemo( + () => + (projectListResponse?.data ?? []) + .filter( + (p) => + p.id !== sourceProjectId && + p.status !== ProjectStatus.ARCHIVED + ) + .map((p) => ({ + value: p.id, + label: p.display_name || p.id + })), + [projectListResponse?.data, sourceProjectId] + ); + + const copiedProjectLabel = copied + ? (projectOptions.find((p) => p.value === copied.project_id)?.label ?? + copied.project_id) + : ""; + + const onCopyClick = async () => { + if (!connector || copyInFlightRef.current) return; + copyInFlightRef.current = true; + try { + const result = await copyConnector(sourceProjectId, connector.id, { + target_project_id: targetProjectId, + name: name.trim() + }); + if (result.error !== null) { + setErrorMsg(result.error); + } else { + setCopied(result.connector); + } + } finally { + copyInFlightRef.current = false; + } + }; + + const canCopy = + !!connector && !!targetProjectId && !!name.trim() && !isCopying; + + return ( + { + if (!isOpen) onClose(); + }}> + e.preventDefault()}> +
+ + Copy connector to project + + +
+ {copied ? ( +

+ Connector "{copied.name}" was copied to " + {copiedProjectLabel}". +

+ ) : ( + <> +

+ The copy uses the same configuration and + identity as "{connector?.name}". The + identity must be assigned to the target + project's group. Tables are not copied. +

+
+ + { + setName(e.target.value); + setErrorMsg(""); + }} + className="h-9 !text-base font-medium py-2 px-4" + /> +
+ {errorMsg && ( +

+ {errorMsg} +

+ )} + + )} +
+
+
+ {copied ? ( + <> + + + + ) : ( + <> + + + + )} +
+
+
+
+ ); +}; + +export const CopyConnectorDialog = WithErrorBoundary( + CopyConnectorDialogComponent +); diff --git a/ui/src/components/Connectors/CopyConnector/__tests__/CopyConnectorDialog.test.tsx b/ui/src/components/Connectors/CopyConnector/__tests__/CopyConnectorDialog.test.tsx new file mode 100644 index 000000000..076b8bf37 --- /dev/null +++ b/ui/src/components/Connectors/CopyConnector/__tests__/CopyConnectorDialog.test.tsx @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +// All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { MemoryRouter } from "react-router"; + +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { vi } from "vitest"; + +import { JsConnector } from "types/connectors"; + +import { CopyConnectorDialog } from "../CopyConnectorDialog"; + +const copyConnector = vi.fn(); +const navigate = vi.fn(); +const onClose = vi.fn(); + +const projects = [ + { id: "project-sales", display_name: "Sales", status: "active" }, + { id: "project-marketing", display_name: "Marketing", status: "active" }, + { id: "project-legacy", display_name: "Legacy", status: "archived" } +]; + +vi.mock("hooks/connector/connector", () => ({ + useCopyConnector: () => ({ copyConnector, isCopying: false }) +})); +vi.mock("hooks/project/projects", () => ({ + useProjectList: () => ({ + projectListResponse: { data: projects }, + isLoading: false + }) +})); +vi.mock("utils/navigator", () => ({ + useCustomNavigation: () => navigate +})); + +const connector = { + id: "connector-sales", + name: "Sales analytics" +} as JsConnector; + +const renderDialog = () => + render( + + + + ); + +const copyButton = () => screen.getByRole("button", { name: "Copy" }); + +const chooseTarget = async (name: string) => { + await userEvent.click( + screen.getByTestId("testid-copy-connector-target-project") + ); + const listbox = await screen.findByTestId("listbox"); + await userEvent.click(await within(listbox).findByText(name)); +}; + +describe("CopyConnectorDialog", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("offers only other active projects and requires a target", async () => { + renderDialog(); + + expect(screen.getByLabelText("Connector name")).toHaveValue( + "Sales analytics" + ); + expect(copyButton()).toBeDisabled(); + + await userEvent.click( + screen.getByTestId("testid-copy-connector-target-project") + ); + const listbox = await screen.findByTestId("listbox"); + expect(within(listbox).getByText("Marketing")).toBeInTheDocument(); + expect(within(listbox).queryByText("Sales")).not.toBeInTheDocument(); + expect(within(listbox).queryByText("Legacy")).not.toBeInTheDocument(); + }); + + it("copies with the chosen target and trimmed name, then links to the target project", async () => { + copyConnector.mockResolvedValue({ + connector: { + id: "connector-copy", + name: "Sales copy", + project_id: "project-marketing" + }, + error: null + }); + renderDialog(); + + await chooseTarget("Marketing"); + const nameInput = screen.getByLabelText("Connector name"); + await userEvent.clear(nameInput); + await userEvent.type(nameInput, " Sales copy "); + await userEvent.click(copyButton()); + + expect(copyConnector).toHaveBeenCalledWith( + "project-sales", + "connector-sales", + { target_project_id: "project-marketing", name: "Sales copy" } + ); + expect( + await screen.findByText( + 'Connector "Sales copy" was copied to "Marketing".' + ) + ).toBeInTheDocument(); + + await userEvent.click( + screen.getByRole("button", { name: "Go to project" }) + ); + expect(onClose).toHaveBeenCalled(); + expect(navigate).toHaveBeenCalledWith( + "/project/project-marketing/connectors/Sales copy" + ); + }); + + it("shows the server error inline and keeps the form", async () => { + copyConnector.mockResolvedValue({ + connector: null, + error: "Connector named 'Sales analytics' already exists in this project" + }); + renderDialog(); + + await chooseTarget("Marketing"); + await userEvent.click(copyButton()); + + await waitFor(() => + expect(screen.getByRole("alert")).toHaveTextContent( + "already exists in this project" + ) + ); + expect(copyButton()).toBeEnabled(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it("sends one copy request when Copy is activated twice while a copy is pending", async () => { + let resolveCopy: (value: unknown) => void = () => {}; + copyConnector.mockReturnValue( + new Promise((resolve) => { + resolveCopy = resolve; + }) + ); + renderDialog(); + + await chooseTarget("Marketing"); + await userEvent.click(copyButton()); + await userEvent.click(copyButton()); + resolveCopy({ + connector: null, + error: "Connector named 'Sales analytics' already exists in this project" + }); + + await waitFor(() => + expect(screen.getByRole("alert")).toHaveTextContent( + "already exists" + ) + ); + expect(copyConnector).toHaveBeenCalledTimes(1); + }); + + it("disables Copy when the name is blank", async () => { + renderDialog(); + + await chooseTarget("Marketing"); + expect(copyButton()).toBeEnabled(); + await userEvent.clear(screen.getByLabelText("Connector name")); + + expect(copyButton()).toBeDisabled(); + expect(copyConnector).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/components/Connectors/CopyConnector/__tests__/MockFunctions/CopyConnector.mock.ts b/ui/src/components/Connectors/CopyConnector/__tests__/MockFunctions/CopyConnector.mock.ts new file mode 100644 index 000000000..433683ef3 --- /dev/null +++ b/ui/src/components/Connectors/CopyConnector/__tests__/MockFunctions/CopyConnector.mock.ts @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +// All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { ConnectorResponse } from "gen/v0/types"; +import { testResponseType } from "tests/testResponseType"; +import { createMockResponse } from "tests/testUtil"; + +export const mockCopiedConnector: ConnectorResponse = { + id: "connector_00000000000000000000000000000c09", + project_id: "project-target", + identity_id: "identity_00000000000000000000000000000001", + name: "Sales analytics", + description: "", + timestamps: { + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z" + }, + config: { + type: "s3", + target: { mode: "rooted", bucket: "sales", prefix: "", region: null } + } +} as ConnectorResponse; + +let copyConnectorResponseType = ""; + +export const mockCopyConnectorResponse = () => { + if (copyConnectorResponseType === testResponseType.ERROR) { + return Promise.reject({ + response: { + status: 409, + data: { + detail: "Connector named 'Sales analytics' already exists in this project" + } + } + }); + } + return Promise.resolve(createMockResponse(mockCopiedConnector)); +}; + +export const setCopyConnectorResponseType = (type: string = "") => { + copyConnectorResponseType = type; +}; diff --git a/ui/src/gen/spec/v0_openapi.json b/ui/src/gen/spec/v0_openapi.json index bb62c36ef..807be0dd7 100644 --- a/ui/src/gen/spec/v0_openapi.json +++ b/ui/src/gen/spec/v0_openapi.json @@ -838,6 +838,65 @@ } } }, + "/v0/projects/{project_id}/connectors/{connector_id}/copy": { + "post": { + "tags": ["Connectors"], + "summary": "Copy Connector", + "operationId": "copy_connector_v0_projects__project_id__connectors__connector_id__copy_post", + "parameters": [ + { + "name": "project_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Project Id" + } + }, + { + "name": "connector_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Connector Id" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopyConnectorArgs" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConnectorResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/v0/projects/{project_id}/connectors/{connector_id}/validate": { "post": { "tags": ["Connectors"], @@ -8026,6 +8085,41 @@ ], "title": "ConnectorType" }, + "CopyConnectorArgs": { + "properties": { + "target_project_id": { + "type": "string", + "title": "Target Project Id" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + } + }, + "additionalProperties": false, + "type": "object", + "required": ["target_project_id"], + "title": "CopyConnectorArgs", + "description": "Copy one connector's configuration and identity into a project.\n\n``name`` and ``description`` default to the source connector's values.\nThe identity must be assigned to the target project's group." + }, "CreateAPIKeyResponse": { "properties": { "id": { diff --git a/ui/src/gen/v0/api/connectors/connectors.ts b/ui/src/gen/v0/api/connectors/connectors.ts index 5c6c454da..4471fbc2e 100644 --- a/ui/src/gen/v0/api/connectors/connectors.ts +++ b/ui/src/gen/v0/api/connectors/connectors.ts @@ -26,6 +26,7 @@ import { customClient } from "../../../../services/orval_axios_client"; import { CreateProjectsCompleteByProjectIdResponse, CreateProjectsConnectorsByProjectIdResponse, + CreateProjectsCopyByConnectorIdResponse, CreateProjectsDeleteByProjectIdResponse, CreateProjectsStartByProjectIdResponse, DeleteProjectsConnectorsByConnectorIdResponse, @@ -42,6 +43,7 @@ import { import type { CompleteFileUploadRequest, ConnectorResponse, + CopyConnectorArgs, CreateConnectorArgs, DeleteUploadedFileRequest, EmptyResponse, @@ -834,6 +836,113 @@ export const useDeleteProjectsConnectorsByConnectorId = < queryClient ); }; +/** + * @summary Copy Connector + */ +export const createProjectsCopyByConnectorId = ( + projectId: string, + connectorId: string, + copyConnectorArgs: CopyConnectorArgs, + options?: SecondParameter, + signal?: AbortSignal +) => { + return customClient( + { + url: `/v0/projects/${projectId}/connectors/${connectorId}/copy`, + method: "POST", + headers: { "Content-Type": "application/json" }, + data: copyConnectorArgs, + signal + }, + options || CreateProjectsCopyByConnectorIdResponse + ); +}; + +export const getCreateProjectsCopyByConnectorIdMutationKey = () => + ["createProjectsCopyByConnectorId"] as const; + +export const getCreateProjectsCopyByConnectorIdMutationOptions = < + TError = HTTPValidationError, + TContext = unknown +>(options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CreateProjectsCopyByConnectorIdMutationVariables, + TContext + >; + request?: SecondParameter; +}): UseMutationOptions< + Awaited>, + TError, + CreateProjectsCopyByConnectorIdMutationVariables, + TContext +> => { + const mutationKey = getCreateProjectsCopyByConnectorIdMutationKey(); + const { mutation: mutationOptions, request: requestOptions } = options + ? options.mutation && + "mutationKey" in options.mutation && + options.mutation.mutationKey + ? options + : { ...options, mutation: { ...options.mutation, mutationKey } } + : { mutation: { mutationKey }, request: undefined }; + + const mutationFn: MutationFunction< + Awaited>, + CreateProjectsCopyByConnectorIdMutationVariables + > = (props) => { + const { projectId, connectorId, data } = props ?? {}; + + return createProjectsCopyByConnectorId( + projectId, + connectorId, + data, + requestOptions + ); + }; + + return { mutationFn, ...mutationOptions }; +}; + +export type CreateProjectsCopyByConnectorIdMutationResult = NonNullable< + Awaited> +>; +export type CreateProjectsCopyByConnectorIdMutationBody = CopyConnectorArgs; +export type CreateProjectsCopyByConnectorIdMutationError = HTTPValidationError; +export type CreateProjectsCopyByConnectorIdMutationVariables = { + projectId: string; + connectorId: string; + data: CopyConnectorArgs; +}; + +/** + * @summary Copy Connector + */ +export const useCreateProjectsCopyByConnectorId = < + TError = HTTPValidationError, + TContext = unknown +>( + options?: { + mutation?: UseMutationOptions< + Awaited>, + TError, + CreateProjectsCopyByConnectorIdMutationVariables, + TContext + >; + request?: SecondParameter; + }, + queryClient?: QueryClient +): UseMutationResult< + Awaited>, + TError, + CreateProjectsCopyByConnectorIdMutationVariables, + TContext +> => { + return useMutation( + getCreateProjectsCopyByConnectorIdMutationOptions(options), + queryClient + ); +}; /** * @summary Validate Connector */ diff --git a/ui/src/gen/v0/schemas/connectors.ts b/ui/src/gen/v0/schemas/connectors.ts index 7d712cb28..d1dfeeeb4 100644 --- a/ui/src/gen/v0/schemas/connectors.ts +++ b/ui/src/gen/v0/schemas/connectors.ts @@ -1310,6 +1310,233 @@ export const DeleteProjectsConnectorsByConnectorIdResponse = zod.object({ "created_by": zod.union([zod.string(), zod.null()]).optional() }); +/** + * @summary Copy Connector + */ +export const CreateProjectsCopyByConnectorIdParams = zod.object({ + "project_id": zod.string(), + "connector_id": zod.string() +}); + +export const CreateProjectsCopyByConnectorIdBody = zod + .object({ + "target_project_id": zod.string(), + "name": zod.union([zod.string(), zod.null()]).optional(), + "description": zod.union([zod.string(), zod.null()]).optional() + }) + .describe( + "Copy one connector's configuration and identity into a project. ``name`` and ``description`` default to the source connector's values. The identity must be assigned to the target project's group." + ); + +export const createProjectsCopyByConnectorIdResponseConfigOneTypeDefault = `snowflake`; +export const createProjectsCopyByConnectorIdResponseConfigTwoTypeDefault = `databricks`; +export const createProjectsCopyByConnectorIdResponseConfigThreeTypeDefault = `bigquery`; +export const createProjectsCopyByConnectorIdResponseConfigFourTargetOnePrefixDefault = ``; +export const createProjectsCopyByConnectorIdResponseConfigFourTargetOneModeDefault = `rooted`; +export const createProjectsCopyByConnectorIdResponseConfigFourTargetTwoModeDefault = `any_uri`; +export const createProjectsCopyByConnectorIdResponseConfigFourTypeDefault = `s3`; +export const createProjectsCopyByConnectorIdResponseConfigFiveTargetOnePrefixDefault = ``; +export const createProjectsCopyByConnectorIdResponseConfigFiveTargetOneModeDefault = `rooted`; +export const createProjectsCopyByConnectorIdResponseConfigFiveTargetTwoModeDefault = `any_uri`; +export const createProjectsCopyByConnectorIdResponseConfigFiveTypeDefault = `gcs`; +export const createProjectsCopyByConnectorIdResponseConfigSixTargetOnePrefixDefault = ``; +export const createProjectsCopyByConnectorIdResponseConfigSixTargetOneEndpointSuffixDefault = `dfs.core.windows.net`; +export const createProjectsCopyByConnectorIdResponseConfigSixTargetOneModeDefault = `rooted`; +export const createProjectsCopyByConnectorIdResponseConfigSixTargetTwoModeDefault = `any_uri`; +export const createProjectsCopyByConnectorIdResponseConfigSixTypeDefault = `adls`; +export const createProjectsCopyByConnectorIdResponseDescriptionDefault = ``; + +export const CreateProjectsCopyByConnectorIdResponse = zod.object({ + "id": zod.string(), + "project_id": zod.string(), + "identity_id": zod.string(), + "name": zod.string(), + "timestamps": zod.object({ + "created_at": zod.iso.datetime({ "offset": true, "local": true }), + "updated_at": zod.iso.datetime({ "offset": true, "local": true }) + }), + "config": zod.union([ + zod.object({ + "warehouse": zod.string(), + "database": zod.string(), + "schema_name": zod.string(), + "role": zod.union([zod.string(), zod.null()]).optional(), + "type": zod + .literal("snowflake") + .default( + createProjectsCopyByConnectorIdResponseConfigOneTypeDefault + ) + .meta({ title: "Type" }) + }), + zod.object({ + "catalog": zod.string(), + "schema_name": zod.string(), + "cluster_id": zod.union([zod.string(), zod.null()]).optional(), + "warehouse_id": zod.union([zod.string(), zod.null()]).optional(), + "type": zod + .literal("databricks") + .default( + createProjectsCopyByConnectorIdResponseConfigTwoTypeDefault + ) + .meta({ title: "Type" }) + }), + zod.object({ + "project_id": zod.string(), + "dataset_id": zod.string(), + "location": zod.string(), + "billing_project_id": zod + .union([zod.string(), zod.null()]) + .optional(), + "type": zod + .literal("bigquery") + .default( + createProjectsCopyByConnectorIdResponseConfigThreeTypeDefault + ) + .meta({ title: "Type" }) + }), + zod + .object({ + "target": zod.union([ + zod + .object({ + "bucket": zod.string(), + "prefix": zod + .string() + .default( + createProjectsCopyByConnectorIdResponseConfigFourTargetOnePrefixDefault + ), + "region": zod + .union([zod.string(), zod.null()]) + .optional(), + "mode": zod + .literal("rooted") + .default( + createProjectsCopyByConnectorIdResponseConfigFourTargetOneModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Restrict every S3 operation to one bucket and optional prefix." + ), + zod + .object({ + "mode": zod + .literal("any_uri") + .default( + createProjectsCopyByConnectorIdResponseConfigFourTargetTwoModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Require a canonical full S3 URI on every object operation. Region selection is intentionally per request; connector-wide region configuration is forbidden in this mode. Discovery remains unavailable." + ) + ]), + "type": zod + .literal("s3") + .default( + createProjectsCopyByConnectorIdResponseConfigFourTypeDefault + ) + .meta({ title: "Type" }) + }) + .describe( + "Project-owned S3 connector with rooted or rootless any-URI mode." + ), + zod.object({ + "target": zod.union([ + zod + .object({ + "bucket": zod.string(), + "prefix": zod + .string() + .default( + createProjectsCopyByConnectorIdResponseConfigFiveTargetOnePrefixDefault + ), + "mode": zod + .literal("rooted") + .default( + createProjectsCopyByConnectorIdResponseConfigFiveTargetOneModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Restrict every GCS operation to one bucket and optional prefix." + ), + zod + .object({ + "mode": zod + .literal("any_uri") + .default( + createProjectsCopyByConnectorIdResponseConfigFiveTargetTwoModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Require one canonical full GCS URI on every object operation." + ) + ]), + "requester_pays_project": zod + .union([zod.string(), zod.null()]) + .optional(), + "type": zod + .literal("gcs") + .default( + createProjectsCopyByConnectorIdResponseConfigFiveTypeDefault + ) + .meta({ title: "Type" }) + }), + zod.object({ + "target": zod.union([ + zod + .object({ + "storage_account": zod.string(), + "filesystem": zod.string(), + "prefix": zod + .string() + .default( + createProjectsCopyByConnectorIdResponseConfigSixTargetOnePrefixDefault + ), + "endpoint_suffix": zod + .string() + .default( + createProjectsCopyByConnectorIdResponseConfigSixTargetOneEndpointSuffixDefault + ), + "mode": zod + .literal("rooted") + .default( + createProjectsCopyByConnectorIdResponseConfigSixTargetOneModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Restrict every ADLS operation to one filesystem and prefix." + ), + zod + .object({ + "mode": zod + .literal("any_uri") + .default( + createProjectsCopyByConnectorIdResponseConfigSixTargetTwoModeDefault + ) + .meta({ title: "Mode" }) + }) + .describe( + "Require one canonical full ADLS URI on every object operation." + ) + ]), + "type": zod + .literal("adls") + .default( + createProjectsCopyByConnectorIdResponseConfigSixTypeDefault + ) + .meta({ title: "Type" }) + }) + ]), + "description": zod + .string() + .default(createProjectsCopyByConnectorIdResponseDescriptionDefault), + "created_by": zod.union([zod.string(), zod.null()]).optional() +}); + /** * @summary Validate Connector */ diff --git a/ui/src/gen/v0/types/copyConnectorArgs.ts b/ui/src/gen/v0/types/copyConnectorArgs.ts new file mode 100644 index 000000000..60e24a780 --- /dev/null +++ b/ui/src/gen/v0/types/copyConnectorArgs.ts @@ -0,0 +1,18 @@ +/** + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. + * All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * @generated by Orval — DO NOT EDIT. + */ +import type { CopyConnectorArgsDescription } from "./copyConnectorArgsDescription"; +import type { CopyConnectorArgsName } from "./copyConnectorArgsName"; + +/** + * Copy one connector's configuration and identity into a project. ``name`` and ``description`` default to the source connector's values. The identity must be assigned to the target project's group. + */ +export interface CopyConnectorArgs { + target_project_id: string; + name?: CopyConnectorArgsName; + description?: CopyConnectorArgsDescription; +} diff --git a/ui/src/gen/v0/types/copyConnectorArgsDescription.ts b/ui/src/gen/v0/types/copyConnectorArgsDescription.ts new file mode 100644 index 000000000..962c2f0eb --- /dev/null +++ b/ui/src/gen/v0/types/copyConnectorArgsDescription.ts @@ -0,0 +1,9 @@ +/** + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. + * All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * @generated by Orval — DO NOT EDIT. + */ + +export type CopyConnectorArgsDescription = string | null; diff --git a/ui/src/gen/v0/types/copyConnectorArgsName.ts b/ui/src/gen/v0/types/copyConnectorArgsName.ts new file mode 100644 index 000000000..12f6ebd10 --- /dev/null +++ b/ui/src/gen/v0/types/copyConnectorArgsName.ts @@ -0,0 +1,9 @@ +/** + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. + * All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * @generated by Orval — DO NOT EDIT. + */ + +export type CopyConnectorArgsName = string | null; diff --git a/ui/src/gen/v0/types/index.ts b/ui/src/gen/v0/types/index.ts index f468f21eb..0f3018779 100644 --- a/ui/src/gen/v0/types/index.ts +++ b/ui/src/gen/v0/types/index.ts @@ -99,6 +99,9 @@ export * from "./connectorResponse"; export * from "./connectorResponseConfig"; export * from "./connectorResponseCreatedBy"; export * from "./connectorType"; +export * from "./copyConnectorArgs"; +export * from "./copyConnectorArgsDescription"; +export * from "./copyConnectorArgsName"; export * from "./createAdminAPIKeyRequest"; export * from "./createAPIKeyResponse"; export * from "./createConnectorArgs"; diff --git a/ui/src/hooks/connector/__tests__/connector.test.tsx b/ui/src/hooks/connector/__tests__/connector.test.tsx index 57fea8d91..bca60e0d4 100644 --- a/ui/src/hooks/connector/__tests__/connector.test.tsx +++ b/ui/src/hooks/connector/__tests__/connector.test.tsx @@ -15,6 +15,11 @@ import { testResponseType } from "tests/testResponseType"; import { createQueryClient, createWrapper } from "tests/testUtil"; import { vi } from "vitest"; +import { + mockCopiedConnector, + setCopyConnectorResponseType +} from "components/Connectors/CopyConnector/__tests__/MockFunctions/CopyConnector.mock"; + import { connectorListWithDistinctNamesResponse, setConnectorListResponseType, @@ -31,6 +36,7 @@ import { useConnectorDetails, useConnectorDropdownOptions, useConnectors, + useCopyConnector, useGetColumns, useGetSampleRows } from "../connector"; @@ -60,6 +66,7 @@ beforeEach(() => { setCustomConnectorListResponse(null); setConnectorTablesResponseType(); setDeleteConnectorTestType(); + setCopyConnectorResponseType(); }); afterEach(() => { @@ -619,3 +626,61 @@ describe("useGetSampleRows", () => { }); }); }); + +describe("useCopyConnector", () => { + const args = { + target_project_id: "project-target", + name: "Sales analytics" + }; + + const renderUseCopyConnector = () => + renderHook(() => useCopyConnector(), { + wrapper: createWrapper(queryClient) + }); + + it("posts to the source connector's copy route and refreshes the target project's connectors", async () => { + const invalidate = vi.spyOn(queryClient, "invalidateQueries"); + const { result } = renderUseCopyConnector(); + + let outcome: Awaited>; + await act(async () => { + outcome = await result.current.copyConnector( + "project-source", + "connector-source", + args + ); + }); + + expect(outcome!).toEqual({ + connector: mockCopiedConnector, + error: null + }); + expect(mockAxiosInstance.post).toHaveBeenCalledWith( + "v0/projects/project-source/connectors/connector-source/copy", + args, + expect.anything() + ); + expect(invalidate).toHaveBeenCalledWith({ + queryKey: ["connectorList", "project-target"] + }); + }); + + it("returns the server message without refreshing on failure", async () => { + setCopyConnectorResponseType(testResponseType.ERROR); + const invalidate = vi.spyOn(queryClient, "invalidateQueries"); + const { result } = renderUseCopyConnector(); + + let outcome: Awaited>; + await act(async () => { + outcome = await result.current.copyConnector( + "project-source", + "connector-source", + args + ); + }); + + expect(outcome!.connector).toBeNull(); + expect(outcome!.error).toContain("already exists in this project"); + expect(invalidate).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/hooks/connector/connector.ts b/ui/src/hooks/connector/connector.ts index 3785a9720..53c5fee14 100644 --- a/ui/src/hooks/connector/connector.ts +++ b/ui/src/hooks/connector/connector.ts @@ -10,6 +10,7 @@ import { } from "@kumo-ai/kumo-ui-catalog"; import { useQueryClient } from "@tanstack/react-query"; import { + useCreateProjectsCopyByConnectorId, useDeleteProjectsConnectorsByConnectorId, useGetProjectsColumnsByConnectorId, useGetProjectsConnectorsByConnectorId, @@ -17,6 +18,8 @@ import { useGetProjectsSampleByConnectorId } from "gen/v0/api/connectors/connectors"; import { + ConnectorResponse, + CopyConnectorArgs, GetProjectsColumnsByConnectorIdParams, GetProjectsSampleByConnectorIdParams, SourceColumn @@ -41,9 +44,11 @@ import { getProjectPath, storageKeys } from "utils/Constants"; import { connectorListFromConnectorResp } from "utils/Converters/connectorsConverter"; import { connectorFromConnectorResp } from "utils/Converters/connectorsConverter"; import { tableFromTableResponse } from "utils/Converters/tablesConverter"; +import { parseErrorMessage } from "utils/errorHandler"; import { isValid } from "utils/Helpers/typeGuards"; import { useCustomNavigation } from "utils/navigator"; import { + invalidateConnectorList, invalidateProjectTableList, invalidateTablesList } from "utils/queryInvalidation"; @@ -171,6 +176,41 @@ export const useConnectors = ( }; }; +export type CopyConnectorResult = + | { connector: ConnectorResponse; error: null } + | { connector: null; error: string }; + +export const useCopyConnector = () => { + const queryClient = useQueryClient(); + const { mutateAsync, isPending } = useCreateProjectsCopyByConnectorId(); + + const copyConnector = useCallback( + async ( + projectId: string, + connectorId: string, + args: CopyConnectorArgs + ): Promise => { + try { + const response = await mutateAsync({ + projectId, + connectorId, + data: args + }); + invalidateConnectorList(queryClient, args.target_project_id); + return { connector: response.data, error: null }; + } catch (e) { + return { + connector: null, + error: parseErrorMessage(e as CustomError) + }; + } + }, + [mutateAsync, queryClient] + ); + + return { copyConnector, isCopying: isPending }; +}; + export const useConnectorDropdownOptions = ( handleError: (err: Error) => void, enabled = true diff --git a/ui/src/pages/Connectors/ConnectorsList/ConnectorsList.tsx b/ui/src/pages/Connectors/ConnectorsList/ConnectorsList.tsx index 8ff903a9c..3bbd9821c 100644 --- a/ui/src/pages/Connectors/ConnectorsList/ConnectorsList.tsx +++ b/ui/src/pages/Connectors/ConnectorsList/ConnectorsList.tsx @@ -4,8 +4,15 @@ import { useCallback, useMemo, useState } from "react"; -import { AddCircle, Button, DeleteIcon, Edit } from "@kumo-ai/kumo-ui-catalog"; - +import { + AddCircle, + Button, + DeleteIcon, + Duplicate, + Edit +} from "@kumo-ai/kumo-ui-catalog"; + +import { CopyConnectorDialog } from "components/Connectors/CopyConnector/CopyConnectorDialog"; import Overview from "components/Connectors/Overview/Overview"; import EmptyEntities from "components/Empty/EmptyEntities"; import ListOverview from "components/ListOverview/ListOverview"; @@ -50,6 +57,7 @@ const ConnectorsList = () => { const [selectedConnector, setSelectedConnector] = useState(null); const [connectedTables, setConnectedTables] = useState([]); + const [isCopyDialogOpen, setIsCopyDialogOpen] = useState(false); const [banner, alert, handleError, clearErrors, dialogRef] = useValidationState(setPageLoading); @@ -127,6 +135,20 @@ const ConnectorsList = () => { const editMenuItems = connectorEditMenuItems(onEditClick); const menuItems: MenuItemType[] = [ ...editMenuItems, + { + content: ( + <> + + {" Copy to project "} + + ), + disabled: false, + onSelect: () => { + clearErrors(); + setIsCopyDialogOpen(true); + }, + tooltipText: "" + }, { content: ( <> @@ -207,6 +229,14 @@ const ConnectorsList = () => { /> } /> + {projectId && isCopyDialogOpen && ( + setIsCopyDialogOpen(false)} + connector={connectorInfo} + sourceProjectId={projectId} + /> + )} ); }; diff --git a/ui/src/pages/Connectors/ConnectorsList/__tests__/ConnectorList.test.tsx b/ui/src/pages/Connectors/ConnectorsList/__tests__/ConnectorList.test.tsx index 523154234..9b00eb3ad 100644 --- a/ui/src/pages/Connectors/ConnectorsList/__tests__/ConnectorList.test.tsx +++ b/ui/src/pages/Connectors/ConnectorsList/__tests__/ConnectorList.test.tsx @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 import { fireEvent, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { vi } from "vitest"; import { useConnectors } from "hooks/connector/connector"; @@ -37,11 +38,25 @@ const connector = { } }; -vi.mock("hooks/connector/connector", () => ({ - useConnectors: vi.fn() -})); +vi.mock("hooks/connector/connector", async () => { + const { useEffect } = + await vi.importActual("react"); + return { + useConnectors: vi.fn(), + useConnectedTables: ( + _connectorId: string, + _handleError: unknown, + setLoading: (loading: boolean) => void + ) => { + useEffect(() => setLoading(false), [setLoading]); + return { isLoading: false, tables: [], deleteTable: vi.fn() }; + }, + useCopyConnector: () => ({ copyConnector: vi.fn(), isCopying: false }) + }; +}); vi.mock("hooks/project/projects", () => ({ - useProjectId: () => "project-sales" + useProjectId: () => "project-sales", + useProjectList: () => ({ projectListResponse: { data: [] } }) })); vi.mock("hooks/validation/validation", () => ({ useValidationState: () => [null, null, vi.fn(), vi.fn(), { current: null }] @@ -80,6 +95,39 @@ describe("ConnectorsList", () => { ); }); + it("opens the copy dialog from the connector menu", async () => { + render( + + + } + /> + + + ); + + expect( + screen.queryByTestId("copy-connector-dialog") + ).not.toBeInTheDocument(); + await userEvent.click( + await screen.findByTestId("more-options-dropdown") + ); + await userEvent.click( + await screen.findByRole("menuitem", { name: /Copy to project/ }) + ); + + expect( + await screen.findByTestId("copy-connector-dialog") + ).toBeInTheDocument(); + expect(screen.getByLabelText("Connector name")).toHaveValue( + "Sales analytics" + ); + }); + it("uses the project empty state", () => { vi.mocked(useConnectors).mockReturnValue({ isDataLoading: false, @@ -97,4 +145,4 @@ describe("ConnectorsList", () => { expect(screen.getByText("Project connector empty state")).toBeVisible(); }); }); -import { MemoryRouter } from "react-router"; +import { MemoryRouter, Route, Routes } from "react-router"; diff --git a/ui/src/tests/mockAxios.ts b/ui/src/tests/mockAxios.ts index 80bafaf52..8d7b6b3af 100644 --- a/ui/src/tests/mockAxios.ts +++ b/ui/src/tests/mockAxios.ts @@ -14,6 +14,7 @@ import { mockCreateGroupResponse } from "components/Admin/Groups/__tests__/MockF import { mockBPAvailableXaiResponse } from "components/BatchPredictions/__tests__/MockFunctions/BPAvailableXai.mock"; import { mockBPXaiResponse } from "components/BatchPredictions/__tests__/MockFunctions/BPXai.mock"; import { mockPredictionStatsResponse } from "components/BatchPredictions/__tests__/MockFunctions/PredictionStats.mock"; +import { mockCopyConnectorResponse } from "components/Connectors/CopyConnector/__tests__/MockFunctions/CopyConnector.mock"; import { mockGraphSnapshotResponse } from "components/Jobs/Graph/__tests__/MockFunctions/GraphSnapshot.mock"; import { mockGraphSnapshotTotalRows } from "components/Jobs/Graph/__tests__/MockFunctions/GraphSnapshotTotalRows.mock"; import { mockArchiveResponse } from "components/Jobs/Overview/__tests__/MockFunctions/Archive.mock"; @@ -247,6 +248,9 @@ export const mockAxiosInstance = { if (url === "v1/tables/infer_metadata") { return mockInferMetadataResponse(payload); } + if (/^v0\/projects\/[^/]+\/connectors\/[^/]+\/copy$/.test(url)) { + return mockCopyConnectorResponse(); + } if (url.startsWith("v0/projects/") && url.endsWith("/archive")) { return mockArchiveProjectResponse(); }