Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(frontend): migrate instance detail and create instance pages to React (#19876)
Danny Xue7a7f082fe9c
diff --git a/frontend/src/components/InstanceForm/BigQueryHostInput.vue b/frontend/src/components/InstanceForm/BigQueryHostInput.vuedeleted file mode 100644index 6d6a3a7477..0000000000--- a/frontend/src/components/InstanceForm/BigQueryHostInput.vue+++ /dev/null@@ -1,83 +0,0 @@-<template>- <div class="grid grid-cols-2 gap-x-2 gap-y-1">- <div>- <label class="textlabel">- {{ $t("instance.project-id") }}- <span style="color: red">*</span>- </label>- <NInput- v-model:value="state.projectId"- required- placeholder="projectId"- class="mt-1 w-full"- :status="state.dirty && !isValidProjectId ? 'error' : undefined"- :disabled="!allowEdit"- />- </div>-- <p class="col-span-2 textinfolabel">- {{ $t("instance.find-gcp-project-id") }}- <a- href="https://docs.bytebase.com/get-started/connect/gcp?source=console"- target="_blank"- class="normal-link inline-flex items-center"- >- {{ $t("common.detailed-guide") }}- <heroicons-outline:external-link class="w-4 h-4 ml-1" />- </a>- </p>- </div>-</template>--<script lang="ts" setup>-import { NInput } from "naive-ui";-import { computed, reactive, watch } from "vue";--type LocalState = {- projectId: string;- dirty: boolean;-};--const props = defineProps<{- host: string;- allowEdit: boolean;-}>();--const emit = defineEmits<{- (name: "update:host", host: string): void;-}>();--const RE_PROJECT_ID = /^(?:[a-z]|[-.:]|[0-9])+$/;--const state = reactive<LocalState>({- projectId: "",- dirty: false,-});--const isValidProjectId = computed(() => {- return RE_PROJECT_ID.test(state.projectId);-});--const update = () => {- if (!isValidProjectId.value) {- emit("update:host", "");- return;- }- const host = `${state.projectId}`;- emit("update:host", host);-};--watch([() => state.projectId], () => {- state.dirty = true;- update();-});--watch(- () => props.host,- (host) => {- if (!host) return;- state.projectId = host;- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/InstanceForm/Buttons.vue b/frontend/src/components/InstanceForm/Buttons.vuedeleted file mode 100644index da6c21c536..0000000000--- a/frontend/src/components/InstanceForm/Buttons.vue+++ /dev/null@@ -1,579 +0,0 @@-<template>- <template v-if="isCreating">- <div- class="w-full py-4 border-t border-block-border flex justify-between bg-white"- v-bind="$attrs"- >- <NButton- v-if="allowCancel"- :disabled="state.isRequesting || state.isTestingConnection"- @click.prevent="cancel"- >- {{ $t("common.cancel") }}- </NButton>- <div class="flex items-center gap-x-2">- <NButton- :disabled="- !allowCreate || state.isRequesting || state.isTestingConnection- "- :loading="state.isRequesting"- type="primary"- @click.prevent="tryCreate"- >- {{ $t("common.create") }}- </NButton>- </div>- </div>- </template>- <template v-if="!isCreating && instance">- <div- v-if="valueChanged && allowEdit"- class="w-full mt-4 py-4 border-t border-block-border flex justify-between bg-white"- v-bind="$attrs"- >- <NButton- :disabled="state.isTestingConnection"- @click.prevent="resetChanges"- >- <span> {{ $t("common.cancel") }}</span>- </NButton>- <div class="flex items-center gap-x-2">- <NButton- tertiary- type="primary"- :loading="state.isTestingConnection"- :disabled="!allowUpdate || state.isRequesting || !allowEdit"- @click.prevent="testConnectionForCurrentEditingDS"- >- {{ $t("instance.test-connection") }}- </NButton>- <NButton- :disabled="- !allowUpdate || state.isRequesting || state.isTestingConnection- "- :loading="state.isRequesting"- type="primary"- @click.prevent="doUpdate"- >- {{ $t("common.confirm-and-update") }}- </NButton>- </div>- </div>- </template>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { cloneDeep, isEqual } from "lodash-es";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import {- pushNotification,- useDatabaseV1Store,- useInstanceV1Store,- useSubscriptionV1Store,-} from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type {- DataSource,- Instance,-} from "@/types/proto-es/v1/instance_service_pb";-import {- DataSourceType,- InstanceSchema,-} from "@/types/proto-es/v1/instance_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { convertKVListToLabels, defer, isValidSpannerHost } from "@/utils";-import {- calcDataSourceUpdateMask,- type EditDataSource,- extractBasicInfo,- extractDataSourceEditState,-} from "./common";-import { useInstanceFormContext } from "./context";-import ScanIntervalInput from "./ScanIntervalInput.vue";--const props = withDefaults(- defineProps<{- allowCancel?: boolean;- onCreated?: (instance: Instance) => void;- onUpdated?: (instance: Instance) => void;- }>(),- {- allowCancel: true,- onCreated: undefined,- onUpdated: undefined,- }-);--const context = useInstanceFormContext();-const {- $d,- events,- state,- instance,- isCreating,- allowEdit,- allowCreate,- basicInfo,- labelKVList,- adminDataSource,- editingDataSource,- readonlyDataSourceList,- dataSourceEditState,- hasReadonlyReplicaFeature,- missingFeature,- testConnection,- checkDataSource,- extractDataSourceFromEdit,- pendingCreateInstance,- valueChanged,-} = context;--const router = useRouter();-const { t } = useI18n();-const instanceV1Store = useInstanceV1Store();-const databaseStore = useDatabaseV1Store();-const subscriptionStore = useSubscriptionV1Store();-const scanIntervalInputRef = ref<InstanceType<typeof ScanIntervalInput>>();--const resetChanges = () => {- const original = getOriginalEditState();- basicInfo.value = cloneDeep(original.basicInfo);- dataSourceEditState.value.dataSources = cloneDeep(original.dataSources);-};--const allowUpdate = computed((): boolean => {- if (!valueChanged.value) {- return false;- }- if (scanIntervalInputRef.value) {- const scanIntervalInput = scanIntervalInputRef.value;- if (!scanIntervalInput.validate()) {- return false;- }- }- if (basicInfo.value.engine === Engine.SPANNER) {- if (!isValidSpannerHost(adminDataSource.value.host)) {- return false;- }- if (readonlyDataSourceList.value.length > 0) {- if (- readonlyDataSourceList.value.some((ds) => !isValidSpannerHost(ds.host))- ) {- return false;- }- }- return !!basicInfo.value.title.trim();- }- if (basicInfo.value.engine === Engine.BIGQUERY) {- if (!adminDataSource.value.host) {- return false;- }- if (readonlyDataSourceList.value.length > 0) {- if (readonlyDataSourceList.value.some((ds) => !ds.host)) {- return false;- }- }- return !!basicInfo.value.title.trim();- }- return checkDataSource([- adminDataSource.value,- ...readonlyDataSourceList.value,- ]);-});--// getOriginalEditState returns the origin instance data including-// basic information, admin data source and read-only data source.-const getOriginalEditState = () => {- return {- basicInfo: extractBasicInfo(instance.value),- dataSources: extractDataSourceEditState(instance.value).dataSources,- };-};--const confirmContinueWithConnectionFailure = (message: string) => {- const d = defer<boolean>();- $d.warning({- title: t("common.warning"),- content: t("instance.unable-to-connect", [message]),- contentClass: "whitespace-pre-wrap",- style: "z-index: 100000",- negativeText: t("common.cancel"),- positiveText: t("common.continue-anyway"),- onNegativeClick: () => {- d.resolve(false);- },- onPositiveClick: () => {- d.resolve(true);- },- });- return d.promise;-};--const tryCreate = async () => {- const editingDS = adminDataSource.value;- const testResult = await testConnection(editingDS, /* silent */ true);- if (testResult.success) {- doCreate();- } else {- maybeOpenConnectionOptions(editingDS);- const confirmed = await confirmContinueWithConnectionFailure(- testResult.message- );- if (confirmed) {- doCreate();- }- }-};--const hasExternalSecretFeature = computed(() =>- subscriptionStore.hasFeature(PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER)-);-const checkExternalSecretFeature = (dataSources: DataSource[]) => {- if (hasExternalSecretFeature.value) {- return true;- }-- return dataSources.every((ds) => {- return !ds.externalSecret && !/^{{.+}}$/.test(ds.password);- });-};--const checkRODataSourceFeature = (instance: Instance) => {- // This is to- // - Disallow creating any new RO data sources- // - Disallow updating any existed RO data sources- // if feature is not available.-- // Early pass if the feature is available.- if (hasReadonlyReplicaFeature.value) {- return true;- }-- if (readonlyDataSourceList.value.length === 0) {- // Not creating or editing any RO data source- return true;- }-- const checkOne = (ds: EditDataSource) => {- if (ds.pendingCreate) {- // Disallowed to create any new RO data sources- return false;- } else {- const editing = extractDataSourceFromEdit(instance.engine, ds);- const original = instance.dataSources.find((d) => d.id === ds.id);- if (original) {- const updateMask = calcDataSourceUpdateMask(editing, original, ds);- // Disallowed to update any existed RO data source- if (updateMask.length > 0) {- return false;- }- }- }- return true;- };- // Need to check all RO data sources- return readonlyDataSourceList.value.every(checkOne);-};--const hasConfiguredConnectionOptions = (ds: EditDataSource): boolean => {- const hasExtraParameters =- Object.keys(ds.extraConnectionParameters ?? {}).length > 0;- const hasSslConfig = !!(ds.useSsl || ds.sslCa || ds.sslCert || ds.sslKey);- const hasSshConfig = !!(- ds.sshHost ||- ds.sshPort ||- ds.sshUser ||- ds.sshPassword ||- ds.sshPrivateKey- );-- return hasExtraParameters || hasSslConfig || hasSshConfig;-};--const maybeOpenConnectionOptions = (ds: EditDataSource) => {- if (!hasConfiguredConnectionOptions(ds)) {- return;- }- events.emit("show-connection-options");-};--// We will also create the database * denoting all databases-// and its RW data source. The username, password is actually-// stored in that data source object instead of in the instance self.-// Conceptually, data source is the proper place to store connection info (thinking of DSN)-const doCreate = async () => {- if (!isCreating.value) {- return;- }-- if (!checkExternalSecretFeature(pendingCreateInstance.value.dataSources)) {- missingFeature.value = PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER;- return;- }-- state.value.isRequesting = true;- try {- const createdInstance = await instanceV1Store.createInstance(- pendingCreateInstance.value- );- if (props.onCreated) {- props.onCreated(createdInstance);- } else {- router.push(`/${createdInstance.name}`);- events.emit("dismiss");- }-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-created-instance-createdinstance-name", [- createdInstance.title,- ]),- });- } finally {- state.value.isRequesting = false;- }-};--const updateEditState = (instance: Instance) => {- basicInfo.value = extractBasicInfo(instance);- const updatedEditState = extractDataSourceEditState(instance);- dataSourceEditState.value.dataSources = updatedEditState.dataSources;- if (- updatedEditState.dataSources.findIndex(- (ds) => ds.id === dataSourceEditState.value.editingDataSourceId- ) < 0- ) {- // The original selected data source id is no-longer in the latest data source list- dataSourceEditState.value.editingDataSourceId =- updatedEditState.editingDataSourceId;- }-};--const doUpdate = async () => {- const inst = instance.value;- if (!inst) {- return;- }- if (!checkRODataSourceFeature(inst)) {- missingFeature.value = PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION;- return;- }-- if (!checkExternalSecretFeature([adminDataSource.value])) {- missingFeature.value = PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER;- return;- }-- if (- !checkExternalSecretFeature([- adminDataSource.value,- ...readonlyDataSourceList.value,- ])- ) {- missingFeature.value = PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER;- return;- }-- // When clicking **Update** we may have more than one thing to do (if needed)- // 1. Patch the instance itself.- // 2. Update the admin datasource.- // 3. Create OR update read-only data source(s).-- const pendingRequestRunners: (() => Promise<unknown>)[] = [];-- const maybeQueueUpdateInstanceBasicInfo = () => {- const currentLabels = convertKVListToLabels(labelKVList.value, false);- const instancePatch = create(InstanceSchema, {- ...instance,- ...basicInfo.value,- labels: currentLabels,- });- const updateMask: string[] = [];- if (instancePatch.title !== inst.title) {- updateMask.push("title");- }- if (instancePatch.externalLink !== inst.externalLink) {- updateMask.push("external_link");- }- if (instancePatch.activation !== inst.activation) {- updateMask.push("activation");- }- if (instancePatch.environment !== inst.environment) {- updateMask.push("environment");- }- if (- Number(instancePatch.syncInterval?.seconds || 0n) !==- Number(inst.syncInterval?.seconds || 0n)- ) {- updateMask.push("sync_interval");- }- if (!isEqual(instancePatch.syncDatabases, inst.syncDatabases)) {- updateMask.push("sync_databases");- }- if (!isEqual(instancePatch.labels, inst.labels)) {- updateMask.push("labels");- }- if (updateMask.length === 0) {- return;- }- pendingRequestRunners.push(() =>- instanceV1Store.updateInstance(instancePatch, updateMask).then(() => {- if (updateMask.includes("sync_databases")) {- return refreshInstanceDatabases(instancePatch.name);- }- })- );- };- const refreshInstanceDatabases = async (instance: string) => {- await instanceV1Store.syncInstance(instance, true);- databaseStore.removeCacheByInstance(instance);- };- /**- * @returns true if blocked by connection testing failure- */- const maybeQueueUpdateDataSource = async (- editing: DataSource,- original: DataSource | undefined,- editState: EditDataSource- ) => {- if (!original) return;- const updateMask = calcDataSourceUpdateMask(editing, original, editState);- if (updateMask.length === 0) {- return;- }- const testResult = await testConnection(editState, /* silent */ true);- if (!testResult.success) {- maybeOpenConnectionOptions(editState);- const continueAnyway = await confirmContinueWithConnectionFailure(- testResult.message- );- if (!continueAnyway) {- return true;- }- }-- pendingRequestRunners.push(() =>- instanceV1Store.updateDataSource({- instance: inst.name,- dataSource: editing,- updateMask,- })- );- };- const maybeQueueUpdateAdminDataSource = async () => {- const original = inst.dataSources.find(- (ds) => ds.type === DataSourceType.ADMIN- );- const editing = extractDataSourceFromEdit(- inst.engine,- adminDataSource.value- );- return await maybeQueueUpdateDataSource(- editing,- original,- adminDataSource.value- );- };- /**- * @returns true if blocked by connection testing failure- */- const maybeQueueUpsertReadonlyDataSources = async () => {- if (readonlyDataSourceList.value.length === 0) {- // Nothing to do, don't block- return false;- }- // Upsert readonly data sources one by one- for (let i = 0; i < readonlyDataSourceList.value.length; i++) {- const editing = readonlyDataSourceList.value[i];- const patch = extractDataSourceFromEdit(inst.engine, editing);- if (editing.pendingCreate) {- const testResult = await testConnection(editing, /* silent */ true);- if (!testResult.success) {- maybeOpenConnectionOptions(editing);- const continueAnyway = await confirmContinueWithConnectionFailure(- testResult.message- );- if (!continueAnyway) {- return true;- }- }-- pendingRequestRunners.push(() =>- instanceV1Store.createDataSource({- instance: inst.name,- dataSource: patch,- })- );- } else {- const original = inst.dataSources.find((ds) => ds.id === editing.id);- const blocked = await maybeQueueUpdateDataSource(- patch,- original,- editing- );- if (blocked) {- return true;- }- }- }- };-- // prepare pending request runners- await maybeQueueUpdateInstanceBasicInfo();- if (await maybeQueueUpdateAdminDataSource()) {- // blocked- return;- }- if (await maybeQueueUpsertReadonlyDataSources()) {- // blocked- return;- }-- if (pendingRequestRunners.length === 0) {- return;- }-- state.value.isRequesting = true;- try {- // Send requests one-by-one- for (let i = 0; i < pendingRequestRunners.length; i++) {- const runner = pendingRequestRunners[i];- await runner();- }-- const updatedInstance = instanceV1Store.getInstanceByName(inst.name);- updateEditState(updatedInstance);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-updated-instance-instance-name", [- updatedInstance.title,- ]),- });-- if (props.onUpdated) {- props.onUpdated(updatedInstance);- }- } finally {- state.value.isRequesting = false;- }-};--const testConnectionForCurrentEditingDS = async () => {- const editingDS = editingDataSource.value;- if (!editingDS) return;- const testResult = await testConnection(editingDS, /* !silent */ false);- if (!testResult.success) {- maybeOpenConnectionOptions(editingDS);- }-};--const cancel = () => {- events.emit("dismiss");-};-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vue b/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vuedeleted file mode 100644index e971d3a0a0..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/CreateDataSourceExample.vue+++ /dev/null@@ -1,584 +0,0 @@-<template>- <div- v-if="grantStatement"- class="w-full flex flex-col justify-start"- :class="props.className"- >- <p class="w-full text-sm text-gray-500">- <template v-if="isEngineUsingSQL">- {{- props.dataSourceType === DataSourceType.ADMIN- ? $t("instance.sentence.create-admin-user")- : $t("instance.sentence.create-readonly-user")- }}- </template>- <template v-else>- {{- props.dataSourceType === DataSourceType.ADMIN- ? $t("instance.sentence.create-admin-user-non-sql")- : $t("instance.sentence.create-readonly-user-non-sql")- }}- </template>- <span- v-if="!props.createInstanceFlag"- class="normal-link select-none ml-1"- @click="toggleCreateUserExample"- >- {{ $t("instance.show-how-to-create") }}- </span>- </p>- <div v-if="state.showCreateUserExample" class="text-sm text-main">- <template- v-if="- props.engine === Engine.MYSQL ||- props.engine === Engine.TIDB ||- props.engine === Engine.OCEANBASE- "- >- <i18n-t- v-if="- authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- tag="span"- keypath="instance.sentence.google-cloud-sql.mysql.template"- >- <template #user>- <span class="font-semibold">- {{ userName }}- </span>- </template>- </i18n-t>- <i18n-t- v-else-if="- authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- "- tag="span"- keypath="instance.sentence.aws-rds.mysql.template"- >- <template #user>- <span class="font-semibold">- {{ userName }}- </span>- </template>- </i18n-t>- <i18n-t- v-else- tag="span"- keypath="instance.sentence.create-user-example.mysql.template"- >- <template #user>- <span class="font-semibold">- {{ userName }}- </span>- </template>- <template #password>- <span class="text-red-600"> YOUR_DB_PWD </span>- </template>- </i18n-t>- </template>- <template v-else-if="props.engine === Engine.CLICKHOUSE">- <i18n-t- tag="p"- keypath="instance.sentence.create-user-example.clickhouse.template"- >- <template #user>- <span class="font-semibold">{{ userName }}</span>- </template>- <template #password>- <span class="text-red-600">YOUR_DB_PWD</span>- </template>- <template #link>- <a- class="normal-link"- href="https://clickhouse.com/docs/en/operations/access-rights/#access-control-usage"- target="__blank"- >- {{- $t(- "instance.sentence.create-user-example.clickhouse.sql-driven-workflow"- )- }}- </a>- </template>- </i18n-t>- </template>- <template v-else-if="props.engine === Engine.POSTGRES">- <BBAttention class="my-2" type="warning">- {{ $t("instance.sentence.create-user-example.postgresql.warn") }}- </BBAttention>- <i18n-t- v-if="- authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- tag="p"- keypath="instance.sentence.google-cloud-sql.postgresql.template"- >- <template #user>- <span class="font-semibold">- {{ userName }}- </span>- </template>- </i18n-t>- <i18n-t- v-else-if="- authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- "- tag="p"- keypath="instance.sentence.aws-rds.postgresql.template"- >- <template #user>- <span class="font-semibold">- {{ userName }}- </span>- </template>- </i18n-t>- <i18n-t- v-else- tag="p"- keypath="instance.sentence.create-user-example.postgresql.template"- >- <template #user>- <span class="font-semibold">{{ userName }}</span>- </template>- <template #password>- <span class="text-red-600">YOUR_DB_PWD</span>- </template>- </i18n-t>- </template>- <template v-else-if="props.engine === Engine.SNOWFLAKE">- <i18n-t- tag="p"- keypath="instance.sentence.create-user-example.snowflake.template"- >- <template #user>- <span class="font-semibold">{{ userName }}</span>- </template>- <template #password>- <span class="text-red-600">YOUR_DB_PWD</span>- </template>- <template #warehouse>- <span class="text-red-600">YOUR_COMPUTE_WAREHOUSE</span>- </template>- </i18n-t>- </template>- <template v-else-if="props.engine === Engine.REDIS">- <i18n-t- tag="p"- keypath="instance.sentence.create-user-example.redis.template"- >- <template #user>- <span class="font-semibold">{{ userName }}</span>- </template>- <template #password>- <span class="text-red-600"> YOUR_DB_PWD </span>- </template>- </i18n-t>- <!-- TODO(xz): add a "detailed guide" link to docs here -->- </template>- <div class="mt-2 flex flex-row">- <NConfigProvider- class="flex-1 min-w-0 w-full inline-flex items-center px-3 py-2 border border-r border-control-border bg-gray-50 sm:text-sm whitespace-pre-line rounded-l-[3px]"- :hljs="hljs"- >- <NCode- word-wrap- :language="languageOfEngineV1(engine)"- :code="grantStatement"- />- </NConfigProvider>- <div- class="flex items-center -ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light disabled:text-gray-300 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-50 focus:ring-control focus:outline-hidden focus-visible:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed rounded-r-[3px]"- >- <CopyButton :content="grantStatement" />- </div>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import hljs from "highlight.js/lib/core";-import { NCode, NConfigProvider } from "naive-ui";-import { computed, reactive } from "vue";-import { BBAttention } from "@/bbkit";-import { CopyButton } from "@/components/v2";-import {- DATASOURCE_ADMIN_USER_NAME,- DATASOURCE_READONLY_USER_NAME,- languageOfEngineV1,-} from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- DataSource_AuthenticationType,- DataSourceType,-} from "@/types/proto-es/v1/instance_service_pb";--interface LocalState {- showCreateUserExample: boolean;-}--const props = withDefaults(- defineProps<{- className?: string;- createInstanceFlag: boolean;- engine: Engine;- dataSourceType: DataSourceType;- authenticationType: DataSource_AuthenticationType;- }>(),- {- className: "",- createInstanceFlag: false,- engine: Engine.MYSQL,- dataSourceType: DataSourceType.ADMIN,- }-);--const state = reactive<LocalState>({- showCreateUserExample: props.createInstanceFlag,-});--const isEngineUsingSQL = computed(() => {- return languageOfEngineV1(props.engine) === "sql";-});--const userName = computed(() => {- return props.dataSourceType === DataSourceType.ADMIN- ? DATASOURCE_ADMIN_USER_NAME- : DATASOURCE_READONLY_USER_NAME;-});--const grantStatement = computed(() => {- if (props.dataSourceType === DataSourceType.ADMIN) {- const createUserStatement = `CREATE USER ${DATASOURCE_ADMIN_USER_NAME}@'%' IDENTIFIED BY 'YOUR_DB_PWD';`;- switch (props.engine) {- case Engine.MYSQL:- if (- props.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- ) {- return `GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- } else if (- props.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- ) {- return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME}@'%' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';\n\nALTER USER '${DATASOURCE_ADMIN_USER_NAME}'@'%' REQUIRE SSL;\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- }- // RELOAD, LOCK TABLES: enables use of explicit LOCK TABLES statements for backups.- // REPLICATION CLIENT: enables use of the SHOW MASTER STATUS, SHOW SLAVE STATUS, and SHOW BINARY LOGS statements.- // REPLICATION SLAVE: use of the SHOW SLAVE HOSTS, SHOW RELAYLOG EVENTS, and SHOW BINLOG EVENTS statements. This privilege is also required to use the mysqlbinlog options --read-from-remote-server (-R) and --read-from-remote-master.- // REPLICATION_APPLIER: execute the internal-use BINLOG statements used by mysqlbinlog.- // SESSION_VARIABLES_ADMIN: use of the SET sql_log_bin statements during PITR.- return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- case Engine.TIDB:- return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nLOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- case Engine.MARIADB:- return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- case Engine.OCEANBASE:- return `${createUserStatement}\n\nGRANT ALTER, CREATE, CREATE VIEW, DELETE, DROP, INDEX, INSERT, \nPROCESS, SELECT, SHOW DATABASES, SHOW VIEW, UPDATE, USAGE, \nREPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;- case Engine.CLICKHOUSE:- return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALL ON *.* TO ${DATASOURCE_ADMIN_USER_NAME} WITH GRANT OPTION;`;- case Engine.SNOWFLAKE:- return `-- Option 1: grant ACCOUNTADMIN role--CREATE OR REPLACE USER ${DATASOURCE_ADMIN_USER_NAME} PASSWORD = 'YOUR_DB_PWD'-DEFAULT_ROLE = "ACCOUNTADMIN"-DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';--GRANT ROLE "ACCOUNTADMIN" TO USER ${DATASOURCE_ADMIN_USER_NAME};---- Option 2: grant more granular privileges--CREATE OR REPLACE ROLE BYTEBASE;---- If using non-enterprise edition, the following commands may encounter error likes 'Unsupported feature GRANT/REVOKE APPLY TAG', you can skip those unsupported GRANTs.--- Grant the least privileges required by Bytebase--GRANT CREATE DATABASE, EXECUTE TASK, IMPORT SHARE, APPLY MASKING POLICY, APPLY ROW ACCESS POLICY, APPLY TAG ON ACCOUNT TO ROLE BYTEBASE;--GRANT IMPORTED PRIVILEGES ON DATABASE SNOWFLAKE TO ROLE BYTEBASE;--GRANT USAGE ON WAREHOUSE "YOUR_COMPUTE_WAREHOUSE" TO ROLE BYTEBASE;--CREATE OR REPLACE USER BYTEBASE- PASSWORD = 'YOUR_PWD'- DEFAULT_ROLE = "BYTEBASE"- DEFAULT_WAREHOUSE = "YOUR_COMPUTE_WAREHOUSE";--GRANT ROLE "BYTEBASE" TO USER BYTEBASE;--GRANT ROLE "BYTEBASE" TO ROLE SYSADMIN;---- For each database to be managed by Bytebase, you need to grant the following privileges--GRANT ALL PRIVILEGES ON DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;---- Then, grant the required schema object privileges on the database to the Bytebase role-GRANT ALL PRIVILEGES ON ALL EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;---- ALERT and POLICY are the features in Snowflake Enterprise Edition, you can skip those GRANTs if you are using standard edition.-GRANT ALL PRIVILEGES ON ALL ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;--GRANT ALL PRIVILEGES ON ALL SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-GRANT ALL PRIVILEGES ON FUTURE SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;---- PIPE are not allowed to be bulk granted, you need to grant them one by one.-GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;-`;- case Engine.POSTGRES:- if (- props.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- ) {- return `GRANT pg_write_all_data TO "${DATASOURCE_ADMIN_USER_NAME}@{project-id}.iam";---- If you need to create databases via Bytebase-ALTER USER "${DATASOURCE_ADMIN_USER_NAME}@{project-id}.iam" WITH CREATEDB;`;- } else if (- props.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- ) {- return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME};--GRANT rds_iam TO ${DATASOURCE_ADMIN_USER_NAME};--GRANT pg_write_all_data TO ${DATASOURCE_ADMIN_USER_NAME};---- If you need to create databases via Bytebase-ALTER USER ${DATASOURCE_ADMIN_USER_NAME} WITH CREATEDB;`;- }- return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER ${DATASOURCE_ADMIN_USER_NAME} WITH SUPERUSER;`;- case Engine.REDSHIFT:- return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} WITH PASSWORD 'YOUR_DB_PWD' CREATEUSER CREATEDB;`;- case Engine.MONGODB:- return `use admin;-db.createUser({- user: "${DATASOURCE_ADMIN_USER_NAME}",- pwd: "YOUR_DB_PWD",- roles: [- {role: "readWriteAnyDatabase", db: "admin"},- {role: "dbAdminAnyDatabase", db: "admin"},- {role: "userAdminAnyDatabase", db: "admin"}- ]-});-`;- case Engine.SPANNER:- return "";- case Engine.BIGQUERY:- return "";- case Engine.DYNAMODB:- return "";- case Engine.COCKROACHDB:- return "";- case Engine.REDIS:- return `ACL SETUSER ${DATASOURCE_ADMIN_USER_NAME} on >YOUR_DB_PWD +@all &*`;- case Engine.MSSQL:- return `-- If you use Cloud RDS, you need to checkout their documentation for setting up a semi-super privileged user.-CREATE LOGIN ${DATASOURCE_ADMIN_USER_NAME} WITH PASSWORD = 'YOUR_DB_PWD';-ALTER SERVER ROLE sysadmin ADD MEMBER ${DATASOURCE_ADMIN_USER_NAME};`;- case Engine.ORACLE:- return `-- If you use Cloud RDS, you need to checkout their documentation for setting up a semi-super privileged user.-CREATE USER ${DATASOURCE_ADMIN_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';-GRANT ALL PRIVILEGES TO ${DATASOURCE_ADMIN_USER_NAME};`;- }- } else {- const mysqlReadonlyStatement = `CREATE USER ${DATASOURCE_READONLY_USER_NAME}@'%' IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;- switch (props.engine) {- case Engine.MYSQL:- if (- props.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- ) {- return `GRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;- } else if (- props.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- ) {- return `CREATE USER ${DATASOURCE_READONLY_USER_NAME}@'%' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';\n\nALTER USER '${DATASOURCE_READONLY_USER_NAME}'@'%' REQUIRE SSL;\n\nGRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;- }- return mysqlReadonlyStatement;- case Engine.TIDB:- case Engine.OCEANBASE:- return mysqlReadonlyStatement;- case Engine.CLICKHOUSE:- return `CREATE USER ${DATASOURCE_READONLY_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SHOW TABLES, SELECT ON database.* TO ${DATASOURCE_READONLY_USER_NAME};`;- case Engine.SNOWFLAKE:- return `-- Option 1: grant ACCOUNTADMIN role--CREATE OR REPLACE USER ${DATASOURCE_READONLY_USER_NAME} PASSWORD = 'YOUR_DB_PWD'-DEFAULT_ROLE = "ACCOUNTADMIN"-DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';--GRANT ROLE "ACCOUNTADMIN" TO USER ${DATASOURCE_READONLY_USER_NAME};---- Option 2: grant more granular privileges--CREATE OR REPLACE ROLE BYTEBASE_READER;---- If using non-enterprise edition, the following commands may encounter error likes 'Unsupported feature GRANT/REVOKE APPLY TAG', you can skip those unsupported GRANTs.--- Grant the least privileges required by Bytebase--GRANT IMPORT SHARE TO ROLE BYTEBASE_READER;--GRANT IMPORTED PRIVILEGES ON DATABASE SNOWFLAKE TO ROLE BYTEBASE_READER;--GRANT USAGE ON WAREHOUSE "YOUR_COMPUTE_WAREHOUSE" TO ROLE BYTEBASE_READER;--CREATE OR REPLACE USER BYTEBASE_READER- PASSWORD = 'YOUR_PWD'- DEFAULT_ROLE = "BYTEBASE_READER"- DEFAULT_WAREHOUSE = "YOUR_COMPUTE_WAREHOUSE";--GRANT ROLE "BYTEBASE_READER" TO USER BYTEBASE_READER;--GRANT ROLE "BYTEBASE_READER" TO ROLE SYSADMIN;---- For each database to be managed by Bytebase, you need to grant the following privileges--GRANT ALL PRIVILEGES ON DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;---- Then, grant the required schema object privileges on the database to the Bytebase role-GRANT ALL PRIVILEGES ON ALL EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;---- ALERT and POLICY are the features in Snowflake Enterprise Edition, you can skip those GRANTs if you are using standard edition.-GRANT ALL PRIVILEGES ON ALL ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;--GRANT ALL PRIVILEGES ON ALL SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-GRANT ALL PRIVILEGES ON FUTURE SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;---- PIPE are not allowed to be bulk granted, you need to grant them one by one.-GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;-`;- case Engine.POSTGRES:- if (- props.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- ) {- return `GRANT pg_read_all_data TO "${DATASOURCE_READONLY_USER_NAME}@{project-id}.iam";`;- } else if (- props.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM- ) {- return `CREATE USER ${DATASOURCE_READONLY_USER_NAME};\n\nGRANT rds_iam TO ${DATASOURCE_READONLY_USER_NAME};\n\nGRANT pg_read_all_data TO ${DATASOURCE_READONLY_USER_NAME};`;- }- return `CREATE USER ${DATASOURCE_READONLY_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nGRANT pg_read_all_data TO ${DATASOURCE_READONLY_USER_NAME};`;- case Engine.MONGODB:- return `use admin;-db.createUser({- user: "${DATASOURCE_READONLY_USER_NAME}",- pwd: passwordPrompt(),- roles: [- {role: "readAnyDatabase", db: "admin"}- ]-});- `;- case Engine.SPANNER:- return "";- case Engine.BIGQUERY:- return "";- case Engine.DYNAMODB:- return "";- case Engine.COCKROACHDB:- return "";- case Engine.REDIS:- return `ACL SETUSER ${DATASOURCE_READONLY_USER_NAME} on >YOUR_DB_PWD +@read &*`;- }- }- return ""; // fallback-});--const toggleCreateUserExample = () => {- state.showCreateUserExample = !state.showCreateUserExample;-};-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/CreateReadOnlyDataSourceTips.vue b/frontend/src/components/InstanceForm/DataSourceSection/CreateReadOnlyDataSourceTips.vuedeleted file mode 100644index 881f8ad43f..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/CreateReadOnlyDataSourceTips.vue+++ /dev/null@@ -1,31 +0,0 @@-<template>- <div- v-if="!isCreating && !hasReadOnlyDataSource && allowEdit"- class="mt-2 flex flex-row justify-start items-center bg-yellow-50 border-none rounded-lg p-2 px-3"- >- <heroicons-outline:exclamation- class="h-6 w-6 text-yellow-400 shrink-0 mr-1"- />- <span class="text-yellow-800 text-sm">- {{ $t("instance.no-read-only-data-source-warn-for-admin-dba") }}- </span>- <NButton- class="ml-4! text-sm"- @click.prevent="$emit('add-readonly-datasource')"- >- {{ $t("common.create") }}- </NButton>- </div>-</template>--<script setup lang="ts">-import { NButton } from "naive-ui";-import { useInstanceFormContext } from "../context";--defineEmits<{- (event: "add-readonly-datasource"): void;-}>();--const { isCreating, allowEdit, hasReadOnlyDataSource } =- useInstanceFormContext();-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/CredentialSourceForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/CredentialSourceForm.vuedeleted file mode 100644index 6ad519362a..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/CredentialSourceForm.vue+++ /dev/null@@ -1,436 +0,0 @@-<template>- <!-- eslint-disable vue/no-mutating-props -->- <div class="sm:col-span-3 sm:col-start-1">- <label for="credential-source" class="textlabel block">- {{ $t("instance.iam-extension.credential-source") }}- </label>- <NRadioGroup- v-model:value="credentialSource"- class="textlabel mt-2"- :disabled="!allowEdit"- >- <template v-for="option in iamExtensionOptions" :key="option.value">- <NTooltip- v-if="option.disabled"- :show-arrow="true"- trigger="hover"- >- <template #trigger>- <NRadio- :value="option.value"- :label="option.label"- :disabled="!allowEdit || option.disabled"- />- </template>- {{ $t("instance.iam-extension.saas-default-credential-restriction") }}- </NTooltip>- <NRadio- v-else- :value="option.value"- :label="option.label"- :disabled="!allowEdit"- />- </template>- </NRadioGroup>- <template v-if="credentialSource === 'specific-credential'">- <div- v-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AZURE_IAM- "- class="mt-4 sm:col-span-3 sm:col-start-1"- >- <label for="tenant-id" class="textlabel block mt-2">- {{ $t("instance.iam-extension.tenant-id") }}- </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'azureCredential'- ? dataSource.iamExtension.value- : {}- ).tenantId- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="''"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'azureCredential') {- dataSource.iamExtension.value.tenantId = val;- }- }- "- />- <label for="client-id" class="textlabel block mt-2">- {{ $t("instance.iam-extension.client-id") }}- </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'azureCredential'- ? dataSource.iamExtension.value- : {}- ).clientId- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="''"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'azureCredential') {- dataSource.iamExtension.value.clientId = val;- }- }- "- />- <label for="client-secret" class="textlabel block mt-2">- {{ $t("instance.iam-extension.client-secret") }}- </label>- <NInput- type="password"- show-password-on="click"- v-model:value="- (dataSource.iamExtension?.case === 'azureCredential'- ? dataSource.iamExtension.value- : {}- ).clientSecret- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('instance.type-or-paste-credentials-write-only')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'azureCredential') {- dataSource.iamExtension.value.clientSecret = val;- }- }- "- />- </div>- <div- v-else-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- class="mt-2 sm:col-span-3 sm:col-start-1"- >- <GcpCredentialInput- v-model:value="- (dataSource.iamExtension?.case === 'gcpCredential'- ? dataSource.iamExtension.value- : {}- ).content- "- />- </div>- <div- v-else-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AWS_RDS_IAM- "- class="mt-4 sm:col-span-3 sm:col-start-1"- >- <label class="textlabel block mt-2"> Access Key ID </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'awsCredential'- ? dataSource.iamExtension.value- : {}- ).accessKeyId- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('common.sensitive-placeholder')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'awsCredential') {- dataSource.iamExtension.value.accessKeyId = val;- }- }- "- />- <label class="textlabel block mt-2"> Secret Access Key </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'awsCredential'- ? dataSource.iamExtension.value- : {}- ).secretAccessKey- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('common.sensitive-placeholder')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'awsCredential') {- dataSource.iamExtension.value.secretAccessKey = val;- }- }- "- />- <label class="textlabel block mt-2"> Session Token </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'awsCredential'- ? dataSource.iamExtension.value- : {}- ).sessionToken- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('common.sensitive-placeholder')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'awsCredential') {- dataSource.iamExtension.value.sessionToken = val;- }- }- "- />- <label class="textlabel block mt-2">- {{ $t("instance.role-arn") }}- </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'awsCredential'- ? dataSource.iamExtension.value- : {}- ).roleArn- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('instance.role-arn-placeholder')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'awsCredential') {- dataSource.iamExtension.value.roleArn = val;- }- }- "- />- <div class="text-sm text-gray-500 mt-1">- {{ $t("instance.role-arn-description") }}- </div>- <label class="textlabel block mt-2">- {{ $t("instance.external-id") }}- </label>- <NInput- v-model:value="- (dataSource.iamExtension?.case === 'awsCredential'- ? dataSource.iamExtension.value- : {}- ).externalId- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('instance.external-id-placeholder')"- @update:value="- (val) => {- if (dataSource.iamExtension?.case === 'awsCredential') {- dataSource.iamExtension.value.externalId = val;- }- }- "- />- <div class="text-sm text-gray-500 mt-1">- {{ $t("instance.external-id-description") }}- </div>- </div>- </template>- <div- v-else-if="credentialSource === 'default'"- class="mt-1 sm:col-span-3 sm:col-start-1 textinfolabel leading-6! credential"- >- <span- v-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AZURE_IAM- "- >- Bytebase will read the credential from environment variables- <code class="code">AZURE_CLIENT_ID</code>/- <code class="code">AZURE_TENANT_ID</code>/- <code class="code">AZURE_CLIENT_SECRET</code>- or- <code class="code">AZURE_CLIENT_CERTIFICATE_PATH</code>, and fallback to- attached users in Azure VM- </span>- <span- v-else-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AWS_RDS_IAM- "- >- Bytebase will read the credential from environment variables- <code class="code">AWS_ACCESS_KEY_ID</code>/- <code class="code">AWS_SECRET_ACCESS_KEY</code>/- <code class="code">AWS_SESSION_TOKEN</code>, fallback to shared- credentials file <code class="code">~/.aws/credentials</code> or IAM- role in AWS ECS- </span>- <span- v-else-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- >- Bytebase will read the credential from environment variable- <code class="code">GOOGLE_APPLICATION_CREDENTIALS</code>, fallback to- the attached service account in GCP GCE- </span>- </div>- </div>-</template>--<script lang="tsx" setup>-/* eslint-disable vue/no-mutating-props */-import { create } from "@bufbuild/protobuf";-import { NInput, NRadio, NRadioGroup, NTooltip } from "naive-ui";-import { computed, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { useActuatorV1Store } from "@/store";-import {- DataSource_AuthenticationType,- DataSource_AWSCredentialSchema,- DataSource_AzureCredentialSchema,- DataSource_GCPCredentialSchema,-} from "@/types/proto-es/v1/instance_service_pb";-import type { EditDataSource } from "../common";-import GcpCredentialInput from "./GcpCredentialInput.vue";--type credentialSource = "default" | "specific-credential";--const props = defineProps<{- allowEdit: boolean;- dataSource: EditDataSource;-}>();--const credentialSource = ref<credentialSource>("default");-const actuatorStore = useActuatorV1Store();--const { t } = useI18n();--const isIAMAuthentication = computed(() => {- return (- props.dataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ||- props.dataSource.authenticationType ===- DataSource_AuthenticationType.AWS_RDS_IAM ||- props.dataSource.authenticationType ===- DataSource_AuthenticationType.AZURE_IAM- );-});--const isDefaultCredentialDisabled = computed(() => {- return actuatorStore.isSaaSMode && isIAMAuthentication.value;-});--const iamExtensionOptions = computed(() => {- return [- {- label: t("common.Default"),- value: "default",- disabled: isDefaultCredentialDisabled.value,- },- {- label: t("instance.iam-extension.specific-credential"),- value: "specific-credential",- },- ];-});--watch(- [- () => props.dataSource.iamExtension?.case === "azureCredential",- () => props.dataSource.iamExtension?.case === "awsCredential",- () => props.dataSource.iamExtension?.case === "gcpCredential",- ],- (credentials) => {- const newVal = credentials.some((c) => c === true)- ? "specific-credential"- : "default";- credentialSource.value = newVal;- },- { immediate: true, deep: true }-);--watch(- () => props.dataSource.authenticationType,- () => {- credentialSource.value = "default";- }-);--// Force specific credential in SaaS mode for IAM authentication-watch(- () => isDefaultCredentialDisabled.value,- (disabled) => {- if (disabled && credentialSource.value === "default") {- credentialSource.value = "specific-credential";- }- },- { immediate: true }-);--watch(- () => credentialSource.value,- (source) => {- switch (props.dataSource.authenticationType) {- case DataSource_AuthenticationType.AWS_RDS_IAM:- if (source === "default") {- props.dataSource.iamExtension = { case: undefined };- } else {- props.dataSource.iamExtension = {- case: "awsCredential",- value: create(- DataSource_AWSCredentialSchema,- props.dataSource.iamExtension?.case === "awsCredential"- ? props.dataSource.iamExtension.value- : {}- ),- };- }- break;- case DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM:- if (source === "default") {- props.dataSource.iamExtension = { case: undefined };- } else {- props.dataSource.iamExtension = {- case: "gcpCredential",- value: create(- DataSource_GCPCredentialSchema,- props.dataSource.iamExtension?.case === "gcpCredential"- ? props.dataSource.iamExtension.value- : {}- ),- };- }- break;- case DataSource_AuthenticationType.AZURE_IAM:- if (source === "default") {- props.dataSource.iamExtension = { case: undefined };- } else {- props.dataSource.iamExtension = {- case: "azureCredential",- value: create(- DataSource_AzureCredentialSchema,- props.dataSource.iamExtension?.case === "azureCredential"- ? props.dataSource.iamExtension.value- : {}- ),- };- }- break;- }- },- { immediate: true }-);-</script>--<style lang="postcss" scoped>-.credential :deep(.code) {- background-color: var(--color-gray-100);- padding: 0.25rem;- border-radius: 0.125rem;- margin-right: 0.25rem;-}-</style>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vuedeleted file mode 100644index bc4f9f9387..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue+++ /dev/null@@ -1,1675 +0,0 @@-<template>- <!-- eslint-disable vue/no-mutating-props -->- <div class="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3">- <template v-if="!optionsOnly">- <template- v-if="- basicInfo.engine !== Engine.SPANNER &&- basicInfo.engine !== Engine.BIGQUERY &&- basicInfo.engine !== Engine.DYNAMODB &&- basicInfo.engine !== Engine.DATABRICKS- "- >- <div- v-if="- basicInfo.engine === Engine.MYSQL ||- basicInfo.engine === Engine.POSTGRES ||- basicInfo.engine === Engine.COSMOSDB ||- basicInfo.engine === Engine.MSSQL ||- basicInfo.engine === Engine.ELASTICSEARCH- "- class="sm:col-span-3 sm:col-start-1"- >- <div class="flex items-center gap-x-2">- <NRadioGroup- v-model:value="dataSource.authenticationType"- class="textlabel"- :disabled="!allowEdit"- >- <NRadio- v-for="item in supportedAuthenticationTypes"- :key="item.value"- :value="item.value"- >- {{ item.label }}- </NRadio>- </NRadioGroup>- </div>- </div>- <div- v-else-if="basicInfo.engine === Engine.HIVE"- class="sm:col-span-3 sm:col-start-1"- >- <NRadioGroup- :value="hiveAuthentication"- class="textlabel"- :disabled="!allowEdit"- @update:value="onHiveAuthenticationChange"- >- <NRadio value="PASSWORD"> Plain Password </NRadio>- <NRadio value="KERBEROS"> Kerberos </NRadio>- </NRadioGroup>- </div>- <CreateDataSourceExample- v-if="!isCreating"- class-name="sm:col-span-3 border-none"- :create-instance-flag="false"- :engine="basicInfo.engine"- :data-source-type="dataSource.type"- :authentication-type="dataSource.authenticationType"- />- <template v-if="dataSource.saslConfig?.mechanism?.case === 'krbConfig'">- <div class="sm:col-span-3 sm:col-start-1">- <label class="textlabel block">- Principal- <RequiredStar />- </label>- <div class="mt-2 flex items-center gap-x-2">- <NInput- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.primary- : ''- "- :disabled="!allowEdit"- placeholder="primary"- @update:value="- (val) => {- if (dataSource.saslConfig?.mechanism?.case === 'krbConfig') {- dataSource.saslConfig.mechanism.value.primary = val;- }- }- "- />- <span>/</span>- <NInput- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.instance- : ''- "- :disabled="!allowEdit"- placeholder="instance, optional"- @update:value="- (val) => {- if (dataSource.saslConfig?.mechanism?.case === 'krbConfig') {- dataSource.saslConfig.mechanism.value.instance = val;- }- }- "- />- <span>@</span>- <NInput- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.realm- : ''- "- :disabled="!allowEdit"- placeholder="realm"- @update:value="- (val) => {- if (dataSource.saslConfig?.mechanism?.case === 'krbConfig') {- dataSource.saslConfig.mechanism.value.realm = val;- }- }- "- />- </div>- </div>- <div class="sm:col-span-3 sm:col-start-1">- <label class="textlabel block">- KDC- <RequiredStar />- </label>- <div class="flex items-center gap-x-2">- <div class="w-fit">- <NRadioGroup- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.kdcTransportProtocol- : 'tcp'- "- class="textlabel w-32"- :disabled="!allowEdit"- @update:value="- (val) => {- if (- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ) {- dataSource.saslConfig.mechanism.value.kdcTransportProtocol =- val;- }- }- "- >- <NRadio value="tcp"> TCP </NRadio>- <NRadio value="udp"> UDP </NRadio>- </NRadioGroup>- </div>- <NInput- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.kdcHost- : ''- "- :disabled="!allowEdit"- placeholder="KDC host"- @update:value="- (val) => {- if (dataSource.saslConfig?.mechanism?.case === 'krbConfig') {- dataSource.saslConfig.mechanism.value.kdcHost = val;- }- }- "- />- <span>:</span>- <NInput- :value="- dataSource.saslConfig?.mechanism?.case === 'krbConfig'- ? dataSource.saslConfig.mechanism.value.kdcPort- : ''- "- :disabled="!allowEdit"- placeholder="KDC port, optional"- :allow-input="onlyAllowNumber"- @update:value="- (val) => {- if (dataSource.saslConfig?.mechanism?.case === 'krbConfig') {- dataSource.saslConfig.mechanism.value.kdcPort = val;- }- }- "- />- </div>- </div>- <div class="sm:col-span-3 sm:col-start-1">- <label class="textlabel block">- Keytab File- <RequiredStar />- </label>- <NUpload :max="1" @change="handleKeytabUpload">- <NUploadDragger class="mt-3">- <span class="textinfolabel"- >Click or Drag your .keytab file here</span- >- </NUploadDragger>- </NUpload>- </div>- </template>- <template v-else>- <div- v-if="- dataSource.authenticationType !==- DataSource_AuthenticationType.AZURE_IAM- "- class="sm:col-span-3 sm:col-start-1"- >- <label for="username" class="textlabel flex items-center gap-x-1">- {{ $t("common.username") }}- <InfoTrigger- v-if="isCreating && infoPanel && hasAuthenticationInfo"- @click="openInfoPanel('authentication')"- />- </label>- <!-- For mysql, username can be empty indicating anonymous user.- But it's a very bad practice to use anonymous user for admin operation,- thus we make it REQUIRED here.-->- <NInput- v-model:value="dataSource.username"- class="mt-2 w-full max-w-[48rem]"- :disabled="!allowEdit"- :placeholder="- basicInfo.engine === Engine.CLICKHOUSE ? $t('common.default') : ''- "- />- </div>- <CredentialSourceForm- v-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AZURE_IAM ||- dataSource.authenticationType ===- DataSource_AuthenticationType.AWS_RDS_IAM ||- dataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- :data-source="dataSource"- :allow-edit="allowEdit"- />- <div- v-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.AWS_RDS_IAM- "- class="sm:col-span-3 sm:col-start-1"- >- <label for="username" class="textlabel block">- {{ $t("instance.database-region") }}- <RequiredStar />- </label>- <NInput- v-model:value="dataSource.region"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="'database region, for example, us-east-1'"- />- </div>- <div- v-if="- dataSource.authenticationType ===- DataSource_AuthenticationType.PASSWORD- "- class="sm:col-span-3 sm:col-start-1"- >- <div v-if="!hideAdvancedFeatures" class="mb-4">- <NRadioGroup- class="textlabel"- :value="state.passwordType"- :disabled="!allowEdit"- @update:value="changeSecretType"- >- <NRadio- :value="- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED- "- >- {{ $t("instance.password-type.password") }}- </NRadio>- <NRadio :value="DataSourceExternalSecret_SecretType.VAULT_KV_V2">- <div class="flex items-center gap-x-1">- {{ $t("instance.password-type.external-secret-vault") }}- <FeatureBadge- :feature="PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER"- />- </div>- </NRadio>- <NRadio- :value="DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER"- >- <div class="flex items-center gap-x-1">- {{ $t("instance.password-type.external-secret-aws") }}- <FeatureBadge- :feature="PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER"- />- </div>- </NRadio>- <NRadio- :value="DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER"- >- <div class="flex items-center gap-x-1">- {{ $t("instance.password-type.external-secret-gcp") }}- <FeatureBadge- :feature="PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER"- />- </div>- </NRadio>- <NRadio- :value="DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT"- >- <div class="flex items-center gap-x-1">- {{ $t("instance.password-type.external-secret-azure") }}- <FeatureBadge- :feature="PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER"- />- </div>- </NRadio>- </NRadioGroup>- <LearnMoreLink- url="https://docs.bytebase.com/get-started/connect/overview#secret-manager-integration"- class="text-sm"- />- </div>- <div- v-if="- state.passwordType ===- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED- "- >- <label class="textlabel block">- {{ $t("common.password") }}- </label>- <div class="mt-2">- <NCheckbox- v-if="!isCreating && allowUsingEmptyPassword"- :size="'small'"- :checked="dataSource.useEmptyPassword"- :disabled="!allowEdit"- @update:checked="toggleUseEmptyPassword"- >- {{ $t("instance.no-password") }}- </NCheckbox>- <NInput- type="password"- show-password-on="click"- class="w-full max-w-[48rem]"- :input-props="{ autocomplete: 'off' }"- :placeholder="- dataSource.useEmptyPassword- ? $t('instance.no-password')- : $t('instance.password-write-only')- "- :disabled="!allowEdit || dataSource.useEmptyPassword"- :value="- dataSource.useEmptyPassword ? '' : dataSource.updatedPassword- "- @update:value="dataSource.updatedPassword = $event.trim()"- />- </div>- </div>- <div- v-else-if="dataSource.externalSecret"- class="flex flex-col gap-y-4"- >- <div- v-if="- state.passwordType ===- DataSourceExternalSecret_SecretType.VAULT_KV_V2- "- class="flex flex-col gap-y-4"- >- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{ $t("instance.external-secret-vault.vault-url") }}- <RequiredStar />- </label>- <BBTextField- v-model:value="dataSource.externalSecret.url"- :required="true"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('instance.external-secret-vault.vault-url')"- />- </div>- <div class="sm:col-span-2 sm:col-start-1 flex flex-col gap-y-2">- <label class="textlabel block">- {{- $t("instance.external-secret-vault.vault-auth-type.self")- }}- </label>- <NRadioGroup- class="textlabel"- :value="dataSource.externalSecret.authType"- @update:value="changeExternalSecretAuthType"- >- <NRadio :value="DataSourceExternalSecret_AuthType.TOKEN">- {{- $t(- "instance.external-secret-vault.vault-auth-type.token.self"- )- }}- </NRadio>- <NRadio- :value="DataSourceExternalSecret_AuthType.VAULT_APP_ROLE"- >- {{- $t(- "instance.external-secret-vault.vault-auth-type.approle.self"- )- }}- </NRadio>- </NRadioGroup>- </div>- <div- v-if="- dataSource.externalSecret.authType ===- DataSourceExternalSecret_AuthType.TOKEN- "- class="sm:col-span-2 sm:col-start-1"- >- <label class="textlabel block">- {{- $t(- "instance.external-secret-vault.vault-auth-type.token.self"- )- }}- <RequiredStar />- </label>- <div class="flex gap-x-2 text-sm">- <div class="textinfolabel">- {{- $t(- "instance.external-secret-vault.vault-auth-type.token.tips"- )- }}- </div>- <LearnMoreLink- url="https://developer.hashicorp.com/vault/tutorials/operations/generate-root"- class="ml-1 text-sm"- />- </div>- <BBTextField- :value="- dataSource.externalSecret?.authOption?.case === 'token'- ? dataSource.externalSecret.authOption.value- : ''- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="secretInputPlaceholder"- :required="isCreating"- @update:value="- (val: string) => {- const ds = dataSource;- if (ds.externalSecret) {- ds.externalSecret.authOption = {- case: 'token',- value: val,- };- }- }- "- />- </div>- <div- v-else-if="- dataSource.externalSecret?.authOption?.case === 'appRole'- "- class="flex flex-col gap-y-4"- >- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{- $t(- "instance.external-secret-vault.vault-auth-type.approle.role-id"- )- }}- <RequiredStar />- </label>- <BBTextField- :value="- dataSource.externalSecret?.authOption?.case === 'appRole'- ? dataSource.externalSecret.authOption.value.roleId- : ''- "- :required="isCreating"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="`${$t(- 'instance.external-secret-vault.vault-auth-type.approle.role-id'- )} - ${$t('common.write-only')}`"- @update:value="- (val: string) => {- const ds = dataSource;- if (ds.externalSecret?.authOption?.case === 'appRole') {- ds.externalSecret.authOption.value.roleId = val;- }- }- "- />- </div>- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{- $t(- "instance.external-secret-vault.vault-auth-type.approle.secret-id"- )- }}- <RequiredStar />- </label>- <i18n-t- tag="div"- keypath="instance.external-secret-vault.vault-auth-type.approle.secret-tips"- class="textinfolabel text-sm"- >- <template #learn_more>- <LearnMoreLink- url="https://developer.hashicorp.com/vault/tutorials/auth-methods/approle"- class="ml-1 text-sm"- />- </template>- </i18n-t>- <NRadioGroup- :value="- dataSource.externalSecret?.authOption?.case === 'appRole'- ? dataSource.externalSecret.authOption.value.type- : DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN- "- class="textlabel my-1"- :disabled="!allowEdit"- @update:value="- (val) => {- if (- dataSource.externalSecret?.authOption?.case ===- 'appRole'- ) {- dataSource.externalSecret.authOption.value.type = val;- }- }- "- >- <NRadio- :value="- DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN- "- >- {{- $t(- "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text"- )- }}- </NRadio>- <NRadio- :value="- DataSourceExternalSecret_AppRoleAuthOption_SecretType.ENVIRONMENT- "- >- {{- $t(- "instance.external-secret-vault.vault-auth-type.approle.secret-env-name"- )- }}- </NRadio>- </NRadioGroup>- <BBTextField- :value="- dataSource.externalSecret?.authOption?.case === 'appRole'- ? dataSource.externalSecret.authOption.value.secretId- : ''- "- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="secretInputPlaceholder"- @update:value="- (val: string) => {- const ds = dataSource;- if (ds.externalSecret?.authOption?.case === 'appRole') {- ds.externalSecret.authOption.value.secretId = val;- }- }- "- />- </div>- </div>- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{ $t("instance.external-secret-vault.vault-tls-config") }}- </label>- <SslCertificateFormV1- v-model:verify="verifyVaultTls"- v-model:ca="dataSource.externalSecret.vaultSslCa"- v-model:cert="dataSource.externalSecret.vaultSslCert"- v-model:private-key="dataSource.externalSecret.vaultSslKey"- :disabled="!allowEdit"- :show-tooltip="false"- :show-key-field="true"- :show-cert-field="true"- :verify-label="- $t(- 'instance.external-secret-vault.verify-vault-certificate'- )- "- :ca-label="$t('instance.external-secret-vault.vault-ca-cert')"- :cert-label="- $t('instance.external-secret-vault.vault-client-cert')- "- :key-label="- $t('instance.external-secret-vault.vault-client-key')- "- />- </div>- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{- $t(- "instance.external-secret-vault.vault-secret-engine-name"- )- }}- <RequiredStar />- </label>- <div class="flex gap-x-2 text-sm textinfolabel">- {{- $t(- "instance.external-secret-vault.vault-secret-engine-tips"- )- }}- </div>- <BBTextField- v-model:value="dataSource.externalSecret.engineName"- :required="true"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="- $t(- 'instance.external-secret-vault.vault-secret-engine-name'- )- "- />- </div>- </div>- <div- v-if="- state.passwordType ===- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT- "- class="flex flex-col gap-y-4"- >- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{ $t("instance.external-secret-azure.vault-url") }}- <RequiredStar />- </label>- <div class="flex gap-x-2 text-sm textinfolabel">- {{ $t("instance.external-secret-azure.vault-url-tips") }}- </div>- <BBTextField- v-model:value="dataSource.externalSecret.url"- :required="true"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('instance.external-secret-azure.vault-url')"- />- </div>- </div>- <div class="sm:col-span-2 sm:col-start-1">- <label class="textlabel block">- {{ secretNameLabel }}- <RequiredStar />- </label>- <div- v-if="- state.passwordType ===- DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER- "- class="flex gap-x-2 text-sm textinfolabel"- >- {{ $t("instance.external-secret-gcp.secret-name-tips") }}- </div>- <div- v-else-if="- state.passwordType ===- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT- "- class="flex gap-x-2 text-sm textinfolabel"- >- {{ $t("instance.external-secret-azure.secret-name-tips") }}- </div>- <BBTextField- v-model:value="dataSource.externalSecret.secretName"- :required="true"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="secretNameLabel"- />- </div>- <div- v-if="- state.passwordType !==- DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER &&- state.passwordType !==- DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT- "- class="sm:col-span-2 sm:col-start-1"- >- <label class="textlabel block">- {{ secretKeyLabel }}- <RequiredStar />- </label>- <BBTextField- v-model:value="dataSource.externalSecret.passwordKeyName"- :required="true"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="secretKeyLabel"- />- </div>- </div>-- <template- v-if="- basicInfo.engine === Engine.REDIS &&- dataSource.redisType === DataSource_RedisType.SENTINEL- "- >- <div class="mt-2">- <label class="textlabel"> Master Name <RequiredStar /></label>- <NInput- v-model:value="dataSource.masterName"- class="mt-1 w-full"- :disabled="!allowEdit"- :placeholder="''"- />- </div>- <div class="mt-2">- <label class="textlabel"> Master Username </label>- <NInput- v-model:value="dataSource.masterUsername"- class="mt-1 w-full"- :disabled="!allowEdit"- :placeholder="''"- />- </div>- <div class="mt-2">- <label class="textlabel block"> Master Password </label>- <div class="mt-2">- <NCheckbox- v-if="!isCreating && allowUsingEmptyPassword"- :size="'small'"- :checked="dataSource.useEmptyMasterPassword"- :disabled="!allowEdit"- @update:checked="toggleUseEmptyMasterPassword"- >- {{ $t("instance.no-password") }}- </NCheckbox>- <NInput- type="password"- show-password-on="click"- class="w-full"- :input-props="{ autocomplete: 'off' }"- :placeholder="- dataSource.useEmptyMasterPassword- ? $t('instance.no-password')- : $t('instance.password-write-only')- "- :disabled="!allowEdit || dataSource.useEmptyMasterPassword"- :value="- dataSource.useEmptyMasterPassword- ? ''- : dataSource.updatedMasterPassword- "- @update:value="- dataSource.updatedMasterPassword = $event.trim()- "- />- </div>- </div>- </template>- </div>- </template>- </template>- <template- v-if="- basicInfo.engine === Engine.SPANNER ||- basicInfo.engine === Engine.BIGQUERY- "- >- <NRadioGroup- v-model:value="dataSource.authenticationType"- class="textlabel"- :disabled="!allowEdit"- >- <NRadio- v-for="item in supportedAuthenticationTypes"- :key="item.value"- :value="item.value"- >- {{ item.label }}- </NRadio>- </NRadioGroup>- <CredentialSourceForm :data-source="dataSource" :allow-edit="allowEdit" />- </template>-- <template v-if="basicInfo.engine === Engine.ORACLE">- <OracleSIDAndServiceNameInput- v-model:sid="dataSource.sid"- v-model:service-name="dataSource.serviceName"- :allow-edit="allowEdit"- />- </template>-- <template v-if="basicInfo.engine === Engine.SNOWFLAKE">- <div class="sm:col-span-3 sm:col-start-1">- <div class="textlabel block">- {{ $t("data-source.ssh.private-key") }}- </div>- <div class="flex gap-x-2 text-sm">- <div class="textinfolabel">- {{ $t("data-source.snowflake-keypair-tip") }}- </div>- <LearnMoreLink- url="https://docs.snowflake.com/en/user-guide/key-pair-auth"- class="ml-1 text-sm"- />- </div>- <DroppableTextarea- v-model:value="dataSource.authenticationPrivateKey"- :resizable="false"- :disabled="!allowEdit"- class="w-full h-32 mt-2 whitespace-pre-wrap"- placeholder="-----BEGIN PRIVATE KEY------MIIEvQ...------END PRIVATE KEY-----"- :allow-edit="allowEdit"- />- </div>- <div class="sm:col-span-3 sm:col-start-1">- <div class="textlabel block">- {{ $t("data-source.private-key-passphrase") }}- </div>- <div class="textinfolabel text-sm">- {{ $t("data-source.private-key-passphrase-tip") }}- </div>- <NInput- v-model:value="dataSource.authenticationPrivateKeyPassphrase"- type="password"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('data-source.private-key-passphrase-placeholder')"- />- </div>- </template>-- <template v-if="basicInfo.engine === Engine.DATABRICKS">- <div>- <div class="textlabel black mt-2">- Warehouse ID- <RequiredStar />- </div>- <NInput- v-model:value="dataSource.warehouseId"- class="mt-2"- :disabled="!allowEdit"- />- </div>-- <div>- <div class="textlabel black mt-2">- Token- <RequiredStar />- </div>- <NInput- v-model:value="dataSource.authenticationPrivateKey"- class="mt-2 w-full"- :disabled="!allowEdit"- placeholder="personal access token"- />- </div>- </template>-- <template v-if="showAuthenticationDatabase">- <div class="sm:col-span-3 sm:col-start-1">- <div class="flex flex-row items-center gap-x-2">- <label for="authenticationDatabase" class="textlabel block">- {{ $t("instance.authentication-database") }}- </label>- </div>- <NInput- class="mt-2 w-full"- :input-props="{ autocomplete: 'off' }"- placeholder="admin"- :disabled="!allowEdit"- :value="dataSource.authenticationDatabase"- @update:value="dataSource.authenticationDatabase = $event.trim()"- />- </div>- </template>-- <template- v-if="- dataSource.type === DataSourceType.READ_ONLY &&- (hasReadonlyReplicaHost || hasReadonlyReplicaPort)- "- >- <div v-if="hasReadonlyReplicaHost" class="sm:col-span-3 sm:col-start-1">- <div class="flex flex-row items-center gap-x-2">- <label for="host" class="textlabel block">- {{ $t("data-source.read-replica-host") }}- </label>- </div>- <NInput- class="mt-2 w-full"- :input-props="{ autocomplete: 'off' }"- :value="dataSource.host"- :disabled="!allowEdit"- @update:value="handleHostInput"- />- </div>-- <div v-if="hasReadonlyReplicaPort" class="sm:col-span-3 sm:col-start-1">- <div class="flex flex-row items-center gap-x-2">- <label for="port" class="textlabel block">- {{ $t("data-source.read-replica-port") }}- </label>- </div>- <NInput- class="mt-2 w-full"- :input-props="{ autocomplete: 'off' }"- :value="dataSource.port"- :allow-input="onlyAllowNumber"- :disabled="!allowEdit"- @update:value="handlePortInput"- />- </div>- </template>-- <div v-if="showDatabase" class="sm:col-span-3 sm:col-start-1">- <label for="database" class="textlabel block">- {{ $t("common.database") }}- </label>- <NInput- v-model:value="dataSource.database"- class="mt-2 w-full"- :disabled="!allowEdit"- :placeholder="$t('common.database')"- />- </div>- </template>-- <template v-if="!hideOptions">- <div- v-if="- showSSL &&- dataSource.authenticationType ===- DataSource_AuthenticationType.PASSWORD- "- class="sm:col-span-3 sm:col-start-1"- >- <div- for="ssl"- class="flex items-center justify-start gap-x-2 textlabel"- >- {{ $t("data-source.ssl-connection") }}- <Switch- :text="true"- :value="dataSource.useSsl"- @update:value="handleUseSslChanged"- />- <InfoTrigger- v-if="isCreating && infoPanel && hasSslInfo"- @click="openInfoPanel('ssl')"- />- </div>- <template v-if="dataSource.useSsl">- <SslCertificateFormV1- v-if="dataSource.pendingCreate || dataSource.updateSsl"- class="pt-1!"- v-model:verify="dataSource.verifyTlsCertificate"- v-model:ca="dataSource.sslCa"- v-model:cert="dataSource.sslCert"- v-model:private-key="dataSource.sslKey"- :engine-type="basicInfo.engine"- :disabled="!allowEdit"- />- <NButton- v-else- class="mt-2!"- :disabled="!allowEdit"- @click.prevent="handleEditSSL"- >- {{ $t("common.edit") }} - {{ $t("common.write-only") }}- </NButton>- </template>- </div>-- <div- v-if="- !hideAdvancedFeatures &&- showSSH &&- dataSource.authenticationType ===- DataSource_AuthenticationType.PASSWORD- "- class="sm:col-span-3 sm:col-start-1"- >- <div class="flex flex-row items-center gap-x-1">- <label for="ssh" class="textlabel block">- {{ $t("data-source.ssh-connection") }}- </label>- <InfoTrigger- v-if="isCreating && infoPanel && hasSshInfo"- @click="openInfoPanel('ssh')"- />- </div>- <SshConnectionForm- :value="dataSource"- :instance="instance"- :disabled="!allowEdit"- @change="handleSSHChange"- />- </div>-- <div v-if="hasExtraParameters" class="sm:col-span-3 sm:col-start-1">- <div class="flex flex-row items-center justify-between">- <label class="textlabel block">- {{ $t("data-source.extra-params.self") }}- </label>- </div>- <div class="textinfolabel text-sm mt-1 mb-2">- {{ $t("data-source.extra-params.description") }}- </div>-- <!-- Add parameter form -->- <div- v-if="allowEdit"- class="flex mt-2 mb-2 gap-x-2 bg-gray-50 p-3 rounded-md"- >- <NInput- v-model:value="newParam.key"- class="w-full"- :placeholder="$t('instance.parameter-name-placeholder')"- />- <NInput- v-model:value="newParam.value"- class="w-full"- :placeholder="$t('instance.parameter-value-placeholder')"- />- <NButton- type="primary"- ghost- size="small"- :disabled="!newParam.key.trim()"- @click="addNewParameter"- >- Add- </NButton>- </div>-- <!-- Existing parameters -->- <div- v-for="(param, index) in extraConnectionParamsList"- :key="param.key"- class="flex mt-2 gap-x-2"- >- <NInput- class="w-full"- :value="param.key"- :disabled="!allowEdit"- placeholder="Parameter name"- @update:value="(v) => updateExtraConnectionParamKey(index, v)"- />- <NInput- class="w-full"- :value="param.value"- :disabled="!allowEdit"- placeholder="Parameter value"- @update:value="(v) => updateExtraConnectionParamValue(index, v)"- />- <NButton- v-if="allowEdit"- type="error"- secondary- size="small"- @click="removeExtraConnectionParam(index)"- title="Remove parameter"- >- Remove- </NButton>- </div>-- <!-- Show a message when there are no parameters -->- <div- v-if="extraConnectionParamsList.length === 0"- class="textinfolabel text-sm italic"- >- {{- allowEdit- ? $t("instance.no-params-yet-add-above")- : $t("instance.no-extra-params-configured")- }}- </div>- </div>- </template>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import {- NButton,- NCheckbox,- NInput,- NRadio,- NRadioGroup,- NUpload,- NUploadDragger,- type UploadFileInfo,-} from "naive-ui";-import { computed, inject, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBTextField } from "@/bbkit";-import { FeatureBadge } from "@/components/FeatureGuard";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import DroppableTextarea from "@/components/misc/DroppableTextarea.vue";-import RequiredStar from "@/components/RequiredStar.vue";-import { Switch } from "@/components/v2";-import type { DataSourceOptions } from "@/types/dataSource";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- DataSource_AuthenticationType,- DataSource_RedisType,- DataSourceExternalSecret_AppRoleAuthOption_SecretType,- DataSourceExternalSecret_AppRoleAuthOptionSchema,- DataSourceExternalSecret_AuthType,- DataSourceExternalSecret_SecretType,- DataSourceExternalSecretSchema,- DataSourceType,- KerberosConfigSchema,- SASLConfigSchema,-} from "@/types/proto-es/v1/instance_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { onlyAllowNumber } from "@/utils";-import type { EditDataSource } from "../common";-import { useInstanceFormContext } from "../context";-import InfoTrigger from "../InfoTrigger.vue";-import { hasInfoContent, type InfoSection } from "../info-content";-import CreateDataSourceExample from "./CreateDataSourceExample.vue";-import CredentialSourceForm from "./CredentialSourceForm.vue";-import OracleSIDAndServiceNameInput from "./OracleSIDAndServiceNameInput.vue";-import SshConnectionForm from "./SshConnectionForm.vue";-import SslCertificateFormV1 from "./SslCertificateFormV1.vue";--interface LocalState {- passwordType: DataSourceExternalSecret_SecretType;-}--interface ExtraConnectionParam {- key: string;- value: string;-}--const props = withDefaults(- defineProps<{- dataSource: EditDataSource;- hideOptions?: boolean;- optionsOnly?: boolean;- }>(),- {- hideOptions: false,- optionsOnly: false,- }-);--const {- instance,- specs,- isCreating,- allowEdit,- basicInfo,- adminDataSource,- hasReadonlyReplicaFeature,- missingFeature,- hideAdvancedFeatures,-} = useInstanceFormContext();--const infoPanel = inject<- | {- open: (section: InfoSection) => void;- close: () => void;- setEngine: (engine: Engine) => void;- }- | undefined->("infoPanel", undefined);--const openInfoPanel = (section: InfoSection) => {- if (!hasInfoContent(basicInfo.value.engine, section)) {- return;- }- infoPanel?.open(section);-};--const hasAuthenticationInfo = computed(() =>- hasInfoContent(basicInfo.value.engine, "authentication")-);-const hasSslInfo = computed(() =>- hasInfoContent(basicInfo.value.engine, "ssl")-);-const hasSshInfo = computed(() =>- hasInfoContent(basicInfo.value.engine, "ssh")-);--const {- showDatabase,- showSSL,- showSSH,- allowUsingEmptyPassword,- showAuthenticationDatabase,- hasReadonlyReplicaHost,- hasReadonlyReplicaPort,- hasExtraParameters,-} = specs;--const state = reactive<LocalState>({- passwordType: DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED,-});--// Use a simpler approach to track new parameters-const newParam = reactive({ key: "", value: "" });--// Helper computed to convert object to array for UI-const extraConnectionParamsList = computed<ExtraConnectionParam[]>(() => {- // Ensure we're using a non-null object for the params- const params = props.dataSource.extraConnectionParameters || {};-- // Convert to plain entries for display- return Object.entries(params).map(([key, value]) => ({ key, value }));-});-const { t } = useI18n();--watch(- () => props.dataSource.externalSecret,- (externalSecret) => {- if (externalSecret) {- state.passwordType = externalSecret.secretType;- } else {- state.passwordType =- DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED;- }- },- { immediate: true, deep: true }-);--// Watch SSL fields and set updateSsl flag when they change-watch(- () => [- () => props.dataSource.verifyTlsCertificate,- () => props.dataSource.sslCa,- () => props.dataSource.sslCert,- () => props.dataSource.sslKey,- ],- () => {- if (!props.dataSource.pendingCreate) {- // eslint-disable-next-line vue/no-mutating-props- props.dataSource.updateSsl = true;- }- }-);--const hiveAuthentication = computed(() => {- return props.dataSource.saslConfig?.mechanism?.case === "krbConfig"- ? "KERBEROS"- : "PASSWORD";-});--const onHiveAuthenticationChange = (val: "KERBEROS" | "PASSWORD") => {- const ds = props.dataSource;- if (val === "KERBEROS") {- ds.saslConfig = create(SASLConfigSchema, {- mechanism: {- case: "krbConfig",- value: create(KerberosConfigSchema, {- kdcTransportProtocol: "tcp",- }),- },- });- } else {- ds.saslConfig = undefined;- }-};--const supportedAuthenticationTypes = computed(() => {- switch (basicInfo.value.engine) {- case Engine.COSMOSDB:- return [- {- value: DataSource_AuthenticationType.AZURE_IAM,- label: t("instance.password-type.azure-iam"),- },- ];- case Engine.MSSQL:- return [- {- value: DataSource_AuthenticationType.PASSWORD,- label: t("instance.password-type.password"),- },- {- value: DataSource_AuthenticationType.AZURE_IAM,- label: t("instance.password-type.azure-iam"),- },- ];- case Engine.ELASTICSEARCH:- return [- {- value: DataSource_AuthenticationType.PASSWORD,- label: t("instance.password-type.password"),- },- {- value: DataSource_AuthenticationType.AWS_RDS_IAM,- label: t("instance.password-type.aws-iam"),- },- ];- case Engine.SPANNER:- case Engine.BIGQUERY: {- return [- {- value: DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,- label: t("instance.password-type.google-iam"),- },- ];- }- default:- return [- {- value: DataSource_AuthenticationType.PASSWORD,- label: t("instance.password-type.password"),- },- {- value: DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,- label: t("instance.password-type.google-iam"),- },- {- value: DataSource_AuthenticationType.AWS_RDS_IAM,- label: t("instance.password-type.aws-iam"),- },- ];- }-});--const secretInputPlaceholder = computed(() => {- switch (state.passwordType) {- case DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED:- return `${t("common.password")} - ${t("common.write-only")}`;- case DataSourceExternalSecret_SecretType.VAULT_KV_V2:- switch (props.dataSource.externalSecret?.authType) {- case DataSourceExternalSecret_AuthType.TOKEN:- return `${t(- "instance.external-secret-vault.vault-auth-type.token.self"- )} - ${t("common.write-only")}`;- case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:- switch (- props.dataSource.externalSecret.authOption?.case === "appRole"- ? props.dataSource.externalSecret.authOption.value.type- : undefined- ) {- case DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN:- return `${t(- "instance.external-secret-vault.vault-auth-type.approle.secret-id-plain-text"- )} - ${t("common.write-only")}`;- case DataSourceExternalSecret_AppRoleAuthOption_SecretType.ENVIRONMENT:- return `${t(- "instance.external-secret-vault.vault-auth-type.approle.secret-id-environment"- )} - ${t("common.write-only")}`;- }- }- }-- return "";-});--const secretNameLabel = computed(() => {- switch (state.passwordType) {- case DataSourceExternalSecret_SecretType.VAULT_KV_V2:- return t("instance.external-secret-vault.vault-secret-path");- case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:- return t("instance.external-secret-gcp.secret-name");- case DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT:- return t("instance.external-secret-azure.secret-name");- default:- return t("instance.external-secret.secret-name");- }-});--const secretKeyLabel = computed(() => {- if (state.passwordType === DataSourceExternalSecret_SecretType.VAULT_KV_V2) {- return t("instance.external-secret-vault.vault-secret-key");- }- return t("instance.external-secret.key-name");-});--const verifyVaultTls = computed({- get: () => {- return !props.dataSource.externalSecret?.skipVaultTlsVerification;- },- set: (value: boolean) => {- if (props.dataSource.externalSecret) {- // eslint-disable-next-line vue/no-mutating-props- props.dataSource.externalSecret.skipVaultTlsVerification = !value;- }- },-});--const changeSecretType = (secretType: DataSourceExternalSecret_SecretType) => {- const ds = props.dataSource;- switch (secretType) {- case DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED:- ds.externalSecret = undefined;- break;- case DataSourceExternalSecret_SecretType.VAULT_KV_V2:- ds.externalSecret = create(DataSourceExternalSecretSchema, {- authType: DataSourceExternalSecret_AuthType.TOKEN,- secretType: secretType,- authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",- });- break;- case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:- ds.externalSecret = create(DataSourceExternalSecretSchema, {- authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,- secretType: secretType,- authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",- });- break;- case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:- ds.externalSecret = create(DataSourceExternalSecretSchema, {- authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,- secretType: secretType,- authOption: { case: "token", value: "" },- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: "",- });- break;- case DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT:- ds.externalSecret = create(DataSourceExternalSecretSchema, {- authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,- secretType: secretType,- authOption: { case: "token", value: "" },- url: ds.externalSecret?.url ?? "",- secretName: ds.externalSecret?.secretName ?? "",- passwordKeyName: "",- });- break;- }-- state.passwordType = secretType;-};--const changeExternalSecretAuthType = (- authType: DataSourceExternalSecret_AuthType-) => {- const ds = props.dataSource;- if (!ds.externalSecret) {- return;- }- if (authType === DataSourceExternalSecret_AuthType.VAULT_APP_ROLE) {- ds.externalSecret.authOption = {- case: "appRole",- value: create(DataSourceExternalSecret_AppRoleAuthOptionSchema, {- type: DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN,- }),- };- } else {- ds.externalSecret.authOption = {- case: "token",- value: "",- };- }- ds.externalSecret.authType = authType;-};--const toggleUseEmptyPassword = (on: boolean) => {- const ds = props.dataSource;- ds.useEmptyPassword = on;- if (on) {- ds.updatedPassword = "";- }-};--const toggleUseEmptyMasterPassword = (on: boolean) => {- const ds = props.dataSource;- ds.useEmptyMasterPassword = on;- if (on) {- ds.updatedMasterPassword = "";- }-};--const handleHostInput = (value: string) => {- const ds = props.dataSource;- if (ds.type === DataSourceType.READ_ONLY) {- if (!hasReadonlyReplicaFeature.value) {- if (ds.host || ds.port) {- ds.host = adminDataSource.value.host;- ds.port = adminDataSource.value.port;- missingFeature.value =- PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION;- return;- }- }- }- ds.host = value.trim();-};--const handlePortInput = (value: string) => {- const ds = props.dataSource;- if (ds.type === DataSourceType.READ_ONLY) {- if (!hasReadonlyReplicaFeature.value) {- if (ds.host || ds.port) {- ds.host = adminDataSource.value.host;- ds.port = adminDataSource.value.port;- missingFeature.value =- PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION;- return;- }- }- }- ds.port = value.trim();-};--const handleUseSslChanged = (useSSL: boolean) => {- const ds = props.dataSource;- ds.useSsl = useSSL;- ds.updateSsl = true;-};--const handleEditSSL = () => {- const ds = props.dataSource;- ds.sslCa = "";- ds.sslCert = "";- ds.sslKey = "";- ds.updateSsl = true;-};--const handleSSHChange = (- value: Partial<- Pick<- DataSourceOptions,- "sshHost" | "sshPort" | "sshUser" | "sshPassword" | "sshPrivateKey"- >- >-) => {- const ds = props.dataSource;- Object.assign(ds, value);-};--watch(- () => props.dataSource.authenticationPrivateKey,- (privateKey) => {- const ds = props.dataSource;- ds.useEmptyPassword = !!privateKey;- }-);--const handleKeytabUpload = (options: { file: UploadFileInfo }) => {- const reader = new FileReader();- reader.onload = function () {- const arrayBuffer = reader.result as ArrayBuffer;- const data = new Uint8Array(arrayBuffer);- const ds = props.dataSource;- if (ds.saslConfig?.mechanism?.case === "krbConfig") {- ds.saslConfig.mechanism.value.keytab = data;- }- };- reader.readAsArrayBuffer(options.file.file as Blob);-};--// Extra connection parameters management-const addNewParameter = () => {- // Skip if key is empty- if (!newParam.key.trim()) return;-- const ds = props.dataSource;-- // Get plain params object using our helper- const plainParams = createPlainParamsObject(ds.extraConnectionParameters);-- // Add the new parameter- const trimmedKey = newParam.key.trim();- plainParams[trimmedKey] = newParam.value;-- // Create a fresh object to ensure we're using a plain JS object- const freshParams: Record<string, string> = {};- Object.keys(plainParams).forEach((key) => {- freshParams[key] = plainParams[key];- });-- // Set the object directly using a brand new object- ds.extraConnectionParameters = freshParams;-- // Clear the form- newParam.key = "";- newParam.value = "";-};--// Helper function to create plain parameters object from existing parameters-const createPlainParamsObject = (- existingParams: Record<string, string> | undefined-): Record<string, string> => {- const plainParams: Record<string, string> = {};-- if (existingParams) {- // Copy all properties from the potentially proxied object- Object.entries(existingParams).forEach(([key, value]) => {- plainParams[key] = value;- });- }-- return plainParams;-};--const updateExtraConnectionParamKey = (index: number, newKey: string) => {- const ds = props.dataSource;- const params = extraConnectionParamsList.value;- if (index >= params.length) return;-- // Get plain params object- const plainParams = createPlainParamsObject(ds.extraConnectionParameters);-- const oldKey = params[index].key;- const value = params[index].value;-- // Skip if the key hasn't changed- if (oldKey === newKey) return;-- // Delete the old key- delete plainParams[oldKey];-- // Only add if the key is not empty- if (newKey.trim()) {- plainParams[newKey] = value;- }-- // Set the object directly- ds.extraConnectionParameters = plainParams;-};--const updateExtraConnectionParamValue = (index: number, newValue: string) => {- const ds = props.dataSource;- const params = extraConnectionParamsList.value;- if (index >= params.length) return;-- const key = params[index].key;-- // Get plain params object- const plainParams = createPlainParamsObject(ds.extraConnectionParameters);-- // Update the value- plainParams[key] = newValue;-- // Set the object directly- ds.extraConnectionParameters = plainParams;-};--const removeExtraConnectionParam = (index: number) => {- const ds = props.dataSource;- const params = extraConnectionParamsList.value;- if (index >= params.length) return;-- // Get plain params object- const plainParams = createPlainParamsObject(ds.extraConnectionParameters);-- // Remove the parameter- delete plainParams[params[index].key];-- // Set the object directly- ds.extraConnectionParameters = plainParams;-};-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceSection.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceSection.vuedeleted file mode 100644index 6a9bb6227d..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceSection.vue+++ /dev/null@@ -1,70 +0,0 @@-<template>- <CreateReadOnlyDataSourceTips- @add-readonly-datasource="handleCreateRODataSource"- />-- <div class="mt-2 gap-y-2 gap-x-4 border-none">- <DataSourceTabs- class="sm:col-span-3 mb-4"- @add-readonly-datasource="handleCreateRODataSource"- />-- <DataSourceForm- v-if="editingDataSource"- :data-source="editingDataSource"- :hide-options="hideOptions"- />- </div>-</template>--<script setup lang="ts">-withDefaults(- defineProps<{- hideOptions?: boolean;- }>(),- {- hideOptions: false,- }-);--import { DATASOURCE_READONLY_USER_NAME } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";-import { wrapEditDataSource } from "../common";-import { useInstanceFormContext } from "../context";-import CreateReadOnlyDataSourceTips from "./CreateReadOnlyDataSourceTips.vue";-import DataSourceForm from "./DataSourceForm.vue";-import DataSourceTabs from "./DataSourceTabs.vue";--const {- isCreating,- dataSourceEditState,- editingDataSource,- adminDataSource,- basicInfo,-} = useInstanceFormContext();--const handleCreateRODataSource = () => {- if (isCreating.value) {- return;- }-- const ds = {- ...wrapEditDataSource(undefined /* create new empty DS */),- type: DataSourceType.READ_ONLY,- host: adminDataSource.value.host,- port: adminDataSource.value.port,- database: adminDataSource.value.database,- username: DATASOURCE_READONLY_USER_NAME,- };- if (- basicInfo.value.engine === Engine.SPANNER ||- basicInfo.value.engine === Engine.BIGQUERY ||- basicInfo.value.engine === Engine.DYNAMODB- ) {- ds.host = adminDataSource.value.host;- }- dataSourceEditState.value.dataSources.push(ds);- dataSourceEditState.value.editingDataSourceId = ds.id;-};-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceTabs.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceTabs.vuedeleted file mode 100644index d2d213d08d..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceTabs.vue+++ /dev/null@@ -1,111 +0,0 @@-<template>- <NTabs- v-if="!isCreating"- ref="tabsRef"- v-model:value="dataSourceEditState.editingDataSourceId"- type="line"- justify-content="start"- tab-style="margin-right: 2rem;"- >- <NTab :name="adminDataSource.id">- {{ $t("common.admin") }}- </NTab>- <NTab v-for="ds in readonlyDataSourceList" :key="ds.id" :name="ds.id">- <span>{{ $t("common.read-only") }}</span>- <BBButtonConfirm- v-if="hasReadOnlyDataSource"- class="ml-2!"- :type="'DELETE'"- :disabled="!allowUpdate"- :require-confirm="!ds.pendingCreate"- :ok-text="$t('common.delete')"- :confirm-title="$t('data-source.delete-read-only-data-source') + '?'"- @confirm="handleDeleteDataSource(ds)"- />- </NTab>- <NTab- v-if="!hasReadOnlyDataSource"- name="placeholder-read-only-data-source"- :disabled="true"- >- <span>{{ $t("common.read-only") }}</span>- </NTab>- <NTab v-if="allowEdit" name="placeholder-add-data-source" :disabled="true">- <NButton- quaternary- size="small"- :disabled="!allowUpdate"- style="--n-padding: 0 4px"- @click.stop="$emit('add-readonly-datasource')"- >- <template #icon>- <heroicons:plus />- </template>- </NButton>- </NTab>- </NTabs>-</template>--<script setup lang="ts">-import { pullAt } from "lodash-es";-import type { TabsInst } from "naive-ui";-import { NButton, NTab, NTabs } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import { BBButtonConfirm } from "@/bbkit";-import { useInstanceV1Store } from "@/store";-import { hasWorkspacePermissionV2 } from "@/utils";-import type { EditDataSource } from "../common";-import { useInstanceFormContext } from "../context";--defineEmits<{- (event: "add-readonly-datasource"): void;-}>();--const tabsRef = ref<TabsInst>();-const {- instance,- isCreating,- allowEdit,- dataSourceEditState,- adminDataSource,- readonlyDataSourceList,- hasReadOnlyDataSource,-} = useInstanceFormContext();--const allowUpdate = computed(() =>- hasWorkspacePermissionV2("bb.instances.update")-);--const handleDeleteDataSource = async (ds: EditDataSource) => {- const removeLocalEditDataSource = (ds: EditDataSource) => {- const { dataSources, editingDataSourceId } = dataSourceEditState.value;- const index = dataSources.findIndex((d) => d.id === ds.id);- if (index >= 0) {- pullAt(dataSources, index);- }-- if (ds.id === editingDataSourceId) {- // When the current editing datasource is deleted- // Switch to its sibling- const siblingIndex = Math.min(index, dataSources.length - 1);- const siblingDataSource = dataSources[siblingIndex];- dataSourceEditState.value.editingDataSourceId = siblingDataSource?.id;- }- };-- if (instance.value && !ds.pendingCreate) {- // Remove via API- await useInstanceV1Store().deleteDataSource(instance.value, ds);- }-- removeLocalEditDataSource(ds);-};--watch(- () => dataSourceEditState.value.editingDataSourceId,- async () => {- await nextTick();- tabsRef.value?.syncBarPosition();- }-);-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/GcpCredentialInput.vue b/frontend/src/components/InstanceForm/DataSourceSection/GcpCredentialInput.vuedeleted file mode 100644index a485333df8..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/GcpCredentialInput.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <div class="flex flex-col gap-y-1 w-full">- <p class="textinfolabel">- <span>{{ $t("instance.create-gcp-credentials") }}</span>- <a- href="https://docs.bytebase.com/get-started/connect/gcp?source=console"- target="_blank"- class="normal-link inline-flex items-center ml-1"- >- <span>{{ $t("common.detailed-guide") }}</span>- <heroicons-outline:external-link class="w-4 h-4 ml-1" />- </a>- </p>- <DroppableTextarea- :value="value"- :resizable="false"- :placeholder="$t('instance.type-or-paste-credentials-write-only')"- class="w-full h-24 whitespace-pre-wrap"- @update:value="$emit('update:value', $event ?? '')"- />- </div>-</template>--<script lang="ts" setup>-import DroppableTextarea from "@/components/misc/DroppableTextarea.vue";--defineProps<{- value: string | undefined;-}>();--defineEmits<{- (name: "update:value", value: string): void;-}>();-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/OracleSIDAndServiceNameInput.vue b/frontend/src/components/InstanceForm/DataSourceSection/OracleSIDAndServiceNameInput.vuedeleted file mode 100644index 138c85e386..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/OracleSIDAndServiceNameInput.vue+++ /dev/null@@ -1,74 +0,0 @@-<template>- <div class="sm:col-span-3 sm:col-start-1">- <div class="flex items-center">- <NRadioGroup v-model:value="state.mode">- <NRadio value="ServiceName">- <span class="textlabel">ServiceName</span>- </NRadio>- <NRadio value="SID">- <span class="textlabel">SID</span>- </NRadio>- </NRadioGroup>- <RequiredStar />- </div>- <div class="mt-2">- <NInput- :value="state.value"- :placeholder="state.mode"- @update:value="onUpdate"- />- </div>- </div>-</template>--<script lang="ts" setup>-import { NInput, NRadio, NRadioGroup } from "naive-ui";-import { reactive, watch } from "vue";-import RequiredStar from "@/components/RequiredStar.vue";--type Mode = "ServiceName" | "SID";--type LocalState = {- mode: Mode;- value: string;-};--const props = defineProps<{- sid: string;- serviceName: string;- allowEdit: boolean;-}>();--const emit = defineEmits<{- (name: "update:sid", sid: string): void;- (name: "update:serviceName", serviceName: string): void;-}>();--const guessModeFromProps = (): Mode => {- if (props.sid) return "SID";- return "ServiceName";-};--const state = reactive<LocalState>({- value: props.serviceName || props.sid,- mode: guessModeFromProps(),-});--const onUpdate = (value: string) => {- if (state.mode === "SID") {- emit("update:sid", value);- emit("update:serviceName", "");- } else {- emit("update:serviceName", value);- emit("update:sid", "");- }- state.value = value;-};--watch(- () => state.mode,- () => {- onUpdate("");- }-);-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vuedeleted file mode 100644index fa5e3b9c93..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/SshConnectionForm.vue+++ /dev/null@@ -1,190 +0,0 @@-<template>- <div class="flex flex-row items-center gap-x-4 mt-2">- <NRadio- v-for="sshType in SshTypes"- :key="sshType"- :value="sshType"- :disabled="disabled"- :checked="state.type === sshType"- @update:checked="handleSelectType(sshType, $event)"- >- {{ getSshTypeLabel(sshType) }}- </NRadio>- </div>-- <template v-if="state.type !== 'NONE'">- <div- class="sm:col-span-1 sm:col-start-1 mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4"- >- <div class="sm:col-span-3 sm:col-start-1">- <label for="sshHost" class="textlabel block">- {{ $t("data-source.ssh.host") }}- </label>- <NInput- v-model:value="state.value.sshHost"- class="mt-2 w-full"- :placeholder="''"- :disabled="disabled"- />- </div>-- <div class="sm:col-span-1">- <label for="sshPort" class="textlabel block">- {{ $t("data-source.ssh.port") }}- </label>- <NInput- v-model:value="state.value.sshPort"- class="mt-2 w-full"- :placeholder="''"- :disabled="disabled"- :allow-input="onlyAllowNumber"- />- </div>- </div>-- <div- class="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3"- >- <div class="mt-2 sm:col-span-3 sm:col-start-1">- <label for="sshUser" class="textlabel block">- {{ $t("data-source.ssh.user") }}- </label>- <NInput- v-model:value="state.value.sshUser"- class="mt-2 w-full"- :placeholder="''"- :disabled="disabled"- />- </div>- <div class="mt-2 sm:col-span-3 sm:col-start-1">- <label for="sshPassword" class="textlabel block">- {{ $t("data-source.ssh.password") }}- </label>- <NInput- v-model:value="state.value.sshPassword"- class="mt-2 w-full"- :placeholder="$t('instance.password-write-only')"- :disabled="disabled"- />- </div>- </div>- <div class="mt-4 sm:col-span-3 sm:col-start-1">- <div class="mt-2 sm:col-span-1 sm:col-start-1 flex flex-col">- <label for="sshPrivateKey" class="textlabel block">- {{ $t("data-source.ssh.ssh-key") }}- ({{ t("common.optional") }})- </label>- <DroppableTextarea- v-model:value="state.value.sshPrivateKey"- :resizable="false"- :disabled="disabled"- :placeholder="$t('common.sensitive-placeholder')"- class="w-full h-24 mt-2 whitespace-pre-wrap"- />- </div>- </div>- </template>-</template>--<script lang="ts" setup>-import { NInput, NRadio } from "naive-ui";-import { reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import DroppableTextarea from "@/components/misc/DroppableTextarea.vue";-import type { Instance } from "@/types/proto-es/v1/instance_service_pb";-import { onlyAllowNumber } from "@/utils";--const SshTypes = ["NONE", "TUNNEL+PK"] as const;--type SshType = (typeof SshTypes)[number];--type WithSshOptions = {- sshHost?: string;- sshPort?: string;- sshUser?: string;- sshPassword?: string;- sshPrivateKey?: string;-};--type LocalState = {- type: SshType;- value: WithSshOptions;-};--const props = defineProps<{- value: WithSshOptions;- instance?: Instance;- disabled: boolean;-}>();--const emit = defineEmits<{- (e: "change", value: WithSshOptions): void;-}>();--const { t } = useI18n();--const state = reactive<LocalState>({- type: guessSshType(props.value),- value: {},-});--const handleSelectType = (type: SshType, checked: boolean) => {- if (!checked) return;-- state.type = type;-};--// Sync the latest version to local state when props.value changed.-watch(- () => props.value,- (newValue) => {- state.type = guessSshType(newValue);- state.value = {- sshHost: props.value.sshHost,- sshPort: props.value.sshPort,- sshUser: props.value.sshUser,- sshPassword: props.value.sshPassword,- sshPrivateKey: props.value.sshPrivateKey,- };- },- {- immediate: true,- }-);--// Emit the latest lo the parent when local value has been edited.-watch(- () => state.value,- (localValue) => {- emit("change", { ...localValue });- },- { deep: true }-);--watch(- () => state.type,- (type) => {- if (type === "NONE") {- state.value.sshHost = "";- state.value.sshPort = "";- state.value.sshUser = "";- state.value.sshPassword = "";- state.value.sshPrivateKey = "";- }- }-);--function getSshTypeLabel(type: SshType): string {- if (type === "TUNNEL+PK") {- return t("data-source.ssh-type.tunnel-and-private-key");- }- return t("data-source.ssh-type.none");-}--function guessSshType(value: WithSshOptions): SshType {- if (value.sshPort) {- return "TUNNEL+PK";- }- return "NONE";-}-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/SslCertificateFormV1.vue b/frontend/src/components/InstanceForm/DataSourceSection/SslCertificateFormV1.vuedeleted file mode 100644index 01ecedd53b..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/SslCertificateFormV1.vue+++ /dev/null@@ -1,183 +0,0 @@-<template>- <div class="mt-2 flex flex-col gap-y-1">- <div class="flex flex-row items-center gap-x-1">- <NSwitch- v-model:value="state.value.verify"- size="small"- :disabled="disabled"- />- <label class="textlabel block">- {{ verifyLabel }}- </label>- <NTooltip v-if="showTooltip" style="max-width: 20rem">- <template #trigger>- <Info class="w-4 h-4 text-yellow-600" />- </template>- {{ $t("data-source.ssl.verify-certificate-tooltip") }}- </NTooltip>- </div>-- <NTabs :default-value="'CA'" pane-style="padding-top: 0.25rem">- <NTabPane name="CA" :tab="caLabel" display-directive="show">- <DroppableTextarea- v-model:value="state.value.ca"- :resizable="false"- :disabled="disabled"- class="w-full h-24 whitespace-pre-wrap"- :placeholder="'Input or drag and drop YOUR_CA_CERTIFICATE'"- />- </NTabPane>- <NTabPane- v-if="hasSSLKeyField"- name="KEY"- :tab="keyLabel"- display-directive="show"- >- <DroppableTextarea- v-model:value="state.value.key"- :resizable="false"- :disabled="disabled"- class="w-full h-24 whitespace-pre-wrap"- :placeholder="'Input or drag and drop YOUR_CLIENT_KEY'"- />- </NTabPane>- <NTabPane- v-if="hasSSLCertField"- name="CERT"- :tab="certLabel"- display-directive="show"- >- <DroppableTextarea- v-model:value="state.value.cert"- :resizable="false"- :disabled="disabled"- class="w-full h-24 whitespace-pre-wrap"- :placeholder="'Input or drag and drop YOUR_CLIENT_CERT'"- />- </NTabPane>- </NTabs>- </div>-</template>--<script lang="ts" setup>-import { Info } from "lucide-vue-next";-import { NSwitch, NTabPane, NTabs, NTooltip } from "naive-ui";-import { computed, reactive, watch } from "vue";-import DroppableTextarea from "@/components/misc/DroppableTextarea.vue";-import { t } from "@/plugins/i18n";-import { Engine } from "@/types/proto-es/v1/common_pb";--type TlsConfig = {- verify: boolean;- ca: string;- cert: string;- key: string;-};--type LocalState = {- value: TlsConfig;-};--const props = withDefaults(- defineProps<{- verify: boolean;- ca?: string;- cert?: string;- privateKey?: string;- engineType?: Engine;- disabled: boolean;- verifyLabel?: string;- caLabel?: string;- certLabel?: string;- keyLabel?: string;- showTooltip?: boolean;- showKeyField?: boolean;- showCertField?: boolean;- }>(),- {- ca: "",- cert: "",- privateKey: "",- engineType: Engine.ENGINE_UNSPECIFIED,- showTooltip: true,- showKeyField: undefined,- showCertField: undefined,- caLabel: () => t("data-source.ssl.ca-cert"),- certLabel: () => t("data-source.ssl.client-cert"),- keyLabel: () => t("data-source.ssl.client-key"),- verifyLabel: () => t("data-source.ssl.verify-certificate"),- }-);--const emit = defineEmits<{- (e: "update:verify", value: boolean): void;- (e: "update:ca", value: string): void;- (e: "update:cert", value: string): void;- (e: "update:privateKey", value: string): void;-}>();--const state = reactive<LocalState>({- value: {- verify: props.verify ?? false,- ca: props.ca ?? "",- cert: props.cert ?? "",- key: props.privateKey ?? "",- },-});--const hasSSLKeyField = computed(() => {- if (props.showKeyField !== undefined) {- return props.showKeyField;- }- return ![Engine.MSSQL].includes(props.engineType);-});--const hasSSLCertField = computed(() => {- if (props.showCertField !== undefined) {- return props.showCertField;- }- return ![Engine.MSSQL].includes(props.engineType);-});--// Sync the latest version to local state when props changed.-watch(- () => [props.verify, props.ca, props.cert, props.privateKey] as const,- ([verify, ca, cert, privateKey]) => {- state.value = {- verify: verify ?? false,- ca: ca ?? "",- cert: cert ?? "",- key: privateKey ?? "",- };- }-);--// Emit changes to parent-watch(- () => state.value.verify,- (value) => {- emit("update:verify", value);- }-);--watch(- () => state.value.ca,- (value) => {- emit("update:ca", value);- }-);--watch(- () => state.value.cert,- (value) => {- emit("update:cert", value);- }-);--watch(- () => state.value.key,- (value) => {- emit("update:privateKey", value);- }-);-</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/index.ts b/frontend/src/components/InstanceForm/DataSourceSection/index.tsdeleted file mode 100644index da1b4613bf..0000000000--- a/frontend/src/components/InstanceForm/DataSourceSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import DataSourceSection from "./DataSourceSection.vue";--export default DataSourceSection;diff --git a/frontend/src/components/InstanceForm/Form.vue b/frontend/src/components/InstanceForm/Form.vuedeleted file mode 100644index 4157457d53..0000000000--- a/frontend/src/components/InstanceForm/Form.vue+++ /dev/null@@ -1,1077 +0,0 @@-<template>- <div class="flex flex-col gap-y-6 pb-2">- <div class="w-full flex flex-col gap-y-6">- <div- v-if="isCreating"- class="rounded-lg border border-block-border bg-white"- >- <button- type="button"- class="w-full flex items-center justify-between gap-x-3 px-4 py-3 text-left transition-colors hover:bg-gray-50"- @click="toggleEngineSelector"- >- <div class="min-w-0">- <p- class="text-[11px] font-medium uppercase tracking-[0.14em] text-control-light"- >- {{ $t("database.engine") }}- </p>- <div class="mt-1 flex items-center gap-x-1.5">- <RichEngineName- :engine="basicInfo.engine"- class="text-sm font-medium text-main"- />- <NTag- v-if="isEngineBeta(basicInfo.engine)"- round- size="small"- type="info"- >- Beta- </NTag>- </div>- </div>- <div class="shrink-0 text-control-light">- <ChevronDownIcon- v-if="!isEngineSelectorCollapsed"- class="w-4 h-4"- />- <ChevronRightIcon v-else class="w-4 h-4" />- </div>- </button>-- <Transition name="engine-selector">- <div- v-show="!isEngineSelectorCollapsed"- class="border-t border-block-border px-4 py-4"- >- <InstanceEngineRadioGrid- :engine="basicInfo.engine"- :engine-list="supportedEngineV1List()"- class="w-full grid-cols-2 sm:grid-cols-[repeat(auto-fit,minmax(170px,1fr))] gap-2"- @update:engine="- (newEngine: Engine) => handleSelectInstanceEngine(newEngine)- "- >- <template #suffix="{ engine }">- <NTag- v-if="isEngineBeta(engine as Engine)"- round- size="small"- type="info"- >- Beta- </NTag>- </template>- </InstanceEngineRadioGrid>- </div>- </Transition>- </div>-- <!-- Basic Info Card -->- <div class="border border-block-border rounded-lg p-5">- <h3 class="text-base font-medium text-main">- {{ $t("instance.section.basic-info") }}- </h3>-- <div class="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">- <div class="sm:col-span-2 sm:col-start-1">- <label for="name" class="textlabel flex flex-row items-center">- {{ $t("instance.instance-name") }}- <RequiredStar class="ml-0.5" />- <div v-if="instance" class="ml-2 flex items-center">- <InstanceV1EngineIcon :instance="instance" :tooltip="false" />- <span class="ml-1">{{ instance.engineVersion }}</span>- </div>- </label>- <NInput- v-model:value="basicInfo.title"- required- class="mt-1 w-full max-w-[40rem]"- :disabled="!allowEdit"- :maxlength="200"- />- </div>-- <div- v-if="subscriptionStore.currentPlan !== PlanType.FREE && allowEdit"- class="sm:col-span-2 ml-0 sm:ml-3"- >- <label for="activation" class="textlabel block">- {{ $t("subscription.instance-assignment.assign-license") }}- (<router-link- :to="autoSubscriptionRoute()"- class="accent-link"- >- {{- $t("subscription.instance-assignment.n-license-remain", {- n: availableLicenseCountText,- })- }}</router-link- >)- </label>- <div class="h-8.5 flex flex-row items-center mt-1">- <NSwitch- :value="basicInfo.activation"- :disabled="!basicInfo.activation && availableLicenseCount === 0"- @update:value="changeInstanceActivation"- />- </div>- </div>-- <div- :key="basicInfo.environment"- class="sm:col-span-3 sm:col-start-1 -mt-4"- >- <ResourceIdField- ref="resourceIdField"- v-model:value="resourceId"- class="max-w-full flex-nowrap"- editing-class="mt-4"- resource-type="instance"- :readonly="!isCreating"- :resource-title="basicInfo.title"- :fetch-resource="- (id) =>- instanceV1Store.getOrFetchInstanceByName(- `${instanceNamePrefix}${id}`,- true /* silent */- )- "- />- </div>-- <div class="sm:col-span-2 sm:col-start-1">- <label for="environment" class="textlabel">- {{ $t("common.environment") }}- </label>- <EnvironmentSelect- class="mt-1 w-full max-w-[40rem]"- required="true"- :value="- isValidEnvironmentName(- `${environmentNamePrefix}${environment.id}`- )- ? `${environmentNamePrefix}${environment.id}`- : undefined- "- :disabled="!allowEdit"- @update:value="handleSelectEnvironment($event as (string | undefined))"- />- </div>-- <!-- Labels -->- <div class="sm:col-span-3 sm:col-start-1">- <label for="labels" class="textlabel">- {{ $t("common.labels") }}- </label>- <div class="mt-1">- <LabelListEditor- ref="labelListEditorRef"- v-model:kv-list="labelKVList"- :readonly="!allowEdit"- :show-errors="true"- />- </div>- </div>-- <!--Do not show external link on create to reduce cognitive load-->- <div v-if="!isCreating" class="sm:col-span-3 sm:col-start-1">- <label for="external-link" class="textlabel inline-flex">- <span>- {{- basicInfo.engine === Engine.SNOWFLAKE- ? $t("instance.snowflake-web-console")- : $t("instance.external-link")- }}- </span>- <button- v-if="instanceLink.trim().length > 0"- class="ml-1 btn-icon"- @click.prevent="window.open(urlfy(instanceLink), '_blank')"- >- <heroicons-outline:external-link class="w-4 h-4" />- </button>- </label>- <template v-if="basicInfo.engine === Engine.SNOWFLAKE">- <NInput- required- class="mt-1 w-full"- :disabled="true"- :value="instanceLink"- />- </template>- <template v-else>- <div class="mt-1 textinfolabel">- {{ $t("instance.sentence.console.snowflake") }}- </div>- <NInput- v-model:value="basicInfo.externalLink"- required- class="textfield mt-1 w-full"- :disabled="!allowEdit"- :placeholder="SnowflakeExtraLinkPlaceHolder"- />- </template>- </div>-- <ScanIntervalInput- v-if="!isCreating && instance"- ref="scanIntervalInputRef"- :scan-interval="basicInfo.syncInterval"- :allow-edit="allowEdit"- :instance="instance"- @update:scan-interval="changeScanInterval"- />-- <SyncDatabases- v-if="!isCreating"- :is-creating="false"- :show-label="true"- :allow-edit="allowEdit"- :sync-databases="basicInfo.syncDatabases"- @update:sync-databases="handleChangeSyncDatabases"- />- </div>- </div>-- <!-- Connection Card -->- <div class="border border-block-border rounded-lg p-5">- <h3 class="text-base font-medium text-main">- {{ $t("instance.section.connection") }}- </h3>-- <div class="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">- <div class="sm:col-span-3 sm:col-start-1">- <template v-if="basicInfo.engine === Engine.SPANNER">- <SpannerHostInput- v-model:host="adminDataSource.host"- :allow-edit="allowEdit"- />- </template>- <template v-else-if="basicInfo.engine === Engine.BIGQUERY">- <BigQueryHostInput- v-model:host="adminDataSource.host"- :allow-edit="allowEdit"- />- </template>- <template v-else>- <label for="host" class="textlabel block">- <template v-if="basicInfo.engine === Engine.SNOWFLAKE">- {{ $t("instance.account-locator") }}- <RequiredStar class="mr-2" />- <LearnMoreLink- url="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier"- class="text-sm"- />- </template>- <template v-else-if="basicInfo.engine === Engine.COSMOSDB">- {{ $t("instance.endpoint") }}- <RequiredStar />- </template>- <div- v-else-if="- adminDataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- >- <span>- {{ $t("instance.sentence.google-cloud-sql.instance-name") }}- <RequiredStar />- </span>- <i18n-t- tag="div"- class="textinfolabel mb-1"- keypath="instance.sentence.google-cloud-sql.instance-name-tips"- >- <template #instance>- <span class="font-bold">- {project-id}:{region}:{instance-name}- </span>- </template>- </i18n-t>- </div>- <template v-else>- {{ $t("instance.host-or-socket") }}- <RequiredStar v-if="basicInfo.engine !== Engine.DYNAMODB" />- <InfoTrigger- v-if="isCreating && infoPanel && hasHostInfo"- @click="openInfoPanel('host')"- />- </template>- </label>- <NInput- v-model:value="adminDataSource.host"- required- :placeholder="- basicInfo.engine === Engine.SNOWFLAKE- ? $t('instance.your-snowflake-account-locator')- : $t('instance.sentence.host.none-snowflake')- "- class="mt-1 w-full"- :disabled="!allowEdit"- />- <div- v-if="basicInfo.engine === Engine.SNOWFLAKE"- class="mt-2 textinfolabel"- >- {{ $t("instance.sentence.proxy.snowflake") }}- </div>- </template>- </div>-- <template- v-if="- basicInfo.engine !== Engine.SPANNER &&- basicInfo.engine !== Engine.BIGQUERY &&- basicInfo.engine !== Engine.DATABRICKS &&- basicInfo.engine !== Engine.COSMOSDB &&- adminDataSource.authenticationType !==- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- >- <div class="sm:col-span-1">- <label for="port" class="textlabel block">- {{ $t("instance.port") }}- </label>- <NInput- v-model:value="adminDataSource.port"- class="mt-1 w-full"- :placeholder="defaultPort"- :disabled="!allowEdit || !allowEditPort"- :allow-input="onlyAllowNumber"- />- </div>- </template>-- <div- v-if="basicInfo.engine === Engine.MONGODB"- class="sm:col-span-4 sm:col-start-1"- >- <label- for="connectionStringSchema"- class="textlabel flex flex-row items-center"- >- {{ $t("data-source.connection-string-schema") }}- </label>- <NRadioGroup- :value="currentMongoDBConnectionSchema"- @update:value="handleMongodbConnectionStringSchemaChange"- >- <NRadio- v-for="type in MongoDBConnectionStringSchemaList"- :key="type"- :value="type"- >- {{ type }}- </NRadio>- </NRadioGroup>- </div>-- <div- v-if="basicInfo.engine === Engine.REDIS"- class="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2"- >- <label- for="connectionStringSchema"- class="textlabel flex flex-row items-center"- >- {{ $t("data-source.connection-type") }}- </label>- <NRadioGroup- :value="currentRedisConnectionType"- @update:value="handleRedisConnectionTypeChange"- >- <NRadio- v-for="type in RedisConnectionType"- :key="type"- :value="type"- >- {{ type }}- </NRadio>- </NRadioGroup>- </div>-- <div- v-if="showAdditionalAddresses"- class="sm:col-span-4 sm:col-start-1"- >- <label- for="additionalAddresses"- class="textlabel flex flex-row items-center"- >- {{ $t("data-source.additional-node-addresses") }}- </label>- <div- class="mt-1 grid grid-cols-1 gap-y-1 gap-x-4 sm:grid-cols-12"- >- <template- v-for="(_, index) in adminDataSource.additionalAddresses"- :key="index"- >- <div class="sm:col-span-8 sm:col-start-1">- <label- v-if="index === 0"- for="additionalAddressesHost"- class="textlabel font-normal! flex flex-row items-center"- >- {{ $t("instance.host-or-socket") }}- </label>- <NInput- v-model:value="- adminDataSource.additionalAddresses[index].host- "- required- class="mt-1 w-full"- :disabled="!allowEdit"- />- </div>- <div class="sm:col-span-3">- <label- v-if="index === 0"- for="additionalAddressesPort"- class="textlabel font-normal! flex flex-row items-center"- >- {{ $t("instance.port") }}- </label>- <NInput- v-model:value="- adminDataSource.additionalAddresses[index].port- "- class="mt-1 w-full"- :placeholder="defaultPort"- :disabled="!allowEdit || !allowEditPort"- :allow-input="onlyAllowNumber"- />- </div>- <div class="h-8.5 flex flex-row items-center self-end">- <MiniActionButton- :disabled="!allowEdit"- @click.stop="removeDSAdditionalAddress(index)"- >- <TrashIcon class="w-4 h-4" />- </MiniActionButton>- </div>- </template>- <div class="mt-1 sm:col-span-12 sm:col-start-1">- <NButton- class="ml-auto w-12!"- size="small"- @click.prevent="addDSAdditionalAddress"- >- {{ $t("common.add") }}- </NButton>- </div>- </div>- </div>-- <div- v-if="basicInfo.engine === Engine.MONGODB && !adminDataSource.srv"- class="sm:col-span-2 sm:col-start-1"- >- <label for="replicaSet" class="textlabel">- {{ $t("data-source.replica-set") }}- </label>- <NInput- v-model:value="adminDataSource.replicaSet"- required- class="mt-1 w-full"- :disabled="!allowEdit"- />- </div>-- <div- v-if="- basicInfo.engine === Engine.MONGODB &&- !adminDataSource.srv &&- adminDataSource.additionalAddresses.length === 0- "- class="sm:col-span-4 sm:col-start-1"- >- <NCheckbox- :checked="adminDataSource.directConnection"- :disabled="!allowEdit"- style="--n-label-padding: 0 0 0 1rem"- @update:checked="- (on: boolean) => {- adminDataSource.directConnection = on;- }- "- >- {{ $t("data-source.direct-connection") }}- </NCheckbox>- </div>- </div>-- <!-- Credentials (auth method, username, password) -->- <template v-if="basicInfo.engine !== Engine.DYNAMODB">- <DataSourceSection hide-options />-- <BBAttention- v-if="actuatorStore.isSaaSMode"- class="mt-4 border-none"- type="info"- >- <a- href="https://docs.bytebase.com/get-started/cloud#prerequisites"- target="_blank"- rel="noopener noreferrer"- class="normal-link"- >- {{ $t("instance.sentence.firewall-info") }}- </a>- </BBAttention>- </template>- </div>-- <!-- Connection Options Card (Extra Params, SSL, SSH) -->- <div- v-if="basicInfo.engine !== Engine.DYNAMODB && editingDataSource"- class="border border-block-border rounded-lg bg-white"- >- <button- type="button"- class="w-full flex items-center justify-between gap-x-3 px-5 py-4 text-left transition-colors hover:bg-gray-50"- @click="toggleConnectionOptions"- >- <h3 class="text-base font-medium text-main">- {{ $t("instance.connection-options") }}- </h3>- <div class="shrink-0 text-control-light">- <ChevronDownIcon- v-if="!isConnectionOptionsCollapsed"- class="w-4 h-4"- />- <ChevronRightIcon v-else class="w-4 h-4" />- </div>- </button>- <Transition name="connection-options">- <div- v-show="!isConnectionOptionsCollapsed"- class="border-t border-block-border px-5 py-4"- >- <DataSourceForm :data-source="editingDataSource" options-only />- </div>- </Transition>- </div>-- <div- v-if="- isCreating &&- !!editingDataSource- "- class="flex justify-start"- >- <NButton- tertiary- type="primary"- :loading="state.isTestingConnection"- :disabled="!allowTestConnection"- @click.prevent="testConnectionForCurrentEditingDS"- >- {{ $t("instance.test-connection") }}- </NButton>- </div>-- <!-- Sync Databases Card (create only) -->- <div- v-if="basicInfo.engine !== Engine.DYNAMODB && isCreating"- class="border border-block-border rounded-lg p-5 flex flex-col gap-y-1"- >- <p class="w-full text-lg leading-6 font-medium text-gray-900">- {{ $t("instance.sync-databases.self") }}- </p>-- <SyncDatabases- class="mt-2"- :is-creating="true"- :show-label="false"- :allow-edit="allowEdit && !!allowCreate"- :sync-databases="basicInfo.syncDatabases"- @update:sync-databases="handleChangeSyncDatabases"- />- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import type { Duration } from "@bufbuild/protobuf/wkt";-import { ChevronDownIcon, ChevronRightIcon, TrashIcon } from "lucide-vue-next";-import {- NButton,- NCheckbox,- NInput,- NRadio,- NRadioGroup,- NSwitch,- NTag,-} from "naive-ui";-import { computed, inject, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBAttention } from "@/bbkit";-import { LabelListEditor } from "@/components/Label";-import RequiredStar from "@/components/RequiredStar.vue";-import {- EnvironmentSelect,- InstanceEngineRadioGrid,- InstanceV1EngineIcon,- MiniActionButton,- RichEngineName,-} from "@/components/v2";-import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import {- pushNotification,- useActuatorV1Store,- useDatabaseV1Store,- useInstanceV1Store,- useSubscriptionV1Store,-} from "@/store";-import {- environmentNamePrefix,- instanceNamePrefix,-} from "@/store/modules/v1/common";-import { isValidEnvironmentName, UNKNOWN_ID } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- DataSource_AddressSchema,- DataSource_AuthenticationType,- DataSource_RedisType,-} from "@/types/proto-es/v1/instance_service_pb";-import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-import {- autoSubscriptionRoute,- extractInstanceResourceName,- isDev,- isValidSpannerHost,- onlyAllowNumber,- supportedEngineV1List,- urlfy,-} from "@/utils";-import LearnMoreLink from "../LearnMoreLink.vue";-import BigQueryHostInput from "./BigQueryHostInput.vue";-import {- MongoDBConnectionStringSchemaList,- RedisConnectionType,- SnowflakeExtraLinkPlaceHolder,-} from "./constants";-import { useInstanceFormContext } from "./context";-import DataSourceForm from "./DataSourceSection/DataSourceForm.vue";-import DataSourceSection from "./DataSourceSection/DataSourceSection.vue";-import InfoTrigger from "./InfoTrigger.vue";-import { hasInfoContent, type InfoSection } from "./info-content";-import ScanIntervalInput from "./ScanIntervalInput.vue";-import SpannerHostInput from "./SpannerHostInput.vue";-import SyncDatabases from "./SyncDatabases.vue";--const context = useInstanceFormContext();-const {- events,- state,- specs,- instance,- environment,- isCreating,- allowEdit,- allowCreate,- resourceIdField,- basicInfo,- labelListEditorRef,- labelKVList,- adminDataSource,- editingDataSource,- checkDataSource,- testConnection,-} = context;-const { isEngineBeta, defaultPort, instanceLink, allowEditPort } = specs;--const infoPanel = inject<- | {- open: (section: InfoSection) => void;- close: () => void;- setEngine: (engine: Engine) => void;- }- | undefined->("infoPanel", undefined);--watch(- () => basicInfo.value.engine,- (engine) => {- infoPanel?.setEngine(engine);- },- { immediate: true }-);--const openInfoPanel = (section: InfoSection) => {- if (!hasInfoContent(basicInfo.value.engine, section)) {- return;- }- infoPanel?.open(section);-};--const hasHostInfo = computed(() =>- hasInfoContent(basicInfo.value.engine, "host")-);--const { t } = useI18n();-const instanceV1Store = useInstanceV1Store();-const actuatorStore = useActuatorV1Store();-const subscriptionStore = useSubscriptionV1Store();-const scanIntervalInputRef = ref<InstanceType<typeof ScanIntervalInput>>();-const isEngineSelectorCollapsed = ref(false);-const isConnectionOptionsCollapsed = ref(true);--const showConnectionOptionsCard = computed(() => {- return (- basicInfo.value.engine !== Engine.DYNAMODB && !!editingDataSource.value- );-});--const hasConfiguredConnectionOptions = computed(() => {- const ds = editingDataSource.value;- if (!ds) {- return false;- }-- const hasExtraParameters =- Object.keys(ds.extraConnectionParameters ?? {}).length > 0;- const hasSslConfig = !!(ds.useSsl || ds.sslCa || ds.sslCert || ds.sslKey);- const hasSshConfig = !!(- ds.sshHost ||- ds.sshPort ||- ds.sshUser ||- ds.sshPassword ||- ds.sshPrivateKey- );-- return hasExtraParameters || hasSslConfig || hasSshConfig;-});--watch(- () => ({- show: showConnectionOptionsCard.value,- creating: isCreating.value,- hasConfigured: hasConfiguredConnectionOptions.value,- }),- (next, prev) => {- if (!next.show) {- return;- }-- const becameVisible = !prev?.show;- if (becameVisible) {- isConnectionOptionsCollapsed.value = next.creating- ? true- : !next.hasConfigured;- return;- }-- if (!next.creating && next.hasConfigured && !prev?.hasConfigured) {- isConnectionOptionsCollapsed.value = false;- }- },- { immediate: true }-);--useEmitteryEventListener(events, "show-connection-options", () => {- if (!showConnectionOptionsCard.value) {- return;- }- isConnectionOptionsCollapsed.value = false;-});--const availableLicenseCount = computed(() => {- return Math.max(- 0,- subscriptionStore.instanceLicenseCount -- actuatorStore.activatedInstanceCount- );-});--const availableLicenseCountText = computed((): string => {- if (subscriptionStore.instanceLicenseCount === Number.MAX_VALUE) {- return t("common.unlimited");- }- return `${availableLicenseCount.value}`;-});--const resourceId = computed({- get() {- const id = extractInstanceResourceName(basicInfo.value.name);- if (id === String(UNKNOWN_ID)) return "";- return id;- },- set(id) {- basicInfo.value.name = `instances/${id}`;- },-});--const currentMongoDBConnectionSchema = computed(() => {- return adminDataSource.value.srv === false- ? MongoDBConnectionStringSchemaList[0]- : MongoDBConnectionStringSchemaList[1];-});--const currentRedisConnectionType = computed(() => {- switch (adminDataSource.value.redisType) {- case DataSource_RedisType.STANDALONE:- return RedisConnectionType[0];- case DataSource_RedisType.SENTINEL:- return RedisConnectionType[1];- case DataSource_RedisType.CLUSTER:- return RedisConnectionType[2];- default:- return RedisConnectionType[0];- }-});--const showAdditionalAddresses = computed(() => {- if (basicInfo.value.engine === Engine.CASSANDRA) {- return true;- }- if (basicInfo.value.engine === Engine.MONGODB && !adminDataSource.value.srv) {- return true;- }- if (- basicInfo.value.engine === Engine.REDIS &&- (adminDataSource.value.redisType === DataSource_RedisType.CLUSTER ||- adminDataSource.value.redisType === DataSource_RedisType.SENTINEL)- ) {- return true;- }- return false;-});--// The default host name is 127.0.0.1 or host.docker.internal which is not applicable to Snowflake, so we change-// the host name between 127.0.0.1/host.docker.internal and "" if user hasn't changed default yet.-const changeInstanceEngine = (engine: Engine) => {- context.resetDataSource();- switch (engine) {- case Engine.SNOWFLAKE:- case Engine.DYNAMODB: {- if (- adminDataSource.value.host === "127.0.0.1" ||- adminDataSource.value.host === "host.docker.internal"- ) {- adminDataSource.value.host = "";- }- break;- }- case Engine.SPANNER:- case Engine.BIGQUERY: {- adminDataSource.value.authenticationType =- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM;- if (- adminDataSource.value.host === "127.0.0.1" ||- adminDataSource.value.host === "host.docker.internal"- ) {- adminDataSource.value.host = "";- }- break;- }- case Engine.COSMOSDB: {- // Cosmos DB supports Azure IAM only.- adminDataSource.value.authenticationType =- DataSource_AuthenticationType.AZURE_IAM;- break;- }- default: {- if (!adminDataSource.value.host) {- adminDataSource.value.host = isDev()- ? "127.0.0.1"- : "host.docker.internal";- }- break;- }- }- basicInfo.value.engine = engine;-};--const handleSelectInstanceEngine = (engine: Engine) => {- changeInstanceEngine(engine);- isEngineSelectorCollapsed.value = true;-};--const toggleEngineSelector = () => {- isEngineSelectorCollapsed.value = !isEngineSelectorCollapsed.value;-};--const toggleConnectionOptions = () => {- isConnectionOptionsCollapsed.value = !isConnectionOptionsCollapsed.value;-};--const allowTestConnection = computed(() => {- if (- !allowEdit.value ||- state.value.isRequesting ||- state.value.isTestingConnection- ) {- return false;- }-- const ds = editingDataSource.value;- if (!ds) {- return false;- }-- if (basicInfo.value.engine === Engine.SPANNER) {- return isValidSpannerHost(ds.host);- }- if (basicInfo.value.engine === Engine.BIGQUERY) {- return ds.host !== "";- }- if (basicInfo.value.engine !== Engine.DYNAMODB && ds.host === "") {- return false;- }-- return checkDataSource([ds]);-});--const testConnectionForCurrentEditingDS = async () => {- const ds = editingDataSource.value;- if (!ds) {- return;- }-- const result = await testConnection(ds, /* !silent */ false);- if (!result.success && hasConfiguredConnectionOptions.value) {- events.emit("show-connection-options");- }-};--const handleChangeSyncDatabases = (databases: string[]) => {- basicInfo.value.syncDatabases = [...databases];-};--const changeScanInterval = (duration: Duration | undefined) => {- basicInfo.value.syncInterval = duration;-};--const handleRedisConnectionTypeChange = (type: string) => {- const ds = editingDataSource.value;- if (!ds) return;- switch (type) {- case RedisConnectionType[0]:- ds.redisType = DataSource_RedisType.STANDALONE;- break;- case RedisConnectionType[1]:- ds.redisType = DataSource_RedisType.SENTINEL;- break;- case RedisConnectionType[2]:- ds.redisType = DataSource_RedisType.CLUSTER;- break;- default:- ds.redisType = DataSource_RedisType.STANDALONE;- break;- }-};--const handleMongodbConnectionStringSchemaChange = (type: string) => {- const ds = editingDataSource.value;- if (!ds) return;- switch (type) {- case MongoDBConnectionStringSchemaList[0]:- ds.srv = false;- break;- case MongoDBConnectionStringSchemaList[1]:- // MongoDB doesn't support specify port if using srv record.- ds.port = "";- ds.additionalAddresses = [];- ds.replicaSet = "";- ds.directConnection = false;- ds.srv = true;- break;- default:- ds.srv = false;- }-};--const removeDSAdditionalAddress = (i: number) => {- adminDataSource.value.additionalAddresses.splice(i, 1);- if (adminDataSource.value.additionalAddresses.length === 0) {- adminDataSource.value.directConnection = false;- }-};--const addDSAdditionalAddress = () => {- editingDataSource.value?.additionalAddresses.push(- create(DataSource_AddressSchema, {- host: "",- port: "",- })- );- if (adminDataSource.value.additionalAddresses.length !== 0) {- adminDataSource.value.directConnection = false;- }-};--const changeInstanceActivation = async (on: boolean) => {- basicInfo.value.activation = on;- if (instance.value) {- const instancePatch = {- ...instance.value,- activation: on,- };- const updated = await instanceV1Store.updateInstance(instancePatch, [- "activation",- ]);- useDatabaseV1Store().updateDatabaseInstance(updated);- // refresh activatedInstanceCount- await actuatorStore.fetchServerInfo(actuatorStore.workspaceResourceName);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }-};--const handleSelectEnvironment = (name: string | undefined) => {- basicInfo.value.environment = name;-};-</script>--<style lang="postcss" scoped>-.engine-selector-enter-active,-.engine-selector-leave-active {- overflow: hidden;- transition: max-height 0.2s ease, opacity 0.2s ease, transform 0.2s ease;-}--.engine-selector-enter-from,-.engine-selector-leave-to {- max-height: 0;- opacity: 0;- transform: translateY(-0.25rem);-}--.engine-selector-enter-to,-.engine-selector-leave-from {- max-height: 32rem;- opacity: 1;- transform: translateY(0);-}--.connection-options-enter-active,-.connection-options-leave-active {- overflow: hidden;- transition: max-height 0.2s ease, opacity 0.2s ease, transform 0.2s ease;-}--.connection-options-enter-from,-.connection-options-leave-to {- max-height: 0;- opacity: 0;- transform: translateY(-0.25rem);-}--.connection-options-enter-to,-.connection-options-leave-from {- max-height: 80rem;- opacity: 1;- transform: translateY(0);-}-</style>diff --git a/frontend/src/components/InstanceForm/InfoPanel.vue b/frontend/src/components/InstanceForm/InfoPanel.vuedeleted file mode 100644index 63b736d442..0000000000--- a/frontend/src/components/InstanceForm/InfoPanel.vue+++ /dev/null@@ -1,115 +0,0 @@-<template>- <Teleport v-if="mode === 'overlay'" to="body">- <Transition name="info-panel">- <div- v-if="visible"- class="fixed inset-0 z-50 flex justify-end"- @click.self="$emit('close')"- >- <div- class="w-[500px] bg-white border-l border-block-border shadow-lg flex flex-col h-full"- >- <div- class="sticky top-0 z-10 flex items-center justify-between px-4 py-3 border-b border-block-border bg-white"- >- <h3 class="text-sm font-semibold text-main truncate">- {{ title }}- </h3>- <button- class="text-control-light hover:text-main p-0.5 rounded"- @click="$emit('close')"- >- <XIcon class="w-4 h-4" />- </button>- </div>- <div class="flex-1 overflow-y-auto px-4 py-4">- <slot />- </div>- </div>- </div>- </Transition>- </Teleport>-- <Transition- v-else- name="info-rail"- @before-leave="$emit('before-leave')"- @after-leave="$emit('after-leave')"- >- <aside- v-if="visible"- data-info-panel-docked="true"- class="h-full w-full min-w-0 overflow-hidden border-l border-block-border bg-white"- >- <div class="flex h-full flex-col">- <div- class="sticky top-0 z-10 flex items-center justify-between border-b border-block-border bg-white px-5 py-3"- >- <h3 class="min-w-0 truncate text-sm font-semibold text-main">- {{ title }}- </h3>- <button- class="text-control-light hover:text-main p-0.5 rounded"- @click="$emit('close')"- >- <XIcon class="w-4 h-4" />- </button>- </div>- <div class="flex-1 overflow-y-auto px-5 py-5">- <slot />- </div>- </div>- </aside>- </Transition>-</template>--<script lang="ts" setup>-import { XIcon } from "lucide-vue-next";--withDefaults(- defineProps<{- visible: boolean;- title: string;- mode?: "overlay" | "docked";- }>(),- {- mode: "overlay",- }-);--defineEmits<{- close: [];- "before-leave": [];- "after-leave": [];-}>();-</script>--<style scoped>-.info-panel-enter-active,-.info-panel-leave-active {- transition: transform 0.2s ease;-}-.info-panel-enter-active > div,-.info-panel-leave-active > div {- transition: transform 0.2s ease;-}-.info-panel-enter-from > div,-.info-panel-leave-to > div {- transform: translateX(100%);-}--.info-rail-enter-active,-.info-rail-leave-active {- transition: opacity 0.14s ease, transform 0.14s ease;-}--.info-rail-enter-from {- opacity: 0;- transform: translateX(0.75rem);-}--.info-rail-leave-to {- opacity: 0;- transform: translateX(0);-}-</style>diff --git a/frontend/src/components/InstanceForm/InfoPanelContent.vue b/frontend/src/components/InstanceForm/InfoPanelContent.vuedeleted file mode 100644index 6607e00b70..0000000000--- a/frontend/src/components/InstanceForm/InfoPanelContent.vue+++ /dev/null@@ -1,63 +0,0 @@-<template>- <div v-if="snippet" class="flex flex-col gap-y-3">- <p class="text-sm text-main leading-relaxed">- {{ snippet.content }}- </p>- <div v-if="snippet.codeBlock" class="flex flex-col gap-y-1">- <div class="flex flex-row">- <NConfigProvider- class="flex-1 min-w-0 w-full inline-flex items-center px-3 py-2 border border-control-border bg-gray-50 whitespace-pre-line rounded-l-[3px] overflow-x-auto"- :hljs="hljs"- >- <NCode- class="text-[12px]"- word-wrap- :language="snippet.codeBlock.language"- :code="snippet.codeBlock.code"- />- </NConfigProvider>- <div- class="flex items-center -ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light bg-gray-50 hover:bg-gray-100 rounded-r-[3px]"- >- <CopyButton :content="snippet.codeBlock.code" />- </div>- </div>- </div>- <div- v-if="snippet.learnMoreLinks && snippet.learnMoreLinks.length > 0"- class="flex flex-col gap-y-1"- >- <a- v-for="link in snippet.learnMoreLinks"- :key="link.url"- :href="link.url"- target="_blank"- rel="noopener noreferrer"- class="text-xs accent-link"- >- {{ link.title }}- </a>- </div>- </div>- <div v-else class="text-sm text-control-light italic">- {{ $t("instance.info-panel.no-info") }}- </div>-</template>--<script lang="ts" setup>-import hljs from "highlight.js/lib/core";-import { NCode, NConfigProvider } from "naive-ui";-import { computed } from "vue";-import { CopyButton } from "@/components/v2";-import type { Engine } from "@/types/proto-es/v1/common_pb";-import { getInfoContent, type InfoSection } from "./info-content";--const props = defineProps<{- engine: Engine;- section: InfoSection;-}>();--const snippet = computed(() => {- return getInfoContent(props.engine, props.section);-});-</script>diff --git a/frontend/src/components/InstanceForm/InfoTrigger.vue b/frontend/src/components/InstanceForm/InfoTrigger.vuedeleted file mode 100644index 481db60e29..0000000000--- a/frontend/src/components/InstanceForm/InfoTrigger.vue+++ /dev/null@@ -1,17 +0,0 @@-<template>- <button- class="inline-flex items-center gap-x-0.5 text-control-light hover:text-accent cursor-pointer ml-1"- @click.prevent.stop="$emit('click')"- >- <InfoIcon class="w-3.5 h-3.5" />- <span class="text-xs">{{ $t("common.info") }}</span>- </button>-</template>--<script lang="ts" setup>-import { InfoIcon } from "lucide-vue-next";--defineEmits<{- click: [];-}>();-</script>diff --git a/frontend/src/components/InstanceForm/InstanceForm.vue b/frontend/src/components/InstanceForm/InstanceForm.vuedeleted file mode 100644index 108eb7d3f9..0000000000--- a/frontend/src/components/InstanceForm/InstanceForm.vue+++ /dev/null@@ -1,87 +0,0 @@-<template>- <slot />-- <FeatureModal- v-if="missingFeature"- :feature="missingFeature"- :open="true"- :instance="instance"- @cancel="missingFeature = undefined"- />-</template>--<script lang="ts" setup>-import { computed, onMounted, toRef, watch } from "vue";-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import { useActuatorV1Store } from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { Instance } from "@/types/proto-es/v1/instance_service_pb";-import { FeatureModal } from "../FeatureGuard";-import { defaultPortForEngine } from "./constants";-import { provideInstanceFormContext } from "./context";--const props = defineProps<{- instance?: Instance;- hideAdvancedFeatures?: boolean;-}>();--const emit = defineEmits<{- (event: "dismiss"): void;-}>();--const actuatorStore = useActuatorV1Store();--const instance = toRef(props, "instance");-const hideAdvancedFeatures = toRef(props, "hideAdvancedFeatures");-const context = provideInstanceFormContext({ instance, hideAdvancedFeatures });-const {- events,- isCreating,- valueChanged,- basicInfo,- adminDataSource,- missingFeature,-} = context;--onMounted(async () => {- if (isCreating.value) {- adminDataSource.value.host = actuatorStore.isDocker- ? "host.docker.internal"- : "127.0.0.1";- if (basicInfo.value.engine === Engine.DYNAMODB) {- adminDataSource.value.host = "";- }- adminDataSource.value.srv = false;- adminDataSource.value.authenticationDatabase = "";- }-});--watch(- () => basicInfo.value.engine,- () => {- if (isCreating.value) {- adminDataSource.value.port = defaultPortForEngine(basicInfo.value.engine);- }- },- {- immediate: true,- }-);--watch(- () => props.instance?.activation,- (val) => {- if (val !== undefined) {- basicInfo.value.activation = val;- }- }-);--useEmitteryEventListener(events, "dismiss", () => {- emit("dismiss");-});--defineExpose({- isEditing: computed(() => !isCreating.value && valueChanged.value),-});-</script>diff --git a/frontend/src/components/InstanceForm/ScanIntervalInput.vue b/frontend/src/components/InstanceForm/ScanIntervalInput.vuedeleted file mode 100644index 043be8d0da..0000000000--- a/frontend/src/components/InstanceForm/ScanIntervalInput.vue+++ /dev/null@@ -1,180 +0,0 @@-<template>- <div- v-if="!hideAdvancedFeatures"- class="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2"- >- <div class="flex items-center gap-x-2">- <label class="textlabel">- {{ $t("instance.scan-interval.self") }}- </label>-- <span v-if="instance.lastSyncTime" class="textinfolabel">- ({{- $t("sql-editor.last-synced", {- time: formatAbsoluteDateTime(- getDateForPbTimestampProtoEs(instance.lastSyncTime)?.getTime() ?? 0- ),- })- }})- </span>- <FeatureBadge- :instance="instance"- :feature="PlanFeature.FEATURE_CUSTOM_INSTANCE_SYNC_TIME"- />- </div>- <div class="textinfolabel">- {{ $t("instance.scan-interval.description") }}- </div>- <div class="flex items-center gap-x-6">- <NRadio- :checked="state.mode === 'DEFAULT'"- :disabled="!allowEdit"- value="DEFAULT"- @click="handleModeChange('DEFAULT')"- >- {{ $t("instance.scan-interval.default-never") }}- </NRadio>-- <div class="flex items-center">- <NRadio- :checked="state.mode === 'CUSTOM'"- :disabled="!allowEdit"- value="CUSTOM"- class="items-center!"- @click="handleModeChange('CUSTOM')"- >- <div class="flex items-center gap-x-1.5">- <span>{{ $t("common.custom") }}</span>- <NInputNumber- :value="state.minutes"- :show-button="false"- :placeholder="`>= ${MIN_MINUTES}`"- size="small"- style="width: 4rem"- :status="state.isValid ? undefined : 'error'"- :disabled="state.mode !== 'CUSTOM'"- @update:value="handleMinuteChange($event as number)"- />- <span v-if="!state.isValid" class="text-error">- {{- $t("instance.scan-interval.min-value", {- value: MIN_MINUTES,- })- }}- </span>- <span v-else>{{ $t("common.minutes") }}</span>- </div>- </NRadio>- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import type { Duration } from "@bufbuild/protobuf/wkt";-import { DurationSchema } from "@bufbuild/protobuf/wkt";-import { NInputNumber, NRadio } from "naive-ui";-import { reactive, watch } from "vue";-import { FeatureBadge } from "@/components/FeatureGuard";-import { getDateForPbTimestampProtoEs } from "@/types";-import type { Instance } from "@/types/proto-es/v1/instance_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import { formatAbsoluteDateTime } from "@/utils";-import { useInstanceFormContext } from "./context";--type Mode = "DEFAULT" | "CUSTOM";-type LocalState = {- mode: Mode;- lastValidDuration: Duration | undefined;- isValid: boolean;- minutes: number | undefined;-};--const MIN_MINUTES = 30;--const props = defineProps<{- scanInterval?: Duration | undefined;- allowEdit: boolean;- instance: Instance;-}>();--const emit = defineEmits<{- (event: "update:scan-interval", interval: Duration | undefined): void;-}>();--const { hideAdvancedFeatures } = useInstanceFormContext();--const extractStateFromDuration = (- duration: Duration | undefined-): { mode: Mode; minutes: number | undefined } => {- if (!duration || Number(duration.seconds) === 0) {- return {- mode: "DEFAULT",- minutes: undefined,- };- }- return {- mode: "CUSTOM",- minutes: Math.floor(Number(duration.seconds) / 60),- };-};--const state = reactive<LocalState>({- ...extractStateFromDuration(props.scanInterval),- lastValidDuration: props.scanInterval,- isValid: true,-});--const handleModeChange = (targetMode: Mode) => {- if (targetMode === state.mode) {- return;- }- state.mode = targetMode;- if (targetMode === "DEFAULT") {- emit(- "update:scan-interval",- create(DurationSchema, {- seconds: BigInt(0),- })- );- } else {- emit(- "update:scan-interval",- create(DurationSchema, {- seconds: BigInt(24 * 60 * 60),- })- );- }-};--const handleMinuteChange = (minute: number | undefined) => {- state.minutes = minute;- if (!minute || minute < MIN_MINUTES) {- state.isValid = false;- return;- }- state.isValid = true;- emit(- "update:scan-interval",- create(DurationSchema, {- seconds: BigInt(minute * 60),- })- );-};--watch(- () => props.scanInterval,- (duration) => {- Object.assign(state, extractStateFromDuration(duration));- state.lastValidDuration = duration;- state.isValid = true;- }-);--defineExpose({- validate: () => {- return state.isValid;- },-});-</script>diff --git a/frontend/src/components/InstanceForm/SpannerHostInput.vue b/frontend/src/components/InstanceForm/SpannerHostInput.vuedeleted file mode 100644index f0edc13dd4..0000000000--- a/frontend/src/components/InstanceForm/SpannerHostInput.vue+++ /dev/null@@ -1,117 +0,0 @@-<template>- <div class="grid grid-cols-2 gap-x-2 gap-y-1">- <div>- <label class="textlabel">- {{ $t("instance.project-id") }}- <span style="color: red">*</span>- </label>- <NInput- v-model:value="state.projectId"- required- placeholder="projectId"- class="mt-1 w-full"- :status="state.dirty && !isValidProjectId ? 'error' : undefined"- :disabled="!allowEdit"- />- </div>- <div>- <label class="textlabel">- {{ $t("instance.instance-id") }}- <span style="color: red">*</span>- </label>- <NInput- v-model:value="state.instanceId"- required- placeholder="instanceId"- class="mt-1 w-full"- :status="state.dirty && !isValidInstanceId ? 'error' : undefined"- :disabled="!allowEdit"- />- </div>-- <p class="col-span-2 textinfolabel">- {{ $t("instance.find-gcp-project-id-and-instance-id") }}- <a- href="https://docs.bytebase.com/get-started/connect/gcp?source=console"- target="_blank"- class="normal-link inline-flex items-center"- >- {{ $t("common.detailed-guide") }}- <heroicons-outline:external-link class="w-4 h-4 ml-1" />- </a>- </p>- </div>-</template>--<script lang="ts" setup>-import { NInput } from "naive-ui";-import { computed, reactive, watch } from "vue";--type LocalState = {- projectId: string;- instanceId: string;- dirty: boolean;-};--const props = defineProps<{- host: string;- allowEdit: boolean;-}>();--const emit = defineEmits<{- (name: "update:host", host: string): void;-}>();--const RE =- /^projects\/(?<PROJECT_ID>(?:[a-z]|[-.:]|[0-9])*)\/instances\/(?<INSTANCE_ID>(?:[a-z]|[-]|[0-9])*)$/;-const RE_PROJECT_ID = /^(?:[a-z]|[-.:]|[0-9])+$/;-const RE_INSTANCE_ID = /^(?:[a-z]|[-]|[0-9])+$/;--const state = reactive<LocalState>({- projectId: "",- instanceId: "",- dirty: false,-});--const isValidProjectId = computed(() => {- return RE_PROJECT_ID.test(state.projectId);-});--const isValidInstanceId = computed(() => {- return RE_INSTANCE_ID.test(state.instanceId);-});--const update = () => {- if (!isValidProjectId.value || !isValidInstanceId.value) {- emit("update:host", "");- return;- }- const host = `projects/${state.projectId}/instances/${state.instanceId}`;- emit("update:host", host);-};--const parseProjectIdFromHost = (host: string) => {- const match = host.match(RE);- return match?.groups?.PROJECT_ID ?? "";-};--const parseInstanceIdFromHost = (host: string) => {- const match = host.match(RE);- return match?.groups?.INSTANCE_ID ?? "";-};--watch([() => state.projectId, () => state.instanceId], () => {- state.dirty = true;- update();-});--watch(- () => props.host,- (host) => {- if (!host) return;- state.projectId = parseProjectIdFromHost(host);- state.instanceId = parseInstanceIdFromHost(host);- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/InstanceForm/SyncDatabases.vue b/frontend/src/components/InstanceForm/SyncDatabases.vuedeleted file mode 100644index 3480677161..0000000000--- a/frontend/src/components/InstanceForm/SyncDatabases.vue+++ /dev/null@@ -1,191 +0,0 @@-<template>- <div- v-if="!hideAdvancedFeatures"- class="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2"- >- <div v-if="showLabel" class="flex items-center gap-x-2">- <label class="textlabel">- {{ $t("instance.sync-databases.self") }}- </label>- </div>- <div class="textinfolabel">- {{ $t("instance.sync-databases.description") }}- </div>- <div class="flex flex-col gap-y-2">- <NCheckbox v-model:checked="state.syncAll" :disabled="!allowEdit">- {{ $t("instance.sync-databases.sync-all") }}- </NCheckbox>- <div v-if="!state.syncAll">- <BBSpin v-if="state.loading" class="opacity-60" />- <div v-else class="border rounded-xs p-2 flex flex-col gap-y-2">- <SearchBox- v-model:value="state.searchText"- style="max-width: 100%"- :placeholder="$t('instance.sync-databases.search-database')"- />- <NTree- class="sync-database-tree"- block-line- checkable- style="max-height: 250px"- :pattern="state.searchText"- virtual-scroll- :check-on-click="true"- :data="treeData"- :show-irrelevant-nodes="false"- :render-label="renderLabel"- :disabled="!allowEdit"- v-model:checked-keys="state.selectedDatabases"- />- <NInput- clearable- size="small"- :placeholder="$t('instance.sync-databases.add-database')"- v-model:value="state.inputDatabase"- :disabled="!allowEdit"- @keydown="handleKeyDown"- />- </div>- </div>- </div>- </div>-</template>--<script lang="tsx" setup>-import type { TreeOption } from "naive-ui";-import { NCheckbox, NInput, NTree } from "naive-ui";-import { computed, h, reactive, watch } from "vue";-import { BBSpin } from "@/bbkit";-import { SearchBox } from "@/components/v2";-import { useInstanceV1Store } from "@/store";-import { getHighlightHTMLByKeyWords } from "@/utils";-import { useInstanceFormContext } from "./context";--const props = withDefaults(- defineProps<{- showLabel: boolean;- allowEdit: boolean;- isCreating: boolean;- syncDatabases?: string[];- }>(),- {- syncDatabases: () => [],- }-);--const emit = defineEmits<{- (event: "update:sync-databases", databases: string[]): void;-}>();--interface LocalState {- syncAll: boolean;- loading: boolean;- selectedDatabases: string[];- databaseList: Set<string>;- searchText: string;- inputDatabase: string;-}--const { hideAdvancedFeatures, pendingCreateInstance, instance } =- useInstanceFormContext();-const instanceStore = useInstanceV1Store();--const state = reactive<LocalState>({- syncAll: props.syncDatabases.length === 0,- loading: false,- selectedDatabases: [...props.syncDatabases],- databaseList: new Set<string>(),- searchText: "",- inputDatabase: "",-});--const targetInstance = computed(() => {- return props.isCreating ? pendingCreateInstance.value : instance.value;-});--const fetchAllDatabases = async () => {- if (!targetInstance.value) {- return;- }- state.loading = true;- try {- const resp = await instanceStore.listInstanceDatabases(- targetInstance.value.name,- props.isCreating ? targetInstance.value : undefined- );- state.databaseList = new Set([- ...resp.databases,- ...state.selectedDatabases,- ]);- } finally {- state.loading = false;- }-};--watch(- () => state.syncAll,- async (syncAll) => {- if (!syncAll) {- await fetchAllDatabases();- }- },- { immediate: true }-);--const treeData = computed((): TreeOption[] => {- return [...state.databaseList].map((database) => {- return {- isLeaf: true,- label: database,- key: database,- checkboxDisabled: false,- };- });-});--const renderLabel = ({ option }: { option: TreeOption }) => {- return h("span", {- class: "textinfo text-sm",- innerHTML: getHighlightHTMLByKeyWords(option.label ?? "", state.searchText),- });-};--watch(- () => state.syncAll,- async (syncAll) => {- if (syncAll) {- emit("update:sync-databases", []);- } else {- emit("update:sync-databases", state.selectedDatabases);- }- }-);--watch(- () => state.selectedDatabases,- (selectedDatabases) => {- emit("update:sync-databases", selectedDatabases);- },- { deep: true }-);--const handleKeyDown = (e: KeyboardEvent) => {- if (e.isComposing) return;- const inputDatabase = state.inputDatabase.trim();- if (!inputDatabase) {- return;- }- const { key } = e;- if (key === "Enter") {- state.databaseList.add(inputDatabase);- state.selectedDatabases.push(inputDatabase);- state.inputDatabase = "";- }-};-</script>--<style lang="postcss" scoped>-.sync-database-tree :deep(.n-tree-node-switcher--hide) {- display: none !important;-}-</style>diff --git a/frontend/src/components/InstanceForm/context.ts b/frontend/src/components/InstanceForm/context.tsdeleted file mode 100644index 6a6e8025cb..0000000000--- a/frontend/src/components/InstanceForm/context.ts+++ /dev/null@@ -1,498 +0,0 @@-import { create } from "@bufbuild/protobuf";-import Emittery from "emittery";-import { cloneDeep, isEqual, omit } from "lodash-es";-import { useDialog } from "naive-ui";-import type { InjectionKey, Ref } from "vue";-import { computed, inject, provide, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import {- pushNotification,- useEnvironmentV1Store,- useInstanceV1Store,- useSubscriptionV1Store,-} from "@/store";-import { Engine, State } from "@/types/proto-es/v1/common_pb";-import type {- DataSource,- Instance,-} from "@/types/proto-es/v1/instance_service_pb";-import {- DataSource_AuthenticationType,- DataSource_RedisType,- DataSourceExternalSecret_AuthType,- DataSourceExternalSecret_SecretType,- DataSourceType,- InstanceSchema,-} from "@/types/proto-es/v1/instance_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- convertKVListToLabels,- convertLabelsToKVList,- hasWorkspacePermissionV2,- isValidSpannerHost,-} from "@/utils";-import { extractGrpcErrorMessage } from "@/utils/connect";-import type { LabelListEditor } from "../Label";-import type { ResourceIdField } from "../v2";-import type { EditDataSource } from "./common";-import {- calcDataSourceUpdateMask,- extractBasicInfo,- extractDataSourceEditState,-} from "./common";-import { useInstanceSpecs } from "./specs";--export type LocalState = {- editingDataSourceId: string | undefined;- isTestingConnection: boolean;- isRequesting: boolean;-};--const KEY = Symbol(- "bb.workspace.instance-form"-) as InjectionKey<InstanceFormContext>;--export const provideInstanceFormContext = (baseContext: {- instance: Ref<Instance | undefined>;- hideAdvancedFeatures: Ref<boolean | undefined>;-}) => {- const instanceStore = useInstanceV1Store();- const $d = useDialog();- const { t } = useI18n();- const events = new Emittery<{- dismiss: undefined;- "show-connection-options": undefined;- }>();- const { instance } = baseContext;- const state = ref<LocalState>({- editingDataSourceId: instance.value?.dataSources.find(- (ds) => ds.type === DataSourceType.ADMIN- )?.id,- isTestingConnection: false,- isRequesting: false,- });-- const isCreating = computed(() => instance.value === undefined);- const allowEdit = computed(() => {- if (isCreating.value) return true;-- return (- (instance.value?.state || State.STATE_UNSPECIFIED) === State.ACTIVE &&- hasWorkspacePermissionV2("bb.instances.update")- );- });- const basicInfo = ref(extractBasicInfo(instance.value));- const dataSourceEditState = ref(extractDataSourceEditState(instance.value));-- const labelListEditorRef = ref<InstanceType<typeof LabelListEditor>>();- const labelKVList = ref(- convertLabelsToKVList(basicInfo.value.labels, true /* sort */)- );-- watch(- () => basicInfo.value.labels,- (newLabels) => {- labelKVList.value = convertLabelsToKVList(newLabels, true /* sort */);- }- );-- const adminDataSource = computed(() => {- return dataSourceEditState.value.dataSources.find(- (ds) => ds.type === DataSourceType.ADMIN- )!;- });- const editingDataSource = computed(() => {- const { dataSources, editingDataSourceId } = dataSourceEditState.value;- if (editingDataSourceId === undefined) return undefined;- return dataSources.find((ds) => ds.id === editingDataSourceId);- });- const readonlyDataSourceList = computed(() => {- return dataSourceEditState.value.dataSources.filter(- (ds) => ds.type === DataSourceType.READ_ONLY- );- });- const hasReadOnlyDataSource = computed(() => {- return readonlyDataSourceList.value.length > 0;- });-- const hasReadonlyReplicaFeature = computed(() => {- return useSubscriptionV1Store().hasInstanceFeature(- PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION,- instance.value- );- });-- const resetDataSource = () => {- dataSourceEditState.value = extractDataSourceEditState(instance.value);- };- const missingFeature = ref<PlanFeature | undefined>(undefined);-- const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();-- const environment = computed(() => {- return useEnvironmentV1Store().getEnvironmentByName(- basicInfo.value.environment ?? ""- );- });-- const checkDataSource = (dataSources: DataSource[]) => {- return dataSources.every((ds) => {- if (- ds.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- ) {- // CloudSQL instance name should be {project}:{region}:{cloud sql name}- return /.+:.+:.+/.test(ds.host);- }- if (ds.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM) {- return !!ds.region;- }-- if (basicInfo.value.engine === Engine.ORACLE) {- if (!ds.sid && !ds.serviceName) {- return false;- }- } else if (basicInfo.value.engine === Engine.DATABRICKS) {- if (!ds.warehouseId || !ds.authenticationPrivateKey) {- return false;- }- }-- if (ds.saslConfig?.mechanism?.case === "krbConfig") {- const krbConfig = ds.saslConfig.mechanism.value;- if (- !krbConfig.primary ||- !krbConfig.realm ||- !krbConfig.kdcHost ||- !krbConfig.keytab- ) {- return false;- }- }-- if (!ds.externalSecret) {- return true;- }-- switch (ds.externalSecret.secretType) {- case DataSourceExternalSecret_SecretType.VAULT_KV_V2:- if (- !ds.externalSecret.url ||- !ds.externalSecret.engineName ||- !ds.externalSecret.secretName ||- !ds.externalSecret.passwordKeyName- ) {- return false;- }- break;- case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:- if (- !ds.externalSecret.secretName ||- !ds.externalSecret.passwordKeyName- ) {- return false;- }- break;- case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:- if (!ds.externalSecret.secretName) {- return false;- }- break;- }-- switch (ds.externalSecret.authType) {- case DataSourceExternalSecret_AuthType.TOKEN:- return !!(- ds.externalSecret.authOption?.case === "token" &&- ds.externalSecret.authOption.value- );- case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:- return !!(- ds.externalSecret.authOption?.case === "appRole" &&- ds.externalSecret.authOption.value.roleId &&- ds.externalSecret.authOption.value.secretId- );- }-- return true;- });- };-- const allowCreate = computed(() => {- if (!hasWorkspacePermissionV2("bb.instances.create")) {- return false;- }- if (basicInfo.value.engine === Engine.SPANNER) {- return (- !!basicInfo.value.title.trim() &&- isValidSpannerHost(adminDataSource.value.host)- );- }- if (basicInfo.value.engine === Engine.BIGQUERY) {- return (- !!basicInfo.value.title.trim() && adminDataSource.value.host !== ""- );- }-- // Check Host- if (basicInfo.value.engine !== Engine.DYNAMODB) {- if (adminDataSource.value.host === "") {- return false;- }- }-- // Redis Check Master Name- if (basicInfo.value.engine === Engine.REDIS) {- if (- adminDataSource.value.redisType === DataSource_RedisType.SENTINEL &&- adminDataSource.value.masterName === ""- ) {- return false;- }- }-- const hasLabelErrors =- (labelListEditorRef.value?.flattenErrors ?? []).length > 0;-- return (- !!basicInfo.value.title.trim() &&- resourceIdField.value?.isValidated &&- checkDataSource([adminDataSource.value]) &&- !hasLabelErrors- );- });-- const specs = useInstanceSpecs(basicInfo, adminDataSource, editingDataSource);-- const extractDataSourceFromEdit = (- engine: Engine,- edit: EditDataSource- ): DataSource => {- const { showDatabase, showSSH, showSSL } = specs;- const ds = cloneDeep(- omit(- edit,- "pendingCreate",- "updatedPassword",- "useEmptyPassword",- "updatedMasterPassword",- "useEmptyMasterPassword",- "updateSsl"- )- );- if (edit.updatedPassword) {- ds.password = edit.updatedPassword;- }- if (edit.useEmptyPassword) {- ds.password = "";- }-- if (edit.updatedMasterPassword) {- ds.masterPassword = edit.updatedMasterPassword;- }- if (edit.useEmptyMasterPassword) {- ds.masterPassword = "";- }-- // Clean up unused fields for certain engine types.- if (!showDatabase.value) {- ds.database = "";- }- if (engine !== Engine.ORACLE) {- ds.sid = "";- ds.serviceName = "";- }- if (engine !== Engine.MONGODB) {- ds.srv = false;- ds.authenticationDatabase = "";- }- if (!showSSH.value) {- ds.sshHost = "";- ds.sshPort = "";- ds.sshUser = "";- ds.sshPassword = "";- ds.sshPrivateKey = "";- }- if (!showSSL.value) {- ds.sslCa = "";- ds.sslCert = "";- ds.sslKey = "";- }-- return ds;- };-- const pendingCreateInstance = computed(() => {- const currentLabels = convertKVListToLabels(labelKVList.value, false);- const instance: Instance = create(InstanceSchema, {- ...basicInfo.value,- labels: currentLabels,- engineVersion: "",- dataSources: [],- });- if (editingDataSource.value) {- const dataSourceCreate = extractDataSourceFromEdit(- instance.engine,- adminDataSource.value- );- instance.dataSources = [dataSourceCreate];- }- return instance;- });-- const testConnection = async (- editingDS: EditDataSource,- silent = false- ): Promise<{ success: boolean; message: string }> => {- if (!editingDataSource.value) {- throw new Error("should never reach this line");- }-- // In different scenes, we use different methods to test connection.- const ok = () => {- if (!silent) {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-connected-instance"),- });- }- state.value.isTestingConnection = false;- return { success: true, message: "" };- };- const fail = (host: string, err: unknown) => {- let error = extractGrpcErrorMessage(err);- if (!silent) {- if (host === "localhost" || host === "127.0.0.1") {- error = `${error}\n\n${t("instance.failed-to-connect-instance-localhost")}`;- }- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("instance.failed-to-connect-instance"),- description: error,- // Manual hide, because user may need time to inspect the error- manualHide: true,- });- }- state.value.isTestingConnection = false;- return { success: false, message: error };- };- state.value.isTestingConnection = true;- if (isCreating.value) {- // When creating new instance, use- // adminDataSource + CreateInstanceRequest.validateOnly = true- const instance: Instance = create(InstanceSchema, {- ...basicInfo.value,- engineVersion: "",- dataSources: [],- });- const dataSourceCreate = extractDataSourceFromEdit(- instance.engine,- editingDS- );- instance.dataSources = [dataSourceCreate];- try {- await instanceStore.createInstance(instance, true /* validateOnly */);- return ok();- } catch (err) {- return fail(dataSourceCreate.host, err);- }- } else {- // Editing existed instance.- const ds = extractDataSourceFromEdit(instance.value!.engine, editingDS);- if (editingDS.pendingCreate) {- // When read-only data source is about to be created, use- // editingDataSource + AddDataSourceRequest.validateOnly = true- try {- await instanceStore.createDataSource({- instance: instance.value!.name,- dataSource: ds,- validateOnly: true,- });- return ok();- } catch (err) {- return fail(ds.host, err);- }- } else {- // When a data source (admin or read-only) has been edited, use- // editingDataSource + UpdateDataSourceRequest.validateOnly = true- try {- const original = instance.value!.dataSources.find(- (ds) => ds.id === editingDS.id- );- if (!original) {- throw new Error("should never reach this line");- }- const updateMask = calcDataSourceUpdateMask(ds, original, editingDS);- await instanceStore.updateDataSource({- instance: instance.value!.name,- dataSource: ds,- updateMask,- validateOnly: true,- });- return ok();- } catch (err) {- return fail(ds.host, err);- }- }- }- };-- const valueChanged = computed(() => {- if (instance.value?.state === State.DELETED) {- return false;- }- const original = {- basicInfo: extractBasicInfo(instance.value),- dataSources: extractDataSourceEditState(instance.value).dataSources,- };- const currentLabels = convertKVListToLabels(labelKVList.value, false);- const editing = {- basicInfo: {- ...basicInfo.value,- labels: currentLabels,- },- dataSources: dataSourceEditState.value.dataSources,- };- return !isEqual(editing, original);- });-- const context = {- ...baseContext,- $d,- events,- state,- specs,- isCreating,- allowEdit,- allowCreate,- resourceIdField,- environment,- basicInfo,- labelListEditorRef,- labelKVList,- dataSourceEditState,- adminDataSource,- editingDataSource,- readonlyDataSourceList,- hasReadOnlyDataSource,- hasReadonlyReplicaFeature,- missingFeature,- checkDataSource,- resetDataSource,- extractDataSourceFromEdit,- testConnection,- pendingCreateInstance,- valueChanged,- };- provide(KEY, context);-- return context;-};--export const useInstanceFormContext = () => {- return inject(KEY)!;-};--export type InstanceFormContext = ReturnType<typeof provideInstanceFormContext>;diff --git a/frontend/src/components/InstanceForm/index.ts b/frontend/src/components/InstanceForm/index.tsindex ff3d73a499..5760defb79 100644--- a/frontend/src/components/InstanceForm/index.ts+++ b/frontend/src/components/InstanceForm/index.ts@@ -1,7 +1 @@-import Buttons from "./Buttons.vue";-import Form from "./Form.vue";-import InstanceForm from "./InstanceForm.vue";--export default InstanceForm;--export { InstanceForm, Form, Buttons };+export { EngineIconPath, defaultPortForEngine } from "./constants";diff --git a/frontend/src/components/InstanceForm/specs.ts b/frontend/src/components/InstanceForm/specs.tsdeleted file mode 100644index 8db5ae3da2..0000000000--- a/frontend/src/components/InstanceForm/specs.ts+++ /dev/null@@ -1,87 +0,0 @@-import { computed, type Ref } from "vue";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";-import {- instanceV1HasExtraParameters,- instanceV1HasSSH,- instanceV1HasSSL,-} from "@/utils";-import type { BasicInfo, EditDataSource } from "./common";-import { defaultPortForEngine } from "./constants";--export const useInstanceSpecs = (- basicInfo: Ref<BasicInfo>,- adminDataSource: Ref<EditDataSource>,- editingDataSource: Ref<EditDataSource | undefined>-) => {- const showDatabase = computed((): boolean => {- return (- (basicInfo.value.engine === Engine.POSTGRES ||- basicInfo.value.engine === Engine.REDSHIFT ||- basicInfo.value.engine === Engine.COCKROACHDB ||- basicInfo.value.engine === Engine.MSSQL) &&- editingDataSource.value?.type === DataSourceType.ADMIN- );- });- const showSSL = computed((): boolean => {- return instanceV1HasSSL(basicInfo.value.engine);- });- const showSSH = computed((): boolean => {- return instanceV1HasSSH(basicInfo.value.engine);- });- const isEngineBeta = (_engine: Engine): boolean => {- return false;- };- const defaultPort = computed(() => {- return defaultPortForEngine(basicInfo.value.engine);- });- const instanceLink = computed(() => {- if (basicInfo.value.engine === Engine.SNOWFLAKE) {- if (adminDataSource.value.host) {- return `https://${- adminDataSource.value.host.split("@")[0]- }.snowflakecomputing.com/console`;- }- }- return basicInfo.value.externalLink ?? "";- });- const allowEditPort = computed(() => {- // MongoDB doesn't support specify port if using srv record.- return !(- basicInfo.value.engine === Engine.MONGODB && editingDataSource.value?.srv- );- });-- const allowUsingEmptyPassword = computed(() => {- return basicInfo.value.engine !== Engine.SPANNER;- });- const showAuthenticationDatabase = computed((): boolean => {- return basicInfo.value.engine === Engine.MONGODB;- });- const hasReadonlyReplicaHost = computed((): boolean => {- return basicInfo.value.engine !== Engine.SPANNER;- });- const hasReadonlyReplicaPort = computed((): boolean => {- return basicInfo.value.engine !== Engine.SPANNER;- });- const hasExtraParameters = computed((): boolean => {- return instanceV1HasExtraParameters(basicInfo.value.engine);- });-- return {- showDatabase,- showSSL,- showSSH,- isEngineBeta,- defaultPort,- instanceLink,- allowEditPort,- allowUsingEmptyPassword,- showAuthenticationDatabase,- hasReadonlyReplicaHost,- hasReadonlyReplicaPort,- hasExtraParameters,- };-};--export type InstanceSpecs = ReturnType<typeof useInstanceSpecs>;diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 91b44e5ccb..50eb29a46f 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1532,29 +1532,21 @@"vault-auth-type": {"self": "Auth type","token": {- "self": "Token",- "tips": "A root token without TTL."+ "self": "Token"},"approle": {"self": "AppRole","role-id": "Auth role id","secret-id": "Auth secret id",- "secret-id-plain-text": "Plain text for role secret id",- "secret-id-environment": "Environment name for role secret id","secret-plain-text": "Plain text",- "secret-env-name": "Environment name",- "secret-tips": "An unwrapped secret id without TTL. You can use plain text, or put it into the environment or local file. {learn_more}"+ "secret-env-name": "Environment name"}},"vault-secret-engine-name": "Secret engine name","vault-secret-path": "Secret path","vault-secret-key": "Secret key","vault-secret-engine-tips": "Only support KV v2 engine.",- "vault-tls-config": "Vault TLS Configuration (Optional)",- "verify-vault-certificate": "Verify Vault TLS certificate",- "vault-ca-cert": "Vault CA Certificate",- "vault-client-cert": "Vault Client Certificate",- "vault-client-key": "Vault Client Key"+ "vault-tls-config": "Vault TLS Configuration (Optional)"},"external-secret": {"secret-name": "Secret name",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 0f9a846c1a..5759acc0dd 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1532,29 +1532,21 @@"vault-auth-type": {"self": "Tipo de autenticación","token": {- "self": "Token",- "tips": "Un token raíz sin TTL."+ "self": "Token"},"approle": {"self": "AppRole","role-id": "Auth role id","secret-id": "Auth secret id",- "secret-id-plain-text": "Texto sin formato para identificación secreta de rol",- "secret-id-environment": "Nombre del entorno para la identificación secreta del rol","secret-plain-text": "Texto sin formato",- "secret-env-name": "Nombre del entorno",- "secret-tips": "Una identificación secreta desenvuelta sin TTL. Puede utilizar texto sin formato o colocarlo en el entorno o en el archivo local. {learn_more}"+ "secret-env-name": "Nombre del entorno"}},"vault-secret-engine-name": "Secret engine name","vault-secret-path": "Secret path","vault-secret-key": "Secret key","vault-secret-engine-tips": "Solo admite motor KV v2.",- "vault-tls-config": "Configuración TLS de Vault (opcional)",- "verify-vault-certificate": "Verificar certificado TLS de Vault",- "vault-ca-cert": "Certificado de CA de Vault",- "vault-client-cert": "Certificado de cliente de Vault",- "vault-client-key": "Clave de cliente de Vault"+ "vault-tls-config": "Configuración TLS de Vault (opcional)"},"external-secret": {"secret-name": "Nombre secreto",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 506774eccc..e5850ffd81 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1532,29 +1532,21 @@"vault-auth-type": {"self": "認証タイプ","token": {- "self": "トークン",- "tips": "有効期限のないルートトークン"+ "self": "トークン"},"approle": {"self": "AppRole","role-id": "認証ロールID","secret-id": "認証シークレットID",- "secret-id-plain-text": "シークレットIDのプレーンテキスト",- "secret-id-environment": "シークレットIDを格納する環境変数の名前","secret-plain-text": "プレーンテキスト",- "secret-env-name": "環境変数名",- "secret-tips": "有効期限のないカプセル化されていないシークレット ID は、プレーン テキスト、環境変数名、またはファイル パスを使用できます。 {learn_more}"+ "secret-env-name": "環境変数名"}},"vault-secret-engine-name": "シークレットエンジン名","vault-secret-path": "秘密の道","vault-secret-key": "秘密鍵","vault-secret-engine-tips": "KV v2 ストレージのみをサポートします",- "vault-tls-config": "Vault TLS 構成 (オプション)",- "verify-vault-certificate": "Vault TLS証明書を確認する",- "vault-ca-cert": "Vault CA 証明書",- "vault-client-cert": "Vaultクライアント証明書",- "vault-client-key": "Vaultクライアントキー"+ "vault-tls-config": "Vault TLS 構成 (オプション)"},"external-secret": {"secret-name": "秘密の名前",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 12351247d8..0132161edb 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1532,29 +1532,21 @@"vault-auth-type": {"self": "Loại xác thực","token": {- "self": "Mã thông báo",- "tips": "Mã thông báo gốc không có TTL."+ "self": "Mã thông báo"},"approle": {"self": "AppRole","role-id": "ID vai trò xác thực","secret-id": "ID bí mật xác thực",- "secret-id-plain-text": "Văn bản thuần cho id bí mật vai trò",- "secret-id-environment": "Tên môi trường cho id bí mật vai trò","secret-plain-text": "Văn bản thuần",- "secret-env-name": "Tên môi trường",- "secret-tips": "Id bí mật không được bao bọc không có TTL. Bạn có thể sử dụng văn bản thuần túy hoặc đưa nó vào môi trường hoặc tệp cục bộ. {learn_more}"+ "secret-env-name": "Tên môi trường"}},"vault-secret-engine-name": "Tên công cụ bí mật","vault-secret-path": "Đường dẫn bí mật","vault-secret-key": "Khóa bí mật","vault-secret-engine-tips": "Chỉ hỗ trợ công cụ KV v2.",- "vault-tls-config": "Cấu hình Vault TLS (Tùy chọn)",- "verify-vault-certificate": "Xác minh chứng chỉ TLS của Vault",- "vault-ca-cert": "Chứng chỉ Vault CA",- "vault-client-cert": "Chứng chỉ máy khách Vault",- "vault-client-key": "Khóa máy khách Vault"+ "vault-tls-config": "Cấu hình Vault TLS (Tùy chọn)"},"external-secret": {"secret-name": "Tên bí mật",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 3e89caf68d..e891cbc7f1 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1532,29 +1532,21 @@"vault-auth-type": {"self": "认证方式","token": {- "self": "Token",- "tips": "没有过期时限的根 token"+ "self": "Token"},"approle": {"self": "AppRole","role-id": "Auth role id","secret-id": "Auth secret id",- "secret-id-plain-text": "Secret id 明文",- "secret-id-environment": "储存 secret id 的环境变量名","secret-plain-text": "明文",- "secret-env-name": "环境变量名",- "secret-tips": "未封装、无有效期限的 secret id,您可以使用明文、环境变量名或文件路径。{learn_more}"+ "secret-env-name": "环境变量名"}},"vault-secret-engine-name": "Secret engine name","vault-secret-path": "Secret path","vault-secret-key": "Secret key","vault-secret-engine-tips": "仅支持 KV v2 储存",- "vault-tls-config": "Vault TLS 配置(可选)",- "verify-vault-certificate": "验证 Vault TLS 证书",- "vault-ca-cert": "Vault CA 证书",- "vault-client-cert": "Vault 客户端证书",- "vault-client-key": "Vault 客户端密钥"+ "vault-tls-config": "Vault TLS 配置(可选)"},"external-secret": {"secret-name": "Secret name",diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsxindex 6fd7724954..490251a381 100644--- a/frontend/src/react/components/database/DatabaseTable.tsx+++ b/frontend/src/react/components/database/DatabaseTable.tsx@@ -33,8 +33,8 @@ export interface DatabaseTableProps {filter: DatabaseFilter;parent?: string;mode?: DatabaseTableMode;- selectedNames: Set<string>;- onSelectedNamesChange: (names: Set<string>) => void;+ selectedNames?: Set<string>;+ onSelectedNamesChange?: (names: Set<string>) => void;refreshToken?: number;}@@ -155,8 +155,11 @@ export function DatabaseTable({}}, [isFetchingMore, fetchDatabases]);+ const showSelection = !!selectedNames && !!onSelectedNamesChange;+const toggleSelection = useCallback((name: string) => {+ if (!selectedNames || !onSelectedNamesChange) return;const next = new Set(selectedNames);if (next.has(name)) next.delete(name);else next.add(name);@@ -166,12 +169,13 @@ export function DatabaseTable({);const toggleSelectAll = useCallback(() => {+ if (!selectedNames || !onSelectedNamesChange) return;if (selectedNames.size === databases.length) {onSelectedNamesChange(new Set());} else {onSelectedNamesChange(new Set(databases.map((db) => db.name)));}- }, [databases, selectedNames.size, onSelectedNamesChange]);+ }, [databases, selectedNames, onSelectedNamesChange]);const handleRowClick = useCallback((db: Database, e: React.MouseEvent) => {const url = router.resolve(autoDatabaseRoute(db)).fullPath;@@ -197,9 +201,10 @@ export function DatabaseTable({};const allSelected =- databases.length > 0 && selectedNames.size === databases.length;+ databases.length > 0 && (selectedNames?.size ?? 0) === databases.length;const someSelected =- selectedNames.size > 0 && selectedNames.size < databases.length;+ (selectedNames?.size ?? 0) > 0 &&+ (selectedNames?.size ?? 0) < databases.length;const headerCheckboxRef = useRef<HTMLInputElement>(null);useEffect(() => {if (headerCheckboxRef.current) {@@ -215,15 +220,17 @@ export function DatabaseTable({<table className="w-full text-sm"><thead><tr className="bg-gray-50 border-b border-control-border">- <th className="w-12 px-4 py-2">- <input- ref={headerCheckboxRef}- type="checkbox"- checked={allSelected}- onChange={toggleSelectAll}- className="rounded-xs border-control-border"- />- </th>+ {showSelection && (+ <th className="w-12 px-4 py-2">+ <input+ ref={headerCheckboxRef}+ type="checkbox"+ checked={allSelected}+ onChange={toggleSelectAll}+ className="rounded-xs border-control-border"+ />+ </th>+ )}<thclassName="px-4 py-2 text-left font-medium min-w-[200px] cursor-pointer select-none"onClick={() => toggleSort("name")}@@ -296,7 +303,7 @@ export function DatabaseTable({</tr>) : (databases.map((db, i) => {- const isSelected = selectedNames.has(db.name);+ const isSelected = selectedNames?.has(db.name) ?? false;const instanceResource = getInstanceResource(db);return (<tr@@ -307,15 +314,17 @@ export function DatabaseTable({)}onClick={(e) => handleRowClick(db, e)}>- <td className="w-12 px-4 py-2">- <input- type="checkbox"- checked={isSelected}- onChange={() => toggleSelection(db.name)}- onClick={(e) => e.stopPropagation()}- className="rounded-xs border-control-border"- />- </td>+ {showSelection && (+ <td className="w-12 px-4 py-2">+ <input+ type="checkbox"+ checked={isSelected}+ onChange={() => toggleSelection(db.name)}+ onClick={(e) => e.stopPropagation()}+ className="rounded-xs border-control-border"+ />+ </td>+ )}<td className="px-4 py-2"><div className="flex items-center gap-x-2"><imgdiff --git a/frontend/src/react/components/instance/CreateDataSourceExample.tsx b/frontend/src/react/components/instance/CreateDataSourceExample.tsxnew file mode 100644index 0000000000..8df2db7c64--- /dev/null+++ b/frontend/src/react/components/instance/CreateDataSourceExample.tsx@@ -0,0 +1,530 @@+import { useCallback, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ DATASOURCE_ADMIN_USER_NAME,+ DATASOURCE_READONLY_USER_NAME,+ languageOfEngineV1,+} from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ DataSource_AuthenticationType,+ DataSourceType,+} from "@/types/proto-es/v1/instance_service_pb";++export interface CreateDataSourceExampleProps {+ engine: Engine;+ dataSourceType: DataSourceType;+ authenticationType: DataSource_AuthenticationType;+ createInstanceFlag: boolean;+ className?: string;+}++function getGrantStatement(+ engine: Engine,+ dataSourceType: DataSourceType,+ authenticationType: DataSource_AuthenticationType+): string {+ if (dataSourceType === DataSourceType.ADMIN) {+ const createUserStatement = `CREATE USER ${DATASOURCE_ADMIN_USER_NAME}@'%' IDENTIFIED BY 'YOUR_DB_PWD';`;+ switch (engine) {+ case Engine.MYSQL:+ if (+ authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ } else if (+ authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM+ ) {+ return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME}@'%' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';\n\nALTER USER '${DATASOURCE_ADMIN_USER_NAME}'@'%' REQUIRE SSL;\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ }+ return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \n/*!80000 , SET_USER_ID */\nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ case Engine.TIDB:+ return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nLOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ case Engine.MARIADB:+ return `${createUserStatement}\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, \nRELOAD, LOCK TABLES, REPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ case Engine.OCEANBASE:+ return `${createUserStatement}\n\nGRANT ALTER, CREATE, CREATE VIEW, DELETE, DROP, INDEX, INSERT, \nPROCESS, SELECT, SHOW DATABASES, SHOW VIEW, UPDATE, USAGE, \nREPLICATION CLIENT, REPLICATION SLAVE \nON *.* to ${DATASOURCE_ADMIN_USER_NAME}@'%';`;+ case Engine.CLICKHOUSE:+ return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALL ON *.* TO ${DATASOURCE_ADMIN_USER_NAME} WITH GRANT OPTION;`;+ case Engine.SNOWFLAKE:+ return [+ "-- Option 1: grant ACCOUNTADMIN role",+ "",+ `CREATE OR REPLACE USER ${DATASOURCE_ADMIN_USER_NAME} PASSWORD = 'YOUR_DB_PWD'`,+ 'DEFAULT_ROLE = "ACCOUNTADMIN"',+ "DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';",+ "",+ `GRANT ROLE "ACCOUNTADMIN" TO USER ${DATASOURCE_ADMIN_USER_NAME};`,+ "",+ "-- Option 2: grant more granular privileges",+ "",+ "CREATE OR REPLACE ROLE BYTEBASE;",+ "",+ "-- If using non-enterprise edition, the following commands may encounter error likes 'Unsupported feature GRANT/REVOKE APPLY TAG', you can skip those unsupported GRANTs.",+ "-- Grant the least privileges required by Bytebase ",+ "",+ "GRANT CREATE DATABASE, EXECUTE TASK, IMPORT SHARE, APPLY MASKING POLICY, APPLY ROW ACCESS POLICY, APPLY TAG ON ACCOUNT TO ROLE BYTEBASE;",+ "",+ "GRANT IMPORTED PRIVILEGES ON DATABASE SNOWFLAKE TO ROLE BYTEBASE;",+ "",+ 'GRANT USAGE ON WAREHOUSE "YOUR_COMPUTE_WAREHOUSE" TO ROLE BYTEBASE;',+ "",+ "CREATE OR REPLACE USER BYTEBASE",+ " PASSWORD = 'YOUR_PWD'",+ ' DEFAULT_ROLE = "BYTEBASE"',+ ' DEFAULT_WAREHOUSE = "YOUR_COMPUTE_WAREHOUSE";',+ "",+ 'GRANT ROLE "BYTEBASE" TO USER BYTEBASE;',+ "",+ 'GRANT ROLE "BYTEBASE" TO ROLE SYSADMIN;',+ "",+ "-- For each database to be managed by Bytebase, you need to grant the following privileges",+ "",+ "GRANT ALL PRIVILEGES ON DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "-- Then, grant the required schema object privileges on the database to the Bytebase role",+ "GRANT ALL PRIVILEGES ON ALL EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "-- ALERT and POLICY are the features in Snowflake Enterprise Edition, you can skip those GRANTs if you are using standard edition.",+ "GRANT ALL PRIVILEGES ON ALL ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "GRANT ALL PRIVILEGES ON FUTURE SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ "",+ "-- PIPE are not allowed to be bulk granted, you need to grant them one by one.",+ "GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE;",+ ].join("\n");+ case Engine.POSTGRES:+ if (+ authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT pg_write_all_data TO "${DATASOURCE_ADMIN_USER_NAME}@{project-id}.iam";\n\n-- If you need to create databases via Bytebase\nALTER USER "${DATASOURCE_ADMIN_USER_NAME}@{project-id}.iam" WITH CREATEDB;`;+ } else if (+ authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM+ ) {+ return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME};\n\nGRANT rds_iam TO ${DATASOURCE_ADMIN_USER_NAME};\n\nGRANT pg_write_all_data TO ${DATASOURCE_ADMIN_USER_NAME};\n\n-- If you need to create databases via Bytebase\nALTER USER ${DATASOURCE_ADMIN_USER_NAME} WITH CREATEDB;`;+ }+ return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER ${DATASOURCE_ADMIN_USER_NAME} WITH SUPERUSER;`;+ case Engine.REDSHIFT:+ return `CREATE USER ${DATASOURCE_ADMIN_USER_NAME} WITH PASSWORD 'YOUR_DB_PWD' CREATEUSER CREATEDB;`;+ case Engine.MONGODB:+ return `use admin;\ndb.createUser({\n user: "${DATASOURCE_ADMIN_USER_NAME}",\n pwd: "YOUR_DB_PWD",\n roles: [\n {role: "readWriteAnyDatabase", db: "admin"},\n {role: "dbAdminAnyDatabase", db: "admin"},\n {role: "userAdminAnyDatabase", db: "admin"}\n ]\n});`;+ case Engine.SPANNER:+ return "";+ case Engine.BIGQUERY:+ return "";+ case Engine.DYNAMODB:+ return "";+ case Engine.COCKROACHDB:+ return "";+ case Engine.REDIS:+ return `ACL SETUSER ${DATASOURCE_ADMIN_USER_NAME} on >YOUR_DB_PWD +@all &*`;+ case Engine.MSSQL:+ return `-- If you use Cloud RDS, you need to checkout their documentation for setting up a semi-super privileged user.\nCREATE LOGIN ${DATASOURCE_ADMIN_USER_NAME} WITH PASSWORD = 'YOUR_DB_PWD';\nALTER SERVER ROLE sysadmin ADD MEMBER ${DATASOURCE_ADMIN_USER_NAME};`;+ case Engine.ORACLE:+ return `-- If you use Cloud RDS, you need to checkout their documentation for setting up a semi-super privileged user.\nCREATE USER ${DATASOURCE_ADMIN_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';\nGRANT ALL PRIVILEGES TO ${DATASOURCE_ADMIN_USER_NAME};`;+ }+ } else {+ const mysqlReadonlyStatement = `CREATE USER ${DATASOURCE_READONLY_USER_NAME}@'%' IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;+ switch (engine) {+ case Engine.MYSQL:+ if (+ authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;+ } else if (+ authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM+ ) {+ return `CREATE USER ${DATASOURCE_READONLY_USER_NAME}@'%' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';\n\nALTER USER '${DATASOURCE_READONLY_USER_NAME}'@'%' REQUIRE SSL;\n\nGRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to ${DATASOURCE_READONLY_USER_NAME}@'%';`;+ }+ return mysqlReadonlyStatement;+ case Engine.TIDB:+ case Engine.OCEANBASE:+ return mysqlReadonlyStatement;+ case Engine.CLICKHOUSE:+ return `CREATE USER ${DATASOURCE_READONLY_USER_NAME} IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SHOW TABLES, SELECT ON database.* TO ${DATASOURCE_READONLY_USER_NAME};`;+ case Engine.SNOWFLAKE:+ return [+ "-- Option 1: grant ACCOUNTADMIN role",+ "",+ `CREATE OR REPLACE USER ${DATASOURCE_READONLY_USER_NAME} PASSWORD = 'YOUR_DB_PWD'`,+ 'DEFAULT_ROLE = "ACCOUNTADMIN"',+ "DEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';",+ "",+ `GRANT ROLE "ACCOUNTADMIN" TO USER ${DATASOURCE_READONLY_USER_NAME};`,+ "",+ "-- Option 2: grant more granular privileges",+ "",+ "CREATE OR REPLACE ROLE BYTEBASE_READER;",+ "",+ "-- If using non-enterprise edition, the following commands may encounter error likes 'Unsupported feature GRANT/REVOKE APPLY TAG', you can skip those unsupported GRANTs.",+ "-- Grant the least privileges required by Bytebase ",+ "",+ "GRANT IMPORT SHARE TO ROLE BYTEBASE_READER;",+ "",+ "GRANT IMPORTED PRIVILEGES ON DATABASE SNOWFLAKE TO ROLE BYTEBASE_READER;",+ "",+ 'GRANT USAGE ON WAREHOUSE "YOUR_COMPUTE_WAREHOUSE" TO ROLE BYTEBASE_READER;',+ "",+ "CREATE OR REPLACE USER BYTEBASE_READER",+ " PASSWORD = 'YOUR_PWD'",+ ' DEFAULT_ROLE = "BYTEBASE_READER"',+ ' DEFAULT_WAREHOUSE = "YOUR_COMPUTE_WAREHOUSE";',+ "",+ 'GRANT ROLE "BYTEBASE_READER" TO USER BYTEBASE_READER;',+ "",+ 'GRANT ROLE "BYTEBASE_READER" TO ROLE SYSADMIN;',+ "",+ "-- For each database to be managed by Bytebase, you need to grant the following privileges",+ "",+ "GRANT ALL PRIVILEGES ON DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE SCHEMAS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "-- Then, grant the required schema object privileges on the database to the Bytebase role",+ "GRANT ALL PRIVILEGES ON ALL EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE EVENT TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE EXTERNAL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE FILE FORMATS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE FUNCTIONS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE MATERIALIZED VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE PROCEDURES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE SEQUENCES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE STAGES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE STREAMS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE TABLES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE TASKS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE VIEWS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "-- ALERT and POLICY are the features in Snowflake Enterprise Edition, you can skip those GRANTs if you are using standard edition.",+ "GRANT ALL PRIVILEGES ON ALL ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE ALERTS IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE PASSWORD POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE ROW ACCESS POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE MASKING POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "GRANT ALL PRIVILEGES ON ALL SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "GRANT ALL PRIVILEGES ON FUTURE SESSION POLICIES IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ "",+ "-- PIPE are not allowed to be bulk granted, you need to grant them one by one.",+ "GRANT ALL PRIVILEGES ON PIPE {{PIPE_NAME}} IN DATABASE {{YOUR_DB_NAME}} TO ROLE BYTEBASE_READER;",+ ].join("\n");+ case Engine.POSTGRES:+ if (+ authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return `GRANT pg_read_all_data TO "${DATASOURCE_READONLY_USER_NAME}@{project-id}.iam";`;+ } else if (+ authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM+ ) {+ return `CREATE USER ${DATASOURCE_READONLY_USER_NAME};\n\nGRANT rds_iam TO ${DATASOURCE_READONLY_USER_NAME};\n\nGRANT pg_read_all_data TO ${DATASOURCE_READONLY_USER_NAME};`;+ }+ return `CREATE USER ${DATASOURCE_READONLY_USER_NAME} WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nGRANT pg_read_all_data TO ${DATASOURCE_READONLY_USER_NAME};`;+ case Engine.MONGODB:+ return `use admin;\ndb.createUser({\n user: "${DATASOURCE_READONLY_USER_NAME}",\n pwd: passwordPrompt(),\n roles: [\n {role: "readAnyDatabase", db: "admin"}\n ]\n});`;+ case Engine.SPANNER:+ return "";+ case Engine.BIGQUERY:+ return "";+ case Engine.DYNAMODB:+ return "";+ case Engine.COCKROACHDB:+ return "";+ case Engine.REDIS:+ return `ACL SETUSER ${DATASOURCE_READONLY_USER_NAME} on >YOUR_DB_PWD +@read &*`;+ }+ }+ return "";+}++function EngineSpecificDescription({+ engine,+ authenticationType,+ userName,+}: {+ engine: Engine;+ authenticationType: DataSource_AuthenticationType;+ userName: string;+}) {+ const { t } = useTranslation();++ if (+ engine === Engine.MYSQL ||+ engine === Engine.TIDB ||+ engine === Engine.OCEANBASE+ ) {+ if (+ authenticationType === DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return (+ <span>+ {t("instance.sentence.google-cloud-sql.mysql.template", {+ user: userName,+ })}+ </span>+ );+ }+ if (authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM) {+ return (+ <span>+ {t("instance.sentence.aws-rds.mysql.template", {+ user: userName,+ })}+ </span>+ );+ }+ return (+ <span>+ {t("instance.sentence.create-user-example.mysql.template", {+ user: userName,+ password: "YOUR_DB_PWD",+ })}+ </span>+ );+ }++ if (engine === Engine.CLICKHOUSE) {+ return (+ <p>+ {t("instance.sentence.create-user-example.clickhouse.template", {+ user: userName,+ password: "YOUR_DB_PWD",+ link: t(+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow"+ ),+ })}+ </p>+ );+ }++ if (engine === Engine.POSTGRES) {+ return (+ <>+ <div className="my-2 rounded border border-yellow-400 bg-yellow-50 px-3 py-2 text-sm text-yellow-800">+ {t("instance.sentence.create-user-example.postgresql.warn")}+ </div>+ {authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ? (+ <p>+ {t("instance.sentence.google-cloud-sql.postgresql.template", {+ user: userName,+ })}+ </p>+ ) : authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM ? (+ <p>+ {t("instance.sentence.aws-rds.postgresql.template", {+ user: userName,+ })}+ </p>+ ) : (+ <p>+ {t("instance.sentence.create-user-example.postgresql.template", {+ user: userName,+ password: "YOUR_DB_PWD",+ })}+ </p>+ )}+ </>+ );+ }++ if (engine === Engine.SNOWFLAKE) {+ return (+ <p>+ {t("instance.sentence.create-user-example.snowflake.template", {+ user: userName,+ password: "YOUR_DB_PWD",+ warehouse: "YOUR_COMPUTE_WAREHOUSE",+ })}+ </p>+ );+ }++ if (engine === Engine.REDIS) {+ return (+ <p>+ {t("instance.sentence.create-user-example.redis.template", {+ user: userName,+ password: "YOUR_DB_PWD",+ })}+ </p>+ );+ }++ return null;+}++export function CreateDataSourceExample({+ engine,+ dataSourceType,+ authenticationType,+ createInstanceFlag,+ className,+}: CreateDataSourceExampleProps) {+ const { t } = useTranslation();+ const [showExample, setShowExample] = useState(createInstanceFlag);++ const isEngineUsingSQL = useMemo(+ () => languageOfEngineV1(engine) === "sql",+ [engine]+ );++ const userName = useMemo(+ () =>+ dataSourceType === DataSourceType.ADMIN+ ? DATASOURCE_ADMIN_USER_NAME+ : DATASOURCE_READONLY_USER_NAME,+ [dataSourceType]+ );++ const grantStatement = useMemo(+ () => getGrantStatement(engine, dataSourceType, authenticationType),+ [engine, dataSourceType, authenticationType]+ );++ const handleCopy = useCallback(() => {+ navigator.clipboard.writeText(grantStatement);+ }, [grantStatement]);++ const toggleExample = useCallback(() => {+ setShowExample((prev) => !prev);+ }, []);++ if (!grantStatement) {+ return null;+ }++ const descriptionText = isEngineUsingSQL+ ? dataSourceType === DataSourceType.ADMIN+ ? t("instance.sentence.create-admin-user")+ : t("instance.sentence.create-readonly-user")+ : dataSourceType === DataSourceType.ADMIN+ ? t("instance.sentence.create-admin-user-non-sql")+ : t("instance.sentence.create-readonly-user-non-sql");++ return (+ <div className={`w-full flex flex-col justify-start ${className ?? ""}`}>+ <p className="w-full text-sm text-gray-500">+ {descriptionText}+ {!createInstanceFlag && (+ <span+ className="normal-link select-none ml-1 cursor-pointer"+ onClick={toggleExample}+ >+ {t("instance.show-how-to-create")}+ </span>+ )}+ </p>+ {showExample && (+ <div className="text-sm text-main">+ <EngineSpecificDescription+ engine={engine}+ authenticationType={authenticationType}+ userName={userName}+ />+ <div className="mt-2 flex flex-row">+ <pre className="flex-1 min-w-0 w-full inline-flex items-center px-3 py-2 border border-r border-control-border bg-gray-50 text-sm whitespace-pre-line rounded-l-[3px] font-mono overflow-auto">+ {grantStatement}+ </pre>+ <button+ type="button"+ className="flex items-center -ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light bg-gray-50 hover:bg-gray-100 focus:ring-control focus:outline-hidden focus-visible:ring-2 focus:ring-offset-1 rounded-r-[3px]"+ onClick={handleCopy}+ title="Copy"+ >+ <svg+ className="w-4 h-4"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ </button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/instance/CredentialSourceForm.tsx b/frontend/src/react/components/instance/CredentialSourceForm.tsxnew file mode 100644index 0000000000..01e6f89591--- /dev/null+++ b/frontend/src/react/components/instance/CredentialSourceForm.tsx@@ -0,0 +1,529 @@+import { create } from "@bufbuild/protobuf";+import {+ type DragEvent,+ useCallback,+ useEffect,+ useMemo,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { Input } from "@/react/components/ui/input";+import { Textarea } from "@/react/components/ui/textarea";+import { useVueState } from "@/react/hooks/useVueState";+import { useActuatorV1Store } from "@/store";+import {+ DataSource_AuthenticationType,+ DataSource_AWSCredentialSchema,+ DataSource_AzureCredentialSchema,+ DataSource_GCPCredentialSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import type { EditDataSource } from "./common";++type CredentialSource = "default" | "specific-credential";++interface CredentialSourceFormProps {+ dataSource: EditDataSource;+ allowEdit: boolean;+ onDataSourceChange: (updates: Partial<EditDataSource>) => void;+}++function CredentialSourceForm({+ dataSource,+ allowEdit,+ onDataSourceChange,+}: CredentialSourceFormProps) {+ const { t } = useTranslation();+ const actuatorStore = useActuatorV1Store();+ const isSaaSMode = useVueState(() => actuatorStore.isSaaSMode);++ const isIAMAuthentication =+ dataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ||+ dataSource.authenticationType ===+ DataSource_AuthenticationType.AWS_RDS_IAM ||+ dataSource.authenticationType === DataSource_AuthenticationType.AZURE_IAM;++ const isDefaultCredentialDisabled = isSaaSMode && isIAMAuthentication;++ const deriveCredentialSource = useCallback((): CredentialSource => {+ const ext = dataSource.iamExtension;+ if (+ ext?.case === "azureCredential" ||+ ext?.case === "awsCredential" ||+ ext?.case === "gcpCredential"+ ) {+ return "specific-credential";+ }+ return "default";+ }, [dataSource.iamExtension]);++ const [credentialSource, setCredentialSource] = useState<CredentialSource>(+ () => {+ const derived = deriveCredentialSource();+ if (isDefaultCredentialDisabled && derived === "default") {+ return "specific-credential";+ }+ return derived;+ }+ );++ // Sync credentialSource when iamExtension changes externally+ useEffect(() => {+ setCredentialSource(deriveCredentialSource());+ }, [deriveCredentialSource]);++ // Force specific credential in SaaS mode for IAM authentication+ useEffect(() => {+ if (isDefaultCredentialDisabled && credentialSource === "default") {+ setCredentialSource("specific-credential");+ }+ }, [isDefaultCredentialDisabled, credentialSource]);++ // When credential source changes, update the iamExtension on the dataSource+ useEffect(() => {+ const authType = dataSource.authenticationType;+ if (credentialSource === "default") {+ onDataSourceChange({ iamExtension: { case: undefined } });+ return;+ }+ switch (authType) {+ case DataSource_AuthenticationType.AWS_RDS_IAM:+ onDataSourceChange({+ iamExtension: {+ case: "awsCredential",+ value: create(+ DataSource_AWSCredentialSchema,+ dataSource.iamExtension?.case === "awsCredential"+ ? dataSource.iamExtension.value+ : {}+ ),+ },+ });+ break;+ case DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM:+ onDataSourceChange({+ iamExtension: {+ case: "gcpCredential",+ value: create(+ DataSource_GCPCredentialSchema,+ dataSource.iamExtension?.case === "gcpCredential"+ ? dataSource.iamExtension.value+ : {}+ ),+ },+ });+ break;+ case DataSource_AuthenticationType.AZURE_IAM:+ onDataSourceChange({+ iamExtension: {+ case: "azureCredential",+ value: create(+ DataSource_AzureCredentialSchema,+ dataSource.iamExtension?.case === "azureCredential"+ ? dataSource.iamExtension.value+ : {}+ ),+ },+ });+ break;+ }+ }, [credentialSource]);++ // Reset to default when authentication type changes+ const [prevAuthType, setPrevAuthType] = useState(+ dataSource.authenticationType+ );+ if (dataSource.authenticationType !== prevAuthType) {+ setPrevAuthType(dataSource.authenticationType);+ setCredentialSource("default");+ }++ const options = useMemo(+ () => [+ {+ label: t("common.default"),+ value: "default" as CredentialSource,+ disabled: isDefaultCredentialDisabled,+ },+ {+ label: t("instance.iam-extension.specific-credential"),+ value: "specific-credential" as CredentialSource,+ },+ ],+ [t, isDefaultCredentialDisabled]+ );++ const handleCredentialSourceChange = (value: CredentialSource) => {+ if (!allowEdit) return;+ setCredentialSource(value);+ };++ const updateAzureField = (+ field: "tenantId" | "clientId" | "clientSecret",+ val: string+ ) => {+ if (dataSource.iamExtension?.case === "azureCredential") {+ onDataSourceChange({+ iamExtension: {+ case: "azureCredential",+ value: create(DataSource_AzureCredentialSchema, {+ ...dataSource.iamExtension.value,+ [field]: val,+ }),+ },+ });+ }+ };++ const updateAwsField = (+ field:+ | "accessKeyId"+ | "secretAccessKey"+ | "sessionToken"+ | "roleArn"+ | "externalId",+ val: string+ ) => {+ if (dataSource.iamExtension?.case === "awsCredential") {+ onDataSourceChange({+ iamExtension: {+ case: "awsCredential",+ value: create(DataSource_AWSCredentialSchema, {+ ...dataSource.iamExtension.value,+ [field]: val,+ }),+ },+ });+ }+ };++ const updateGcpContent = (val: string) => {+ onDataSourceChange({+ iamExtension: {+ case: "gcpCredential",+ value: create(DataSource_GCPCredentialSchema, { content: val }),+ },+ });+ };++ return (+ <div className="sm:col-span-3 sm:col-start-1">+ <label htmlFor="credential-source" className="textlabel block">+ {t("instance.iam-extension.credential-source")}+ </label>+ <div className="textlabel mt-2 flex gap-x-4">+ {options.map((option) => (+ <label+ key={option.value}+ className="inline-flex items-center gap-x-1.5"+ title={+ option.disabled+ ? t(+ "instance.iam-extension.saas-default-credential-restriction"+ )+ : undefined+ }+ >+ <input+ type="radio"+ name="credential-source"+ value={option.value}+ checked={credentialSource === option.value}+ disabled={!allowEdit || option.disabled}+ onChange={() => handleCredentialSourceChange(option.value)}+ />+ <span>{option.label}</span>+ </label>+ ))}+ </div>++ {credentialSource === "specific-credential" && (+ <>+ {dataSource.authenticationType ===+ DataSource_AuthenticationType.AZURE_IAM && (+ <AzureCredentialFields+ dataSource={dataSource}+ allowEdit={allowEdit}+ onFieldChange={updateAzureField}+ />+ )}+ {dataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (+ <GcpCredentialField+ value={+ dataSource.iamExtension?.case === "gcpCredential"+ ? dataSource.iamExtension.value.content+ : ""+ }+ onChange={updateGcpContent}+ />+ )}+ {dataSource.authenticationType ===+ DataSource_AuthenticationType.AWS_RDS_IAM && (+ <AwsCredentialFields+ dataSource={dataSource}+ allowEdit={allowEdit}+ onFieldChange={updateAwsField}+ />+ )}+ </>+ )}++ {credentialSource === "default" && (+ <DefaultCredentialInfo+ authenticationType={dataSource.authenticationType}+ />+ )}+ </div>+ );+}++function AzureCredentialFields({+ dataSource,+ allowEdit,+ onFieldChange,+}: {+ dataSource: EditDataSource;+ allowEdit: boolean;+ onFieldChange: (+ field: "tenantId" | "clientId" | "clientSecret",+ val: string+ ) => void;+}) {+ const { t } = useTranslation();+ const azure =+ dataSource.iamExtension?.case === "azureCredential"+ ? dataSource.iamExtension.value+ : undefined;++ return (+ <div className="mt-4 sm:col-span-3 sm:col-start-1">+ <label className="textlabel block mt-2">+ {t("instance.iam-extension.tenant-id")}+ </label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ value={azure?.tenantId ?? ""}+ onChange={(e) => onFieldChange("tenantId", e.target.value)}+ />+ <label className="textlabel block mt-2">+ {t("instance.iam-extension.client-id")}+ </label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ value={azure?.clientId ?? ""}+ onChange={(e) => onFieldChange("clientId", e.target.value)}+ />+ <label className="textlabel block mt-2">+ {t("instance.iam-extension.client-secret")}+ </label>+ <Input+ type="password"+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("instance.type-or-paste-credentials-write-only")}+ value={azure?.clientSecret ?? ""}+ onChange={(e) => onFieldChange("clientSecret", e.target.value)}+ />+ </div>+ );+}++function AwsCredentialFields({+ dataSource,+ allowEdit,+ onFieldChange,+}: {+ dataSource: EditDataSource;+ allowEdit: boolean;+ onFieldChange: (+ field:+ | "accessKeyId"+ | "secretAccessKey"+ | "sessionToken"+ | "roleArn"+ | "externalId",+ val: string+ ) => void;+}) {+ const { t } = useTranslation();+ const aws =+ dataSource.iamExtension?.case === "awsCredential"+ ? dataSource.iamExtension.value+ : undefined;++ return (+ <div className="mt-4 sm:col-span-3 sm:col-start-1">+ <label className="textlabel block mt-2">Access Key ID</label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.accessKeyId ?? ""}+ onChange={(e) => onFieldChange("accessKeyId", e.target.value)}+ />+ <label className="textlabel block mt-2">Secret Access Key</label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.secretAccessKey ?? ""}+ onChange={(e) => onFieldChange("secretAccessKey", e.target.value)}+ />+ <label className="textlabel block mt-2">Session Token</label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("common.sensitive-placeholder")}+ value={aws?.sessionToken ?? ""}+ onChange={(e) => onFieldChange("sessionToken", e.target.value)}+ />+ <label className="textlabel block mt-2">{t("instance.role-arn")}</label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("instance.role-arn-placeholder")}+ value={aws?.roleArn ?? ""}+ onChange={(e) => onFieldChange("roleArn", e.target.value)}+ />+ <div className="text-sm text-gray-500 mt-1">+ {t("instance.role-arn-description")}+ </div>+ <label className="textlabel block mt-2">+ {t("instance.external-id")}+ </label>+ <Input+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("instance.external-id-placeholder")}+ value={aws?.externalId ?? ""}+ onChange={(e) => onFieldChange("externalId", e.target.value)}+ />+ <div className="text-sm text-gray-500 mt-1">+ {t("instance.external-id-description")}+ </div>+ </div>+ );+}++function GcpCredentialField({+ value,+ onChange,+}: {+ value: string;+ onChange: (val: string) => void;+}) {+ const { t } = useTranslation();+ const [isDragOver, setIsDragOver] = useState(false);++ const handleDragOver = (e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ setIsDragOver(true);+ };++ const handleDragLeave = () => {+ setIsDragOver(false);+ };++ const handleDrop = (e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ setIsDragOver(false);+ const files = e.dataTransfer.files;+ if (files.length > 0) {+ const file = files[0];+ const reader = new FileReader();+ reader.onload = (event) => {+ const content = event.target?.result;+ if (typeof content === "string") {+ onChange(content);+ }+ };+ reader.readAsText(file);+ }+ };++ return (+ <div className="mt-2 sm:col-span-3 sm:col-start-1">+ <div className="flex flex-col gap-y-1 w-full">+ <p className="textinfolabel">+ <span>{t("instance.create-gcp-credentials")}</span>+ <a+ href="https://docs.bytebase.com/get-started/connect/gcp?source=console"+ target="_blank"+ rel="noreferrer"+ className="normal-link inline-flex items-center ml-1"+ >+ <span>{t("common.detailed-guide")}</span>+ <svg+ xmlns="http://www.w3.org/2000/svg"+ className="w-4 h-4 ml-1"+ fill="none"+ viewBox="0 0 24 24"+ stroke="currentColor"+ strokeWidth={2}+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"+ />+ </svg>+ </a>+ </p>+ <Textarea+ value={value}+ placeholder={t("instance.type-or-paste-credentials-write-only")}+ className={`w-full h-24 whitespace-pre-wrap resize-none ${isDragOver ? "ring-2 ring-accent border-accent" : ""}`}+ onChange={(e) => onChange(e.target.value)}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ />+ </div>+ </div>+ );+}++function DefaultCredentialInfo({+ authenticationType,+}: {+ authenticationType: DataSource_AuthenticationType;+}) {+ return (+ <div className="mt-1 sm:col-span-3 sm:col-start-1 textinfolabel !leading-6">+ {authenticationType === DataSource_AuthenticationType.AZURE_IAM && (+ <span>+ Bytebase will read the credential from environment variables{" "}+ <Code>AZURE_CLIENT_ID</Code>/<Code>AZURE_TENANT_ID</Code>/+ <Code>AZURE_CLIENT_SECRET</Code> or{" "}+ <Code>AZURE_CLIENT_CERTIFICATE_PATH</Code>, and fallback to attached+ users in Azure VM+ </span>+ )}+ {authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM && (+ <span>+ Bytebase will read the credential from environment variables{" "}+ <Code>AWS_ACCESS_KEY_ID</Code>/<Code>AWS_SECRET_ACCESS_KEY</Code>/+ <Code>AWS_SESSION_TOKEN</Code>, fallback to shared credentials file{" "}+ <Code>~/.aws/credentials</Code> or IAM role in AWS ECS+ </span>+ )}+ {authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (+ <span>+ Bytebase will read the credential from environment variable{" "}+ <Code>GOOGLE_APPLICATION_CREDENTIALS</Code>, fallback to the attached+ service account in GCP GCE+ </span>+ )}+ </div>+ );+}++function Code({ children }: { children: React.ReactNode }) {+ return <code className="bg-gray-100 p-1 rounded-sm mr-1">{children}</code>;+}++export { CredentialSourceForm };diff --git a/frontend/src/react/components/instance/DataSourceForm.tsx b/frontend/src/react/components/instance/DataSourceForm.tsxnew file mode 100644index 0000000000..2988479b2a--- /dev/null+++ b/frontend/src/react/components/instance/DataSourceForm.tsx@@ -0,0 +1,1825 @@+import { create } from "@bufbuild/protobuf";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ DataSource_AuthenticationType,+ DataSource_RedisType,+ DataSourceExternalSecret_AppRoleAuthOption_SecretType,+ DataSourceExternalSecret_AppRoleAuthOptionSchema,+ DataSourceExternalSecret_AuthType,+ DataSourceExternalSecret_SecretType,+ DataSourceExternalSecretSchema,+ DataSourceType,+ KerberosConfigSchema,+ SASLConfigSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { onlyAllowNumber } from "@/utils";+import { CreateDataSourceExample } from "./CreateDataSourceExample";+import { CredentialSourceForm } from "./CredentialSourceForm";+import type { EditDataSource } from "./common";+import { useInstanceFormContext } from "./InstanceFormContext";+import { hasInfoContent, type InfoSection } from "./info-content";+import { SshConnectionForm } from "./SshConnectionForm";+import { SslCertificateForm } from "./SslCertificateForm";++interface DataSourceFormProps {+ dataSource: EditDataSource;+ hideOptions?: boolean;+ optionsOnly?: boolean;+ onDataSourceChange: (ds: EditDataSource) => void;+ onOpenInfoPanel?: (section: InfoSection) => void;+}++export function DataSourceForm({+ dataSource,+ hideOptions = false,+ optionsOnly = false,+ onDataSourceChange,+ onOpenInfoPanel,+}: DataSourceFormProps) {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const {+ instance,+ specs,+ isCreating,+ allowEdit,+ basicInfo,+ adminDataSource,+ hasReadonlyReplicaFeature,+ setMissingFeature,+ hideAdvancedFeatures,+ } = ctx;++ const {+ showDatabase,+ showSSL,+ showSSH,+ allowUsingEmptyPassword,+ showAuthenticationDatabase,+ hasReadonlyReplicaHost,+ hasReadonlyReplicaPort,+ hasExtraParameters,+ } = specs;++ const [passwordType, setPasswordType] = useState(+ dataSource.externalSecret?.secretType ??+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED+ );+ const [newParamKey, setNewParamKey] = useState("");+ const [newParamValue, setNewParamValue] = useState("");++ // Sync passwordType when externalSecret changes+ useEffect(() => {+ if (dataSource.externalSecret) {+ setPasswordType(dataSource.externalSecret.secretType);+ } else {+ setPasswordType(+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED+ );+ }+ }, [dataSource.externalSecret]);++ const update = useCallback(+ (partial: Partial<EditDataSource>) => {+ onDataSourceChange({ ...dataSource, ...partial });+ },+ [dataSource, onDataSourceChange]+ );++ const hasAuthenticationInfo = hasInfoContent(+ basicInfo.engine,+ "authentication"+ );+ const hasSslInfo = hasInfoContent(basicInfo.engine, "ssl");+ const hasSshInfo = hasInfoContent(basicInfo.engine, "ssh");++ const hiveAuthentication =+ dataSource.saslConfig?.mechanism?.case === "krbConfig"+ ? "KERBEROS"+ : "PASSWORD";++ const onHiveAuthenticationChange = (val: "KERBEROS" | "PASSWORD") => {+ if (val === "KERBEROS") {+ update({+ saslConfig: create(SASLConfigSchema, {+ mechanism: {+ case: "krbConfig",+ value: create(KerberosConfigSchema, {+ kdcTransportProtocol: "tcp",+ }),+ },+ }),+ });+ } else {+ update({ saslConfig: undefined });+ }+ };++ const supportedAuthenticationTypes = useMemo(() => {+ switch (basicInfo.engine) {+ case Engine.COSMOSDB:+ return [+ {+ value: DataSource_AuthenticationType.AZURE_IAM,+ label: t("instance.password-type.azure-iam"),+ },+ ];+ case Engine.MSSQL:+ return [+ {+ value: DataSource_AuthenticationType.PASSWORD,+ label: t("instance.password-type.password"),+ },+ {+ value: DataSource_AuthenticationType.AZURE_IAM,+ label: t("instance.password-type.azure-iam"),+ },+ ];+ case Engine.ELASTICSEARCH:+ return [+ {+ value: DataSource_AuthenticationType.PASSWORD,+ label: t("instance.password-type.password"),+ },+ {+ value: DataSource_AuthenticationType.AWS_RDS_IAM,+ label: t("instance.password-type.aws-iam"),+ },+ ];+ case Engine.SPANNER:+ case Engine.BIGQUERY:+ return [+ {+ value: DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,+ label: t("instance.password-type.google-iam"),+ },+ ];+ default:+ return [+ {+ value: DataSource_AuthenticationType.PASSWORD,+ label: t("instance.password-type.password"),+ },+ {+ value: DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,+ label: t("instance.password-type.google-iam"),+ },+ {+ value: DataSource_AuthenticationType.AWS_RDS_IAM,+ label: t("instance.password-type.aws-iam"),+ },+ ];+ }+ }, [basicInfo.engine, t]);++ const extraConnectionParamsList = useMemo(() => {+ const params = dataSource.extraConnectionParameters || {};+ return Object.entries(params).map(([key, value]) => ({ key, value }));+ }, [dataSource.extraConnectionParameters]);++ const changeSecretType = (+ secretType: DataSourceExternalSecret_SecretType+ ) => {+ const ds = { ...dataSource };+ switch (secretType) {+ case DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED:+ ds.externalSecret = undefined;+ break;+ case DataSourceExternalSecret_SecretType.VAULT_KV_V2:+ ds.externalSecret = create(DataSourceExternalSecretSchema, {+ authType: DataSourceExternalSecret_AuthType.TOKEN,+ secretType,+ authOption: { case: "token", value: "" },+ secretName: ds.externalSecret?.secretName ?? "",+ passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",+ });+ break;+ case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:+ ds.externalSecret = create(DataSourceExternalSecretSchema, {+ authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,+ secretType,+ authOption: { case: "token", value: "" },+ secretName: ds.externalSecret?.secretName ?? "",+ passwordKeyName: ds.externalSecret?.passwordKeyName ?? "",+ });+ break;+ case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:+ ds.externalSecret = create(DataSourceExternalSecretSchema, {+ authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,+ secretType,+ authOption: { case: "token", value: "" },+ secretName: ds.externalSecret?.secretName ?? "",+ passwordKeyName: "",+ });+ break;+ case DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT:+ ds.externalSecret = create(DataSourceExternalSecretSchema, {+ authType: DataSourceExternalSecret_AuthType.AUTH_TYPE_UNSPECIFIED,+ secretType,+ authOption: { case: "token", value: "" },+ url: ds.externalSecret?.url ?? "",+ secretName: ds.externalSecret?.secretName ?? "",+ passwordKeyName: "",+ });+ break;+ }+ setPasswordType(secretType);+ onDataSourceChange(ds);+ };++ const changeExternalSecretAuthType = (+ authType: DataSourceExternalSecret_AuthType+ ) => {+ if (!dataSource.externalSecret) return;+ const ds = { ...dataSource };+ if (authType === DataSourceExternalSecret_AuthType.VAULT_APP_ROLE) {+ ds.externalSecret = {+ ...ds.externalSecret!,+ authOption: {+ case: "appRole" as const,+ value: create(DataSourceExternalSecret_AppRoleAuthOptionSchema, {+ type: DataSourceExternalSecret_AppRoleAuthOption_SecretType.PLAIN,+ }),+ },+ authType,+ };+ } else {+ ds.externalSecret = {+ ...ds.externalSecret!,+ authOption: { case: "token" as const, value: "" },+ authType,+ };+ }+ onDataSourceChange(ds);+ };++ const toggleUseEmptyPassword = (on: boolean) => {+ update({+ useEmptyPassword: on,+ updatedPassword: on ? "" : dataSource.updatedPassword,+ });+ };++ const handleHostInput = (value: string) => {+ if (dataSource.type === DataSourceType.READ_ONLY) {+ if (!hasReadonlyReplicaFeature) {+ if (dataSource.host || dataSource.port) {+ update({+ host: adminDataSource.host,+ port: adminDataSource.port,+ });+ setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);+ return;+ }+ }+ }+ update({ host: value.trim() });+ };++ const handlePortInput = (value: string) => {+ if (dataSource.type === DataSourceType.READ_ONLY) {+ if (!hasReadonlyReplicaFeature) {+ if (dataSource.host || dataSource.port) {+ update({+ host: adminDataSource.host,+ port: adminDataSource.port,+ });+ setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);+ return;+ }+ }+ }+ update({ port: value.trim() });+ };++ const handleUseSslChanged = (useSSL: boolean) => {+ update({ useSsl: useSSL, updateSsl: true });+ };++ const handleEditSSL = () => {+ update({ sslCa: "", sslCert: "", sslKey: "", updateSsl: true });+ };++ const handleSSHChange = (+ value: Partial<{+ sshHost: string;+ sshPort: string;+ sshUser: string;+ sshPassword: string;+ sshPrivateKey: string;+ }>+ ) => {+ update(value);+ };++ const addNewParameter = () => {+ if (!newParamKey.trim()) return;+ const params = { ...(dataSource.extraConnectionParameters || {}) };+ params[newParamKey.trim()] = newParamValue;+ update({ extraConnectionParameters: params });+ setNewParamKey("");+ setNewParamValue("");+ };++ const updateExtraConnectionParamKey = (index: number, newKey: string) => {+ const params = extraConnectionParamsList;+ if (index >= params.length) return;+ const plain = { ...(dataSource.extraConnectionParameters || {}) };+ const oldKey = params[index].key;+ const value = params[index].value;+ if (oldKey === newKey) return;+ delete plain[oldKey];+ if (newKey.trim()) plain[newKey] = value;+ update({ extraConnectionParameters: plain });+ };++ const updateExtraConnectionParamValue = (index: number, newValue: string) => {+ const params = extraConnectionParamsList;+ if (index >= params.length) return;+ const plain = { ...(dataSource.extraConnectionParameters || {}) };+ plain[params[index].key] = newValue;+ update({ extraConnectionParameters: plain });+ };++ const removeExtraConnectionParam = (index: number) => {+ const params = extraConnectionParamsList;+ if (index >= params.length) return;+ const plain = { ...(dataSource.extraConnectionParameters || {}) };+ delete plain[params[index].key];+ update({ extraConnectionParameters: plain });+ };++ const secretNameLabel = useMemo(() => {+ switch (passwordType) {+ case DataSourceExternalSecret_SecretType.VAULT_KV_V2:+ return t("instance.external-secret-vault.vault-secret-path");+ case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:+ return t("instance.external-secret-gcp.secret-name");+ case DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT:+ return t("instance.external-secret-azure.secret-name");+ default:+ return t("instance.external-secret.secret-name");+ }+ }, [passwordType, t]);++ const secretKeyLabel = useMemo(() => {+ if (passwordType === DataSourceExternalSecret_SecretType.VAULT_KV_V2) {+ return t("instance.external-secret-vault.vault-secret-key");+ }+ return t("instance.external-secret.key-name");+ }, [passwordType, t]);++ const showMainFields =+ basicInfo.engine !== Engine.SPANNER &&+ basicInfo.engine !== Engine.BIGQUERY &&+ basicInfo.engine !== Engine.DYNAMODB &&+ basicInfo.engine !== Engine.DATABRICKS;++ const showAuthTypeRadio =+ basicInfo.engine === Engine.MYSQL ||+ basicInfo.engine === Engine.POSTGRES ||+ basicInfo.engine === Engine.COSMOSDB ||+ basicInfo.engine === Engine.MSSQL ||+ basicInfo.engine === Engine.ELASTICSEARCH;++ const isPasswordAuth =+ dataSource.authenticationType === DataSource_AuthenticationType.PASSWORD;+ const isAzureIAM =+ dataSource.authenticationType === DataSource_AuthenticationType.AZURE_IAM;+ const isAwsIAM =+ dataSource.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM;+ const isGoogleIAM =+ dataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM;+ const isIAM = isAzureIAM || isAwsIAM || isGoogleIAM;++ const handleKeytabUpload = (e: React.ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ const data = new Uint8Array(reader.result as ArrayBuffer);+ if (dataSource.saslConfig?.mechanism?.case === "krbConfig") {+ const krbValue = dataSource.saslConfig.mechanism.value;+ update({+ saslConfig: create(SASLConfigSchema, {+ ...dataSource.saslConfig,+ mechanism: {+ case: "krbConfig",+ value: create(KerberosConfigSchema, {+ ...krbValue,+ keytab: data,+ }),+ },+ }),+ });+ }+ };+ reader.readAsArrayBuffer(file);+ };++ return (+ <div className="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3">+ {!optionsOnly && (+ <>+ {/* Main credential fields */}+ {showMainFields && (+ <>+ {/* Authentication type selector */}+ {showAuthTypeRadio && (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="flex items-center gap-x-2">+ <div className="textlabel flex items-center gap-x-4">+ {supportedAuthenticationTypes.map((item) => (+ <label+ key={item.value}+ className="flex items-center gap-x-1.5 cursor-pointer"+ >+ <input+ type="radio"+ name="authenticationType"+ checked={+ dataSource.authenticationType === item.value+ }+ disabled={!allowEdit}+ onChange={() =>+ update({ authenticationType: item.value })+ }+ />+ {item.label}+ </label>+ ))}+ </div>+ </div>+ </div>+ )}++ {/* Create data source example (edit mode only) */}+ {!isCreating && (+ <CreateDataSourceExample+ className="sm:col-span-3 border-none"+ createInstanceFlag={false}+ engine={basicInfo.engine}+ dataSourceType={dataSource.type}+ authenticationType={dataSource.authenticationType}+ />+ )}++ {/* Hive authentication */}+ {basicInfo.engine === Engine.HIVE && (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="textlabel flex items-center gap-x-4">+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={hiveAuthentication === "PASSWORD"}+ disabled={!allowEdit}+ onChange={() => onHiveAuthenticationChange("PASSWORD")}+ />+ Plain Password+ </label>+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={hiveAuthentication === "KERBEROS"}+ disabled={!allowEdit}+ onChange={() => onHiveAuthenticationChange("KERBEROS")}+ />+ Kerberos+ </label>+ </div>+ </div>+ )}++ {/* Kerberos config */}+ {dataSource.saslConfig?.mechanism?.case === "krbConfig" && (+ <>+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ Principal <span className="text-red-600">*</span>+ </label>+ <div className="mt-2 flex items-center gap-x-2">+ <Input+ value={+ dataSource.saslConfig.mechanism.value.primary ?? ""+ }+ disabled={!allowEdit}+ placeholder="primary"+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case === "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.primary =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ <span>/</span>+ <Input+ value={+ dataSource.saslConfig.mechanism.value.instance ?? ""+ }+ disabled={!allowEdit}+ placeholder="instance, optional"+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case === "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.instance =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ <span>@</span>+ <Input+ value={+ dataSource.saslConfig.mechanism.value.realm ?? ""+ }+ disabled={!allowEdit}+ placeholder="realm"+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case === "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.realm =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ </div>+ </div>+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ KDC <span className="text-red-600">*</span>+ </label>+ <div className="flex items-center gap-x-2">+ <div className="w-fit textlabel flex gap-x-3">+ {["tcp", "udp"].map((proto) => (+ <label+ key={proto}+ className="flex items-center gap-x-1.5"+ >+ <input+ type="radio"+ checked={+ dataSource.saslConfig?.mechanism?.value+ ?.kdcTransportProtocol === proto+ }+ disabled={!allowEdit}+ onChange={() => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case ===+ "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcTransportProtocol =+ proto;+ }+ onDataSourceChange(updated);+ }}+ />+ {proto.toUpperCase()}+ </label>+ ))}+ </div>+ <Input+ value={+ dataSource.saslConfig.mechanism.value.kdcHost ?? ""+ }+ disabled={!allowEdit}+ placeholder="KDC host"+ onChange={(e) => {+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case === "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcHost =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ <span>:</span>+ <Input+ value={+ dataSource.saslConfig.mechanism.value.kdcPort ?? ""+ }+ disabled={!allowEdit}+ placeholder="KDC port, optional"+ onChange={(e) => {+ if (+ e.target.value &&+ !onlyAllowNumber(e.target.value)+ )+ return;+ const updated = { ...dataSource };+ if (+ updated.saslConfig?.mechanism?.case === "krbConfig"+ ) {+ updated.saslConfig.mechanism.value.kdcPort =+ e.target.value;+ }+ onDataSourceChange(updated);+ }}+ />+ </div>+ </div>+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ Keytab File <span className="text-red-600">*</span>+ </label>+ <div className="mt-3 border-2 border-dashed rounded-lg p-6 text-center">+ <input+ type="file"+ accept=".keytab"+ className="hidden"+ id="keytab-upload"+ onChange={handleKeytabUpload}+ />+ <label+ htmlFor="keytab-upload"+ className="cursor-pointer textinfolabel"+ >+ Click or Drag your .keytab file here+ </label>+ </div>+ </div>+ </>+ )}++ {/* Username field (non-Kerberos, non-Azure IAM) */}+ {dataSource.saslConfig?.mechanism?.case !== "krbConfig" &&+ !isAzureIAM && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel flex items-center gap-x-1">+ {t("common.username")}+ {isCreating &&+ onOpenInfoPanel &&+ hasAuthenticationInfo && (+ <button+ type="button"+ className="text-accent text-xs hover:underline"+ onClick={() => onOpenInfoPanel("authentication")}+ >+ ⓘ+ </button>+ )}+ </label>+ <Input+ value={dataSource.username}+ className="mt-2 w-full max-w-[48rem]"+ disabled={!allowEdit}+ placeholder={+ basicInfo.engine === Engine.CLICKHOUSE+ ? t("common.default")+ : ""+ }+ onChange={(e) => update({ username: e.target.value })}+ />+ </div>+ )}++ {/* IAM Credential Source Form */}+ {isIAM && (+ <CredentialSourceForm+ dataSource={dataSource}+ allowEdit={allowEdit}+ onDataSourceChange={update}+ />+ )}++ {/* AWS Region */}+ {isAwsIAM && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ {t("instance.database-region")}{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={dataSource.region ?? ""}+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder="database region, for example, us-east-1"+ onChange={(e) => update({ region: e.target.value })}+ />+ </div>+ )}++ {/* Password / External Secret */}+ {isPasswordAuth &&+ dataSource.saslConfig?.mechanism?.case !== "krbConfig" && (+ <div className="sm:col-span-3 sm:col-start-1">+ {!hideAdvancedFeatures && (+ <div className="mb-4">+ <div className="textlabel flex flex-wrap gap-x-4 gap-y-2">+ {[+ {+ value:+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED,+ label: t("instance.password-type.password"),+ },+ {+ value:+ DataSourceExternalSecret_SecretType.VAULT_KV_V2,+ label: t(+ "instance.password-type.external-secret-vault"+ ),+ },+ {+ value:+ DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER,+ label: t(+ "instance.password-type.external-secret-aws"+ ),+ },+ {+ value:+ DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER,+ label: t(+ "instance.password-type.external-secret-gcp"+ ),+ },+ {+ value:+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT,+ label: t(+ "instance.password-type.external-secret-azure"+ ),+ },+ ].map((item) => (+ <label+ key={item.value}+ className="flex items-center gap-x-1.5 cursor-pointer"+ >+ <input+ type="radio"+ checked={passwordType === item.value}+ disabled={!allowEdit}+ onChange={() => changeSecretType(item.value)}+ />+ {item.label}+ {item.value !==+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED && (+ <span className="text-xs bg-indigo-100 text-indigo-800 px-1.5 py-0.5 rounded-full">+ Pro+ </span>+ )}+ </label>+ ))}+ </div>+ <a+ href="https://docs.bytebase.com/get-started/connect/overview#secret-manager-integration"+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-accent hover:underline"+ >+ {t("common.learn-more")}+ </a>+ </div>+ )}++ {/* Plain password */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED && (+ <div>+ <label className="textlabel block">+ {t("common.password")}+ </label>+ <div className="mt-2">+ {!isCreating && allowUsingEmptyPassword && (+ <label className="flex items-center gap-x-1.5 mb-2 text-sm cursor-pointer">+ <input+ type="checkbox"+ checked={dataSource.useEmptyPassword ?? false}+ disabled={!allowEdit}+ onChange={(e) =>+ toggleUseEmptyPassword(e.target.checked)+ }+ />+ {t("instance.no-password")}+ </label>+ )}+ <Input+ type="password"+ className="w-full max-w-[48rem]"+ autoComplete="off"+ placeholder={+ dataSource.useEmptyPassword+ ? t("instance.no-password")+ : t("instance.password-write-only")+ }+ disabled={+ !allowEdit || !!dataSource.useEmptyPassword+ }+ value={+ dataSource.useEmptyPassword+ ? ""+ : dataSource.updatedPassword+ }+ onChange={(e) =>+ update({+ updatedPassword: e.target.value.trim(),+ })+ }+ />+ </div>+ </div>+ )}++ {/* External secret fields */}+ {passwordType !==+ DataSourceExternalSecret_SecretType.SECRET_TYPE_UNSPECIFIED &&+ dataSource.externalSecret && (+ <div className="flex flex-col gap-y-4">+ {/* Vault KV V2 */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.VAULT_KV_V2 && (+ <div className="flex flex-col gap-y-4">+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-url"+ )}{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={dataSource.externalSecret.url ?? ""}+ required+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-vault.vault-url"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ url: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </div>+ <div className="flex flex-col gap-y-2">+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-auth-type.self"+ )}+ </label>+ <div className="textlabel flex gap-x-4">+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={+ dataSource.externalSecret.authType ===+ DataSourceExternalSecret_AuthType.TOKEN+ }+ onChange={() =>+ changeExternalSecretAuthType(+ DataSourceExternalSecret_AuthType.TOKEN+ )+ }+ />+ {t(+ "instance.external-secret-vault.vault-auth-type.token.self"+ )}+ </label>+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={+ dataSource.externalSecret.authType ===+ DataSourceExternalSecret_AuthType.VAULT_APP_ROLE+ }+ onChange={() =>+ changeExternalSecretAuthType(+ DataSourceExternalSecret_AuthType.VAULT_APP_ROLE+ )+ }+ />+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.self"+ )}+ </label>+ </div>+ </div>+ {/* Token input */}+ {dataSource.externalSecret.authType ===+ DataSourceExternalSecret_AuthType.TOKEN && (+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-auth-type.token.self"+ )}{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={+ dataSource.externalSecret.authOption+ ?.case === "token"+ ? (dataSource.externalSecret.authOption+ .value as string)+ : ""+ }+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={`${t("instance.external-secret-vault.vault-auth-type.token.self")} - ${t("common.write-only")}`}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ authOption: {+ case: "token" as const,+ value: e.target.value,+ },+ };+ onDataSourceChange(ds);+ }}+ />+ </div>+ )}+ {/* AppRole fields */}+ {dataSource.externalSecret.authOption?.case ===+ "appRole" && (+ <div className="flex flex-col gap-y-4">+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.role-id"+ )}{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={+ dataSource.externalSecret.authOption+ .value.roleId ?? ""+ }+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={`${t("instance.external-secret-vault.vault-auth-type.approle.role-id")} - ${t("common.write-only")}`}+ onChange={(e) => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret?.authOption+ ?.case === "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret.authOption,+ value: {+ ...ds.externalSecret.authOption+ .value,+ roleId: e.target.value,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ </div>+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-id"+ )}{" "}+ <span className="text-red-600">*</span>+ </label>+ <div className="textlabel my-1 flex gap-x-4">+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={+ dataSource.externalSecret.authOption+ .value.type === 0+ }+ disabled={!allowEdit}+ onChange={() => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret?.authOption+ ?.case === "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret+ .authOption,+ value: {+ ...ds.externalSecret+ .authOption.value,+ type: 0,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text"+ )}+ </label>+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={+ dataSource.externalSecret.authOption+ .value.type === 1+ }+ disabled={!allowEdit}+ onChange={() => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret?.authOption+ ?.case === "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret+ .authOption,+ value: {+ ...ds.externalSecret+ .authOption.value,+ type: 1,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ {t(+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name"+ )}+ </label>+ </div>+ <Input+ value={+ dataSource.externalSecret.authOption+ .value.secretId ?? ""+ }+ className="mt-2 w-full"+ disabled={!allowEdit}+ onChange={(e) => {+ const ds = { ...dataSource };+ if (+ ds.externalSecret?.authOption+ ?.case === "appRole"+ ) {+ ds.externalSecret = {+ ...ds.externalSecret,+ authOption: {+ ...ds.externalSecret.authOption,+ value: {+ ...ds.externalSecret.authOption+ .value,+ secretId: e.target.value,+ },+ },+ };+ }+ onDataSourceChange(ds);+ }}+ />+ </div>+ </div>+ )}+ {/* Vault TLS config */}+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-tls-config"+ )}+ </label>+ <SslCertificateForm+ verify={+ !dataSource.externalSecret+ .skipVaultTlsVerification+ }+ onVerifyChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ skipVaultTlsVerification: !val,+ };+ onDataSourceChange(ds);+ }}+ ca={dataSource.externalSecret.vaultSslCa}+ onCaChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslCa: val,+ };+ onDataSourceChange(ds);+ }}+ cert={dataSource.externalSecret.vaultSslCert}+ onCertChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslCert: val,+ };+ onDataSourceChange(ds);+ }}+ sslKey={dataSource.externalSecret.vaultSslKey}+ onKeyChange={(val) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ vaultSslKey: val,+ };+ onDataSourceChange(ds);+ }}+ disabled={!allowEdit}+ showKeyAndCert+ />+ </div>+ {/* Engine name */}+ <div>+ <label className="textlabel block">+ {t(+ "instance.external-secret-vault.vault-secret-engine-name"+ )}{" "}+ <span className="text-red-600">*</span>+ </label>+ <div className="flex gap-x-2 text-sm textinfolabel">+ {t(+ "instance.external-secret-vault.vault-secret-engine-tips"+ )}+ </div>+ <Input+ value={+ dataSource.externalSecret.engineName ?? ""+ }+ required+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-vault.vault-secret-engine-name"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ engineName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </div>+ </div>+ )}++ {/* Azure Key Vault URL */}+ {passwordType ===+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (+ <div>+ <label className="textlabel block">+ {t("instance.external-secret-azure.vault-url")}{" "}+ <span className="text-red-600">*</span>+ </label>+ <div className="flex gap-x-2 text-sm textinfolabel">+ {t(+ "instance.external-secret-azure.vault-url-tips"+ )}+ </div>+ <Input+ value={dataSource.externalSecret.url ?? ""}+ required+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t(+ "instance.external-secret-azure.vault-url"+ )}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ url: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </div>+ )}++ {/* Secret name (common) */}+ <div>+ <label className="textlabel block">+ {secretNameLabel}{" "}+ <span className="text-red-600">*</span>+ </label>+ {passwordType ===+ DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER && (+ <div className="flex gap-x-2 text-sm textinfolabel">+ {t(+ "instance.external-secret-gcp.secret-name-tips"+ )}+ </div>+ )}+ {passwordType ===+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (+ <div className="flex gap-x-2 text-sm textinfolabel">+ {t(+ "instance.external-secret-azure.secret-name-tips"+ )}+ </div>+ )}+ <Input+ value={dataSource.externalSecret.secretName ?? ""}+ required+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={secretNameLabel}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ secretName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </div>++ {/* Secret key (not for GCP/Azure) */}+ {passwordType !==+ DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER &&+ passwordType !==+ DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (+ <div>+ <label className="textlabel block">+ {secretKeyLabel}{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={+ dataSource.externalSecret.passwordKeyName ??+ ""+ }+ required+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={secretKeyLabel}+ onChange={(e) => {+ const ds = { ...dataSource };+ ds.externalSecret = {+ ...ds.externalSecret!,+ passwordKeyName: e.target.value,+ };+ onDataSourceChange(ds);+ }}+ />+ </div>+ )}+ </div>+ )}++ {/* Redis Sentinel fields */}+ {basicInfo.engine === Engine.REDIS &&+ dataSource.redisType ===+ DataSource_RedisType.SENTINEL && (+ <>+ <div className="mt-2">+ <label className="textlabel">+ Master Name{" "}+ <span className="text-red-600">*</span>+ </label>+ <Input+ value={dataSource.masterName ?? ""}+ className="mt-1 w-full"+ disabled={!allowEdit}+ onChange={(e) =>+ update({ masterName: e.target.value })+ }+ />+ </div>+ <div className="mt-2">+ <label className="textlabel">Master Username</label>+ <Input+ value={dataSource.masterUsername ?? ""}+ className="mt-1 w-full"+ disabled={!allowEdit}+ onChange={(e) =>+ update({ masterUsername: e.target.value })+ }+ />+ </div>+ <div className="mt-2">+ <label className="textlabel block">+ Master Password+ </label>+ <div className="mt-2">+ {!isCreating && allowUsingEmptyPassword && (+ <label className="flex items-center gap-x-1.5 mb-2 text-sm cursor-pointer">+ <input+ type="checkbox"+ checked={+ dataSource.useEmptyMasterPassword ?? false+ }+ disabled={!allowEdit}+ onChange={(e) => {+ update({+ useEmptyMasterPassword:+ e.target.checked,+ updatedMasterPassword: e.target.checked+ ? ""+ : dataSource.updatedMasterPassword,+ });+ }}+ />+ {t("instance.no-password")}+ </label>+ )}+ <Input+ type="password"+ className="w-full"+ autoComplete="off"+ placeholder={+ dataSource.useEmptyMasterPassword+ ? t("instance.no-password")+ : t("instance.password-write-only")+ }+ disabled={+ !allowEdit ||+ !!dataSource.useEmptyMasterPassword+ }+ value={+ dataSource.useEmptyMasterPassword+ ? ""+ : dataSource.updatedMasterPassword+ }+ onChange={(e) =>+ update({+ updatedMasterPassword:+ e.target.value.trim(),+ })+ }+ />+ </div>+ </div>+ </>+ )}+ </div>+ )}+ </>+ )}++ {/* Spanner/BigQuery auth */}+ {(basicInfo.engine === Engine.SPANNER ||+ basicInfo.engine === Engine.BIGQUERY) && (+ <>+ <div className="sm:col-span-3 sm:col-start-1 textlabel flex gap-x-4">+ {supportedAuthenticationTypes.map((item) => (+ <label+ key={item.value}+ className="flex items-center gap-x-1.5 cursor-pointer"+ >+ <input+ type="radio"+ checked={dataSource.authenticationType === item.value}+ disabled={!allowEdit}+ onChange={() =>+ update({ authenticationType: item.value })+ }+ />+ {item.label}+ </label>+ ))}+ </div>+ <CredentialSourceForm+ dataSource={dataSource}+ allowEdit={allowEdit}+ onDataSourceChange={update}+ />+ </>+ )}++ {/* Oracle SID/Service Name */}+ {basicInfo.engine === Engine.ORACLE && (+ <OracleSIDServiceNameInput+ sid={dataSource.sid ?? ""}+ serviceName={dataSource.serviceName ?? ""}+ allowEdit={allowEdit}+ onSidChange={(val) => update({ sid: val })}+ onServiceNameChange={(val) => update({ serviceName: val })}+ />+ )}++ {/* Snowflake keypair */}+ {basicInfo.engine === Engine.SNOWFLAKE && (+ <>+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="textlabel block">+ {t("data-source.ssh.private-key")}+ </div>+ <div className="flex gap-x-2 text-sm">+ <span className="textinfolabel">+ {t("data-source.snowflake-keypair-tip")}+ </span>+ <a+ href="https://docs.snowflake.com/en/user-guide/key-pair-auth"+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-accent hover:underline"+ >+ {t("common.learn-more")}+ </a>+ </div>+ <textarea+ value={dataSource.authenticationPrivateKey ?? ""}+ disabled={!allowEdit}+ className="w-full h-32 mt-2 whitespace-pre-wrap rounded-md border border-control-border p-2 text-sm font-mono"+ placeholder={`-----BEGIN PRIVATE KEY-----\nMIIEvQ...\n-----END PRIVATE KEY-----`}+ onChange={(e) =>+ update({ authenticationPrivateKey: e.target.value })+ }+ />+ </div>+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="textlabel block">+ {t("data-source.private-key-passphrase")}+ </div>+ <div className="textinfolabel text-sm">+ {t("data-source.private-key-passphrase-tip")}+ </div>+ <Input+ value={dataSource.authenticationPrivateKeyPassphrase ?? ""}+ type="password"+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t(+ "data-source.private-key-passphrase-placeholder"+ )}+ onChange={(e) =>+ update({+ authenticationPrivateKeyPassphrase: e.target.value,+ })+ }+ />+ </div>+ </>+ )}++ {/* Databricks */}+ {basicInfo.engine === Engine.DATABRICKS && (+ <>+ <div>+ <div className="textlabel mt-2">+ Warehouse ID <span className="text-red-600">*</span>+ </div>+ <Input+ value={dataSource.warehouseId ?? ""}+ className="mt-2"+ disabled={!allowEdit}+ onChange={(e) => update({ warehouseId: e.target.value })}+ />+ </div>+ <div>+ <div className="textlabel mt-2">+ Token <span className="text-red-600">*</span>+ </div>+ <Input+ value={dataSource.authenticationPrivateKey ?? ""}+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder="personal access token"+ onChange={(e) =>+ update({ authenticationPrivateKey: e.target.value })+ }+ />+ </div>+ </>+ )}++ {/* MongoDB authentication database */}+ {showAuthenticationDatabase && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ {t("instance.authentication-database")}+ </label>+ <Input+ className="mt-2 w-full"+ autoComplete="off"+ placeholder="admin"+ disabled={!allowEdit}+ value={dataSource.authenticationDatabase ?? ""}+ onChange={(e) =>+ update({ authenticationDatabase: e.target.value.trim() })+ }+ />+ </div>+ )}++ {/* Read-only replica host/port */}+ {dataSource.type === DataSourceType.READ_ONLY &&+ (hasReadonlyReplicaHost || hasReadonlyReplicaPort) && (+ <>+ {hasReadonlyReplicaHost && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ {t("data-source.read-replica-host")}+ </label>+ <Input+ className="mt-2 w-full"+ autoComplete="off"+ value={dataSource.host}+ disabled={!allowEdit}+ onChange={(e) => handleHostInput(e.target.value)}+ />+ </div>+ )}+ {hasReadonlyReplicaPort && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">+ {t("data-source.read-replica-port")}+ </label>+ <Input+ className="mt-2 w-full"+ autoComplete="off"+ value={dataSource.port}+ disabled={!allowEdit}+ onChange={(e) => {+ if (e.target.value && !onlyAllowNumber(e.target.value))+ return;+ handlePortInput(e.target.value);+ }}+ />+ </div>+ )}+ </>+ )}++ {/* Database field */}+ {showDatabase && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label className="textlabel block">{t("common.database")}</label>+ <Input+ value={dataSource.database ?? ""}+ className="mt-2 w-full"+ disabled={!allowEdit}+ placeholder={t("common.database")}+ onChange={(e) => update({ database: e.target.value })}+ />+ </div>+ )}+ </>+ )}++ {/* Connection options (SSL, SSH, Extra params) */}+ {!hideOptions && (+ <>+ {/* SSL */}+ {showSSL && isPasswordAuth && (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="flex items-center justify-start gap-x-2 textlabel">+ {t("data-source.ssl-connection")}+ <button+ type="button"+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${+ dataSource.useSsl ? "bg-accent" : "bg-gray-200"+ }`}+ onClick={() => handleUseSslChanged(!dataSource.useSsl)}+ >+ <span+ className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition-transform ${+ dataSource.useSsl ? "translate-x-4.5" : "translate-x-0.5"+ }`}+ />+ </button>+ {isCreating && onOpenInfoPanel && hasSslInfo && (+ <button+ type="button"+ className="text-accent text-xs hover:underline"+ onClick={() => onOpenInfoPanel("ssl")}+ >+ ⓘ+ </button>+ )}+ </div>+ {dataSource.useSsl && (+ <>+ {dataSource.pendingCreate || dataSource.updateSsl ? (+ <SslCertificateForm+ verify={dataSource.verifyTlsCertificate}+ onVerifyChange={(val) =>+ update({ verifyTlsCertificate: val })+ }+ ca={dataSource.sslCa}+ onCaChange={(val) =>+ update({ sslCa: val, updateSsl: true })+ }+ cert={dataSource.sslCert}+ onCertChange={(val) =>+ update({ sslCert: val, updateSsl: true })+ }+ sslKey={dataSource.sslKey}+ onKeyChange={(val) =>+ update({ sslKey: val, updateSsl: true })+ }+ engineType={basicInfo.engine}+ disabled={!allowEdit}+ />+ ) : (+ <Button+ variant="outline"+ className="mt-2"+ disabled={!allowEdit}+ onClick={handleEditSSL}+ >+ {t("common.edit")} - {t("common.write-only")}+ </Button>+ )}+ </>+ )}+ </div>+ )}++ {/* SSH */}+ {!hideAdvancedFeatures && showSSH && isPasswordAuth && (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="flex flex-row items-center gap-x-1">+ <label className="textlabel block">+ {t("data-source.ssh-connection")}+ </label>+ {isCreating && onOpenInfoPanel && hasSshInfo && (+ <button+ type="button"+ className="text-accent text-xs hover:underline"+ onClick={() => onOpenInfoPanel("ssh")}+ >+ ⓘ+ </button>+ )}+ </div>+ <SshConnectionForm+ value={dataSource}+ instance={instance}+ disabled={!allowEdit}+ onChange={handleSSHChange}+ />+ </div>+ )}++ {/* Extra connection parameters */}+ {hasExtraParameters && (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="flex flex-row items-center justify-between">+ <label className="textlabel block">+ {t("data-source.extra-params.self")}+ </label>+ </div>+ <div className="textinfolabel text-sm mt-1 mb-2">+ {t("data-source.extra-params.description")}+ </div>++ {allowEdit && (+ <div className="flex mt-2 mb-2 gap-x-2 bg-gray-50 p-3 rounded-md">+ <Input+ value={newParamKey}+ className="w-full"+ placeholder={t("instance.parameter-name-placeholder")}+ onChange={(e) => setNewParamKey(e.target.value)}+ />+ <Input+ value={newParamValue}+ className="w-full"+ placeholder={t("instance.parameter-value-placeholder")}+ onChange={(e) => setNewParamValue(e.target.value)}+ />+ <Button+ variant="outline"+ size="sm"+ disabled={!newParamKey.trim()}+ onClick={addNewParameter}+ >+ Add+ </Button>+ </div>+ )}++ {extraConnectionParamsList.map((param, index) => (+ <div key={param.key} className="flex mt-2 gap-x-2">+ <Input+ className="w-full"+ value={param.key}+ disabled={!allowEdit}+ placeholder="Parameter name"+ onChange={(e) =>+ updateExtraConnectionParamKey(index, e.target.value)+ }+ />+ <Input+ className="w-full"+ value={param.value}+ disabled={!allowEdit}+ placeholder="Parameter value"+ onChange={(e) =>+ updateExtraConnectionParamValue(index, e.target.value)+ }+ />+ {allowEdit && (+ <Button+ variant="destructive"+ size="sm"+ onClick={() => removeExtraConnectionParam(index)}+ >+ Remove+ </Button>+ )}+ </div>+ ))}++ {extraConnectionParamsList.length === 0 && (+ <div className="textinfolabel text-sm italic">+ {allowEdit+ ? t("instance.no-params-yet-add-above")+ : t("instance.no-extra-params-configured")}+ </div>+ )}+ </div>+ )}+ </>+ )}+ </div>+ );+}++// Matches Vue OracleSIDAndServiceNameInput.vue exactly+function OracleSIDServiceNameInput({+ sid,+ serviceName,+ allowEdit,+ onSidChange,+ onServiceNameChange,+}: {+ sid: string;+ serviceName: string;+ allowEdit: boolean;+ onSidChange: (val: string) => void;+ onServiceNameChange: (val: string) => void;+}) {+ // Track which mode is selected — default to "serviceName" if both empty+ const mode = sid ? "sid" : "serviceName";++ const handleModeChange = (newMode: "sid" | "serviceName") => {+ if (newMode === "sid") {+ onServiceNameChange("");+ if (!sid) onSidChange("XE");+ } else {+ onSidChange("");+ }+ };++ return (+ <div className="sm:col-span-3 sm:col-start-1">+ <div className="textlabel flex gap-x-4 mb-2">+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={mode === "sid"}+ onChange={() => handleModeChange("sid")}+ disabled={!allowEdit}+ />+ SID+ </label>+ <label className="flex items-center gap-x-1.5 cursor-pointer">+ <input+ type="radio"+ checked={mode === "serviceName"}+ onChange={() => handleModeChange("serviceName")}+ disabled={!allowEdit}+ />+ Service Name+ </label>+ </div>+ <Input+ value={mode === "sid" ? sid : serviceName}+ className="w-full"+ disabled={!allowEdit}+ onChange={(e) => {+ if (mode === "sid") {+ onSidChange(e.target.value);+ } else {+ onServiceNameChange(e.target.value);+ }+ }}+ />+ </div>+ );+}diff --git a/frontend/src/react/components/instance/DataSourceSection.tsx b/frontend/src/react/components/instance/DataSourceSection.tsxnew file mode 100644index 0000000000..c1d1271f7d--- /dev/null+++ b/frontend/src/react/components/instance/DataSourceSection.tsx@@ -0,0 +1,207 @@+import { Plus } from "lucide-react";+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { useInstanceV1Store } from "@/store";+import { DATASOURCE_READONLY_USER_NAME } from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";+import type { EditDataSource } from "./common";+import { wrapEditDataSource } from "./common";+import { DataSourceForm } from "./DataSourceForm";+import { useInstanceFormContext } from "./InstanceFormContext";+import type { InfoSection } from "./info-content";++interface DataSourceSectionProps {+ hideOptions?: boolean;+ onOpenInfoPanel?: (section: InfoSection) => void;+}++export function DataSourceSection({+ hideOptions = false,+ onOpenInfoPanel,+}: DataSourceSectionProps) {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const {+ instance,+ isCreating,+ allowEdit,+ basicInfo,+ dataSourceEditState,+ setDataSourceEditState,+ adminDataSource,+ editingDataSource,+ readonlyDataSourceList,+ hasReadOnlyDataSource,+ } = ctx;+ const instanceStore = useInstanceV1Store();++ const allowUpdate = hasWorkspacePermissionV2("bb.instances.update");++ const handleCreateRODataSource = useCallback(() => {+ if (isCreating) return;+ const ds = {+ ...wrapEditDataSource(undefined),+ type: DataSourceType.READ_ONLY,+ host: adminDataSource.host,+ port: adminDataSource.port,+ database: adminDataSource.database,+ username: DATASOURCE_READONLY_USER_NAME,+ };+ if (+ basicInfo.engine === Engine.SPANNER ||+ basicInfo.engine === Engine.BIGQUERY ||+ basicInfo.engine === Engine.DYNAMODB+ ) {+ ds.host = adminDataSource.host;+ }+ setDataSourceEditState((prev) => ({+ dataSources: [...prev.dataSources, ds],+ editingDataSourceId: ds.id,+ }));+ }, [isCreating, adminDataSource, basicInfo.engine, setDataSourceEditState]);++ const handleDeleteDataSource = useCallback(+ async (ds: EditDataSource) => {+ if (instance && !ds.pendingCreate) {+ await instanceStore.deleteDataSource(instance, ds);+ }+ setDataSourceEditState((prev) => {+ const dataSources = prev.dataSources.filter((d) => d.id !== ds.id);+ let editingDataSourceId = prev.editingDataSourceId;+ if (ds.id === editingDataSourceId) {+ const index = prev.dataSources.findIndex((d) => d.id === ds.id);+ const siblingIndex = Math.min(index, dataSources.length - 1);+ editingDataSourceId = dataSources[siblingIndex]?.id;+ }+ return { dataSources, editingDataSourceId };+ });+ },+ [instance, instanceStore, setDataSourceEditState]+ );++ const handleDataSourceChange = useCallback(+ (updated: EditDataSource) => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) =>+ ds.id === updated.id ? updated : ds+ ),+ }));+ },+ [setDataSourceEditState]+ );++ const handleTabChange = useCallback(+ (tabId: string | number | null) => {+ if (typeof tabId === "string") {+ setDataSourceEditState((prev) => ({+ ...prev,+ editingDataSourceId: tabId,+ }));+ }+ },+ [setDataSourceEditState]+ );++ // Show RO tips when not creating and no RO data source+ const showROTips = !isCreating && !hasReadOnlyDataSource;++ return (+ <>+ {showROTips && (+ <div className="mt-2 rounded-md bg-yellow-50 border border-yellow-200 p-3 flex items-center justify-between">+ <span className="text-sm text-yellow-800">+ {t("data-source.no-read-only-data-source")}+ </span>+ <Button+ variant="outline"+ size="sm"+ onClick={handleCreateRODataSource}+ >+ {t("common.create")}+ </Button>+ </div>+ )}++ <div className="mt-2 gap-y-2 gap-x-4 border-none">+ {/* Data source tabs */}+ {!isCreating && (+ <div className="mb-4 flex items-center gap-x-2 border-b border-block-border">+ <button+ type="button"+ className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${+ dataSourceEditState.editingDataSourceId === adminDataSource.id+ ? "border-accent text-accent"+ : "border-transparent text-control-light hover:text-main"+ }`}+ onClick={() => handleTabChange(adminDataSource.id)}+ >+ {t("common.admin")}+ </button>+ {readonlyDataSourceList.map((ds) => (+ <div key={ds.id} className="flex items-center">+ <button+ type="button"+ className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${+ dataSourceEditState.editingDataSourceId === ds.id+ ? "border-accent text-accent"+ : "border-transparent text-control-light hover:text-main"+ }`}+ onClick={() => handleTabChange(ds.id)}+ >+ {t("common.read-only")}+ </button>+ {hasReadOnlyDataSource && (+ <button+ type="button"+ className="ml-1 text-red-500 hover:text-red-700 text-xs pb-2"+ disabled={!allowUpdate}+ onClick={() => {+ if (+ ds.pendingCreate ||+ window.confirm(+ `${t("data-source.delete-read-only-data-source")}?`+ )+ ) {+ handleDeleteDataSource(ds);+ }+ }}+ >+ ✕+ </button>+ )}+ </div>+ ))}+ {!hasReadOnlyDataSource && (+ <span className="pb-2 px-1 text-sm text-control-light">+ {t("common.read-only")}+ </span>+ )}+ {allowEdit && (+ <button+ type="button"+ className="pb-2 px-1 text-control-light hover:text-main disabled:opacity-50"+ disabled={!allowUpdate}+ onClick={handleCreateRODataSource}+ >+ <Plus className="w-4 h-4" />+ </button>+ )}+ </div>+ )}++ {editingDataSource && (+ <DataSourceForm+ dataSource={editingDataSource}+ hideOptions={hideOptions}+ onDataSourceChange={handleDataSourceChange}+ onOpenInfoPanel={onOpenInfoPanel}+ />+ )}+ </div>+ </>+ );+}diff --git a/frontend/src/react/components/instance/InfoPanel.tsx b/frontend/src/react/components/instance/InfoPanel.tsxnew file mode 100644index 0000000000..f32ff876af--- /dev/null+++ b/frontend/src/react/components/instance/InfoPanel.tsx@@ -0,0 +1,190 @@+import { Check, Copy, X } from "lucide-react";+import type { ReactNode } from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { Engine } from "@/types/proto-es/v1/common_pb";+import { getInfoContent, type InfoSection } from "./info-content";++interface InfoPanelProps {+ visible: boolean;+ title: string;+ mode?: "overlay" | "docked";+ onClose: () => void;+ onBeforeLeave?: () => void;+ onAfterLeave?: () => void;+ children?: ReactNode;+}++export function InfoPanel({+ visible,+ title,+ mode = "overlay",+ onClose,+ onBeforeLeave,+ onAfterLeave,+ children,+}: InfoPanelProps) {+ const [mounted, setMounted] = useState(visible);++ useEffect(() => {+ if (visible) {+ setMounted(true);+ } else {+ onBeforeLeave?.();+ }+ }, [visible, onBeforeLeave]);++ const handleTransitionEnd = useCallback(() => {+ if (!visible) {+ setMounted(false);+ onAfterLeave?.();+ }+ }, [visible, onAfterLeave]);++ if (mode === "overlay") {+ if (!mounted) return null;+ return (+ <div+ className={`fixed inset-0 z-50 flex justify-end transition-opacity duration-200 ${+ visible ? "opacity-100" : "opacity-0 pointer-events-none"+ }`}+ onClick={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ onTransitionEnd={handleTransitionEnd}+ >+ <div+ className={`w-[500px] bg-white border-l border-block-border shadow-lg flex flex-col h-full transition-transform duration-200 ${+ visible ? "translate-x-0" : "translate-x-full"+ }`}+ >+ <PanelHeader title={title} onClose={onClose} className="px-4 py-3" />+ <div className="flex-1 overflow-y-auto px-4 py-4">{children}</div>+ </div>+ </div>+ );+ }++ // Docked mode+ if (!mounted) return null;+ return (+ <aside+ data-info-panel-docked="true"+ className={`h-full w-full min-w-0 overflow-hidden border-l border-block-border bg-white transition-all duration-150 ${+ visible ? "opacity-100" : "opacity-0 translate-x-3"+ }`}+ onTransitionEnd={handleTransitionEnd}+ >+ <div className="flex h-full flex-col">+ <PanelHeader title={title} onClose={onClose} className="px-5 py-3" />+ <div className="flex-1 overflow-y-auto px-5 py-5">{children}</div>+ </div>+ </aside>+ );+}++function PanelHeader({+ title,+ onClose,+ className,+}: {+ title: string;+ onClose: () => void;+ className?: string;+}) {+ return (+ <div+ className={`sticky top-0 z-10 flex items-center justify-between border-b border-block-border bg-white ${className ?? ""}`}+ >+ <h3 className="min-w-0 truncate text-sm font-semibold text-main">+ {title}+ </h3>+ <button+ className="text-control-light hover:text-main p-0.5 rounded"+ onClick={onClose}+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ );+}++interface InfoPanelContentProps {+ engine: Engine;+ section: InfoSection;+}++export function InfoPanelContent({ engine, section }: InfoPanelContentProps) {+ const { t } = useTranslation();+ const snippet = getInfoContent(engine, section);++ if (!snippet) {+ return (+ <div className="text-sm text-control-light italic">+ {t("instance.info-panel.no-info")}+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-y-3">+ <p className="text-sm text-main leading-relaxed">{snippet.content}</p>+ {snippet.codeBlock && (+ <div className="flex flex-col gap-y-1">+ <div className="flex flex-row">+ <pre className="flex-1 min-w-0 w-full px-3 py-2 border border-control-border bg-gray-50 whitespace-pre-line rounded-l-[3px] overflow-x-auto text-[12px]">+ <code>{snippet.codeBlock.code}</code>+ </pre>+ <div className="flex items-center -ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light bg-gray-50 hover:bg-gray-100 rounded-r-[3px]">+ <CopyButton content={snippet.codeBlock.code} />+ </div>+ </div>+ </div>+ )}+ {snippet.learnMoreLinks && snippet.learnMoreLinks.length > 0 && (+ <div className="flex flex-col gap-y-1">+ {snippet.learnMoreLinks.map((link) => (+ <a+ key={link.url}+ href={link.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs accent-link"+ >+ {link.title}+ </a>+ ))}+ </div>+ )}+ </div>+ );+}++function CopyButton({ content }: { content: string }) {+ const [copied, setCopied] = useState(false);+ const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);++ const handleCopy = useCallback(() => {+ navigator.clipboard.writeText(content);+ setCopied(true);+ clearTimeout(timerRef.current);+ timerRef.current = setTimeout(() => setCopied(false), 2000);+ }, [content]);++ useEffect(() => {+ return () => clearTimeout(timerRef.current);+ }, []);++ return (+ <button+ className="p-0.5 rounded text-control-light hover:text-main"+ onClick={handleCopy}+ >+ {copied ? (+ <Check className="w-4 h-4 text-success" />+ ) : (+ <Copy className="w-4 h-4" />+ )}+ </button>+ );+}diff --git a/frontend/src/react/components/instance/InstanceActionDropdown.tsx b/frontend/src/react/components/instance/InstanceActionDropdown.tsxnew file mode 100644index 0000000000..4045bfd411--- /dev/null+++ b/frontend/src/react/components/instance/InstanceActionDropdown.tsx@@ -0,0 +1,150 @@+import { EllipsisVertical } from "lucide-react";+import { useCallback, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { router } from "@/router";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";+import { pushNotification, useInstanceV1Store } from "@/store";+import { State } from "@/types/proto-es/v1/common_pb";+import type { Instance } from "@/types/proto-es/v1/instance_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";++interface InstanceActionDropdownProps {+ instance: Instance;+ onDeleted?: () => void;+}++export function InstanceActionDropdown({+ instance,+ onDeleted,+}: InstanceActionDropdownProps) {+ const { t } = useTranslation();+ const instanceStore = useInstanceV1Store();+ const [open, setOpen] = useState(false);+ const dropdownRef = useRef<HTMLDivElement>(null);++ const canArchive = hasWorkspacePermissionV2("bb.instances.delete");+ const canRestore = hasWorkspacePermissionV2("bb.instances.undelete");++ const handleArchive = useCallback(async () => {+ const msg = t("instance.archive-instance-instance-name", {+ 0: instance.title,+ });+ const forceArchive = window.confirm(+ `${msg}\n\n${t("instance.archived-instances-will-not-be-displayed")}\n\n${t("instance.force-archive-description")}`+ );+ if (!forceArchive) return;++ await instanceStore.archiveInstance(instance, true);+ pushNotification({+ module: "bytebase",+ style: "INFO",+ title: t("instance.successfully-archived-instance", {+ 0: instance.title,+ }),+ });+ router.replace({ name: INSTANCE_ROUTE_DASHBOARD });+ }, [instance, instanceStore, t]);++ const handleRestore = useCallback(async () => {+ if (+ !window.confirm(+ t("instance.restore-instance-instance-name-to-normal-state", {+ 0: instance.title,+ })+ )+ )+ return;++ await instanceStore.restoreInstance(instance);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-restored-instance", {+ 0: instance.title,+ }),+ });+ }, [instance, instanceStore, t]);++ const handleDelete = useCallback(async () => {+ if (+ !window.confirm(+ `${t("common.delete-resource", { resource: instance.title })}\n\n${t("common.cannot-undo-this-action")}`+ )+ )+ return;++ await instanceStore.deleteInstance(instance.name);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.deleted"),+ });+ onDeleted?.();+ router.replace({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: { q: "state:DELETED" },+ });+ }, [instance, instanceStore, t, onDeleted]);++ const options: { key: string; label: string; handler: () => void }[] = [];++ if (instance.state === State.ACTIVE && canArchive) {+ options.push({+ key: "archive",+ label: t("common.archive"),+ handler: handleArchive,+ });+ } else if (instance.state === State.DELETED && canRestore) {+ options.push({+ key: "restore",+ label: t("common.restore"),+ handler: handleRestore,+ });+ }++ if (canArchive || canRestore) {+ options.push({+ key: "delete",+ label: t("common.delete"),+ handler: handleDelete,+ });+ }++ if (options.length === 0) return null;++ return (+ <div className="relative" ref={dropdownRef}>+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={() => setOpen(!open)}+ >+ <EllipsisVertical className="w-4 h-4" />+ </Button>+ {open && (+ <>+ <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />+ <div className="absolute right-0 top-full mt-1 z-50 min-w-[120px] rounded-md border bg-white shadow-md py-1">+ {options.map((opt) => (+ <button+ key={opt.key}+ type="button"+ className={`w-full text-left px-3 py-1.5 text-sm hover:bg-gray-100 ${+ opt.key === "delete" ? "text-red-600" : ""+ }`}+ onClick={() => {+ setOpen(false);+ opt.handler();+ }}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/instance/InstanceFormBody.tsx b/frontend/src/react/components/instance/InstanceFormBody.tsxnew file mode 100644index 0000000000..9c3cd49b1f--- /dev/null+++ b/frontend/src/react/components/instance/InstanceFormBody.tsx@@ -0,0 +1,2032 @@+import { create } from "@bufbuild/protobuf";+import type { Duration } from "@bufbuild/protobuf/wkt";+import { DurationSchema } from "@bufbuild/protobuf/wkt";+import {+ ChevronDown,+ ChevronRight,+ ExternalLink,+ Plus,+ Trash2,+} from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { EnvironmentSelect } from "@/react/components/EnvironmentSelect";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import {+ pushNotification,+ useActuatorV1Store,+ useDatabaseV1Store,+ useInstanceV1Store,+ useSubscriptionV1Store,+} from "@/store";+import {+ environmentNamePrefix,+ instanceNamePrefix,+} from "@/store/modules/v1/common";+import { isValidEnvironmentName, UNKNOWN_ID } from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ DataSource_AddressSchema,+ DataSource_AuthenticationType,+ DataSource_RedisType,+ DataSourceType,+} from "@/types/proto-es/v1/instance_service_pb";+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";+import {+ engineNameV1,+ extractInstanceResourceName,+ isDev,+ isValidSpannerHost,+ supportedEngineV1List,+ urlfy,+} from "@/utils";+import type { EditDataSource } from "./common";+import {+ EngineIconPath,+ MongoDBConnectionStringSchemaList,+ RedisConnectionType,+ SnowflakeExtraLinkPlaceHolder,+} from "./constants";+import { DataSourceForm } from "./DataSourceForm";+import { DataSourceSection } from "./DataSourceSection";+import { useInstanceFormContext } from "./InstanceFormContext";+import { hasInfoContent, type InfoSection } from "./info-content";++// --- Inline sub-components ---++function SpannerHostInput({+ host,+ onHostChange,+ allowEdit,+}: {+ host: string;+ onHostChange: (host: string) => void;+ allowEdit: boolean;+}) {+ const { t } = useTranslation();+ const RE =+ /^projects\/(?<PROJECT_ID>(?:[a-z]|[-.:]|[0-9])*)\/instances\/(?<INSTANCE_ID>(?:[a-z]|[-]|[0-9])*)$/;+ const RE_PROJECT_ID = /^(?:[a-z]|[-.:]|[0-9])+$/;+ const RE_INSTANCE_ID = /^(?:[a-z]|[-]|[0-9])+$/;++ const parseProjectId = (h: string) => h.match(RE)?.groups?.PROJECT_ID ?? "";+ const parseInstanceId = (h: string) => h.match(RE)?.groups?.INSTANCE_ID ?? "";++ const [projectId, setProjectId] = useState(() => parseProjectId(host));+ const [instanceId, setInstanceId] = useState(() => parseInstanceId(host));+ const [dirty, setDirty] = useState(false);++ useEffect(() => {+ if (!host) return;+ setProjectId(parseProjectId(host));+ setInstanceId(parseInstanceId(host));+ }, [host]);++ const update = useCallback(+ (pId: string, iId: string) => {+ setDirty(true);+ if (!RE_PROJECT_ID.test(pId) || !RE_INSTANCE_ID.test(iId)) {+ onHostChange("");+ return;+ }+ onHostChange(`projects/${pId}/instances/${iId}`);+ },+ [onHostChange]+ );++ const isValidProjectId = RE_PROJECT_ID.test(projectId);+ const isValidInstanceId = RE_INSTANCE_ID.test(instanceId);++ return (+ <div className="grid grid-cols-2 gap-x-2 gap-y-1">+ <div>+ <label className="textlabel">+ {t("instance.project-id")}+ <span style={{ color: "red" }}> *</span>+ </label>+ <Input+ value={projectId}+ required+ placeholder="projectId"+ className={`mt-1 w-full ${dirty && !isValidProjectId ? "border-error" : ""}`}+ disabled={!allowEdit}+ onChange={(e) => {+ const v = e.target.value;+ setProjectId(v);+ update(v, instanceId);+ }}+ />+ </div>+ <div>+ <label className="textlabel">+ {t("instance.instance-id")}+ <span style={{ color: "red" }}> *</span>+ </label>+ <Input+ value={instanceId}+ required+ placeholder="instanceId"+ className={`mt-1 w-full ${dirty && !isValidInstanceId ? "border-error" : ""}`}+ disabled={!allowEdit}+ onChange={(e) => {+ const v = e.target.value;+ setInstanceId(v);+ update(projectId, v);+ }}+ />+ </div>+ <p className="col-span-2 textinfolabel">+ {t("instance.find-gcp-project-id-and-instance-id")}{" "}+ <a+ href="https://docs.bytebase.com/get-started/connect/gcp?source=console"+ target="_blank"+ rel="noopener noreferrer"+ className="normal-link inline-flex items-center"+ >+ {t("common.detailed-guide")}+ <ExternalLink className="w-4 h-4 ml-1" />+ </a>+ </p>+ </div>+ );+}++function BigQueryHostInput({+ host,+ onHostChange,+ allowEdit,+}: {+ host: string;+ onHostChange: (host: string) => void;+ allowEdit: boolean;+}) {+ const { t } = useTranslation();+ const RE_PROJECT_ID = /^(?:[a-z]|[-.:]|[0-9])+$/;+ const [projectId, setProjectId] = useState(() => host || "");+ const [dirty, setDirty] = useState(false);++ useEffect(() => {+ if (!host) return;+ setProjectId(host);+ }, [host]);++ const isValidProjectId = RE_PROJECT_ID.test(projectId);++ return (+ <div className="grid grid-cols-2 gap-x-2 gap-y-1">+ <div>+ <label className="textlabel">+ {t("instance.project-id")}+ <span style={{ color: "red" }}> *</span>+ </label>+ <Input+ value={projectId}+ required+ placeholder="projectId"+ className={`mt-1 w-full ${dirty && !isValidProjectId ? "border-error" : ""}`}+ disabled={!allowEdit}+ onChange={(e) => {+ const v = e.target.value;+ setProjectId(v);+ setDirty(true);+ if (!RE_PROJECT_ID.test(v)) {+ onHostChange("");+ } else {+ onHostChange(v);+ }+ }}+ />+ </div>+ <p className="col-span-2 textinfolabel">+ {t("instance.find-gcp-project-id")}{" "}+ <a+ href="https://docs.bytebase.com/get-started/connect/gcp?source=console"+ target="_blank"+ rel="noopener noreferrer"+ className="normal-link inline-flex items-center"+ >+ {t("common.detailed-guide")}+ <ExternalLink className="w-4 h-4 ml-1" />+ </a>+ </p>+ </div>+ );+}++function InstanceEngineRadioGrid({+ engine,+ engineList,+ onEngineChange,+ isEngineBeta,+}: {+ engine: Engine;+ engineList: Engine[];+ onEngineChange: (engine: Engine) => void;+ isEngineBeta: (engine: Engine) => boolean;+}) {+ return (+ <div className="w-full grid grid-cols-2 sm:grid-cols-[repeat(auto-fit,minmax(170px,1fr))] gap-2">+ {engineList.map((eng) => (+ <button+ key={eng}+ type="button"+ className={`flex items-center gap-x-2 rounded-md border px-3 py-2 text-sm text-left transition-colors ${+ eng === engine+ ? "border-accent bg-accent/5 ring-1 ring-accent"+ : "border-control-border hover:border-accent/50 hover:bg-gray-50"+ }`}+ onClick={() => onEngineChange(eng)}+ >+ {EngineIconPath[eng] && (+ <img+ src={EngineIconPath[eng]}+ alt=""+ className="w-5 h-5 shrink-0"+ />+ )}+ <span className="truncate">{engineNameV1(eng)}</span>+ {isEngineBeta(eng) && (+ <span className="ml-auto shrink-0 rounded-full bg-blue-100 px-2 py-0.5 text-xs text-blue-600">+ Beta+ </span>+ )}+ </button>+ ))}+ </div>+ );+}++// Matches Vue ResourceIdField component behavior exactly:+// - Auto-generates resource ID from title with escape + optional random suffix on duplicate+// - Shows inline "Instance ID: xxx It cannot be changed later. Edit" by default+// - Only shows input field when "Edit" is clicked (manualEdit mode)+// - Validates: empty, min/max length, pattern, duplicate via fetchResource++const RESOURCE_ID_CHARS = "abcdefghijklmnopqrstuvwxyz1234567890-";+const RESOURCE_ID_PATTERN = /^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/;++function randomString(len: number): string {+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";+ let result = "";+ for (let i = 0; i < len; i++) {+ result += chars.charAt(Math.floor(Math.random() * chars.length));+ }+ return result;+}++function escapeResourceTitle(str: string): string {+ return str+ .toLowerCase()+ .split("")+ .map((char) => {+ if (char === " ") return "-";+ if (char.match(/\s/)) return "";+ if (RESOURCE_ID_CHARS.includes(char)) return char;+ // Map non-ASCII to a deterministic letter+ const alpha = "abcdefghijklmnopqrstuvwxyz";+ return alpha.charAt(char.charCodeAt(0) % alpha.length);+ })+ .join("")+ .toLowerCase();+}++interface ValidatedMessage {+ type: "error" | "warning";+ message: string;+}++function ResourceIdField({+ value,+ onChange,+ onValidationChange,+ resourceTitle,+ readonly,+ fetchResource,+}: {+ value: string;+ onChange: (id: string) => void;+ onValidationChange?: (valid: boolean) => void;+ resourceTitle: string;+ readonly: boolean;+ fetchResource?: (id: string) => Promise<unknown>;+}) {+ const { t } = useTranslation();+ const [resourceId, setResourceId] = useState(value);+ const [manualEdit, setManualEdit] = useState(false);+ const [validatedMessages, setValidatedMessages] = useState<+ ValidatedMessage[]+ >([]);+ const initializedRef = useRef(false);++ const resourceName = t("dynamic.resource.instance");++ const validate = useCallback(+ async (id: string): Promise<ValidatedMessage[]> => {+ const msgs: ValidatedMessage[] = [];+ if (id === "") {+ msgs.push({+ type: "error",+ message: t("resource-id.validation.empty", {+ resource: resourceName,+ }),+ });+ } else if (id.length > 64) {+ msgs.push({+ type: "error",+ message: t("resource-id.validation.overflow", {+ resource: resourceName,+ }),+ });+ } else if (!RESOURCE_ID_PATTERN.test(id)) {+ msgs.push({+ type: "error",+ message: t("resource-id.validation.pattern", {+ resource: resourceName,+ }),+ });+ }++ if (msgs.length === 0 && fetchResource && id && !readonly) {+ try {+ const resource = await fetchResource(id);+ if (resource) {+ msgs.push({+ type: "error",+ message: t("resource-id.validation.duplicated", {+ resource: resourceName,+ }),+ });+ }+ } catch {+ // NotFound = available, which is good+ }+ }+ return msgs;+ },+ [fetchResource, readonly, resourceName, t]+ );++ const handleResourceIdChange = useCallback(+ async (newValue: string) => {+ setResourceId(newValue);+ onChange(newValue);+ const msgs = await validate(newValue);+ setValidatedMessages(msgs);+ onValidationChange?.(msgs.length === 0 && newValue !== "");+ return msgs;+ },+ [onChange, validate, onValidationChange]+ );++ // Auto-generate from title (mirrors Vue watcher on resourceTitle)+ useEffect(() => {+ if (readonly || manualEdit) return;++ const escapedTitle = escapeResourceTitle(resourceTitle);+ const name = escapedTitle || "";+ if (!name) return;++ (async () => {+ const msgs = await handleResourceIdChange(name);++ // On first init, if duplicate, append random suffix+ if (!initializedRef.current) {+ if (msgs.length > 0) {+ await handleResourceIdChange(+ name + "-" + randomString(4).toLowerCase()+ );+ }+ }+ initializedRef.current = true;+ })();+ }, [resourceTitle]);++ if (readonly) {+ if (!resourceId) return null;+ return (+ <div className="sm:col-span-3 sm:col-start-1 -mt-4">+ <div className="mt-4 textinfolabel text-sm flex items-center gap-x-1">+ {t("resource-id.self", { resource: resourceName })}:{" "}+ <span className="text-gray-600 font-medium">{resourceId}</span>+ </div>+ </div>+ );+ }++ if (!manualEdit) {+ return (+ <div className="sm:col-span-3 sm:col-start-1 -mt-4">+ <div className="mt-4 textinfolabel text-sm flex items-start flex-wrap gap-x-1">+ <div className="flex items-center gap-x-1">+ {t("resource-id.self", { resource: resourceName })}:+ {resourceId ? (+ <span className="text-gray-600 font-medium mr-1">+ {resourceId}+ </span>+ ) : (+ <span className="text-control-placeholder italic">+ <EMPTY>+ </span>+ )}+ </div>+ <div>+ <span>{t("resource-id.cannot-be-changed-later")}</span>+ <span+ className="text-accent font-medium cursor-pointer hover:opacity-80 ml-1"+ onClick={() => setManualEdit(true)}+ >+ {t("common.edit")}+ </span>+ </div>+ </div>+ {validatedMessages.length > 0 && (+ <ul className="w-full my-2 flex flex-col gap-y-2 list-disc list-outside pl-4">+ {validatedMessages.map((msg) => (+ <li+ key={msg.message}+ className={`text-xs break-words ${+ msg.type === "warning" ? "text-yellow-600" : "text-red-600"+ }`}+ >+ {msg.message}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+ }++ return (+ <div className="sm:col-span-3 sm:col-start-1 -mt-4">+ <div className="mt-4">+ <label className="textlabel flex items-center">+ {t("resource-id.self", { resource: resourceName })}+ <span className="ml-0.5 text-error">*</span>+ </label>+ <div className="textinfolabel mb-2 mt-1">+ {t("resource-id.description", { resource: resourceName })}+ </div>+ <Input+ value={resourceId}+ className={`w-full max-w-[40rem] ${+ validatedMessages.some((m) => m.type === "error")+ ? "border-error"+ : ""+ }`}+ placeholder={t("resource-id.self", { resource: resourceName })}+ onChange={(e) => {+ handleResourceIdChange(e.target.value);+ }}+ />+ </div>+ {validatedMessages.length > 0 && (+ <ul className="w-full my-2 flex flex-col gap-y-2 list-disc list-outside pl-4">+ {validatedMessages.map((msg) => (+ <li+ key={msg.message}+ className={`text-xs break-words ${+ msg.type === "warning" ? "text-yellow-600" : "text-red-600"+ }`}+ >+ {msg.message}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++// Matches Vue LabelListEditor + LabelEditorRow exactly+const MAX_LABEL_VALUE_LENGTH = 256;++function LabelListEditor({+ kvList,+ onChange,+ readonly,+ showErrors = true,+ onErrorsChange,+}: {+ kvList: { key: string; value: string }[];+ onChange: (list: { key: string; value: string }[]) => void;+ readonly: boolean;+ showErrors?: boolean;+ onErrorsChange?: (errors: string[]) => void;+}) {+ const { t } = useTranslation();++ // Compute validation errors for each kv pair+ const errorList = useMemo(() => {+ return kvList.map((kv) => {+ const errors = { key: [] as string[], value: [] as string[] };+ if (!kv.key) {+ errors.key.push(t("label.error.key-necessary"));+ } else if (kvList.filter((k) => k.key === kv.key).length > 1) {+ errors.key.push(t("label.error.key-duplicated"));+ }+ if (!kv.value) {+ errors.value.push(t("label.error.value-necessary"));+ } else if (kv.value.length > MAX_LABEL_VALUE_LENGTH) {+ errors.value.push(+ t("label.error.max-value-length-exceeded", {+ length: MAX_LABEL_VALUE_LENGTH,+ })+ );+ }+ return errors;+ });+ }, [kvList, t]);++ const flatErrors = useMemo(() => {+ return errorList.flatMap((e) => [...e.key, ...e.value]);+ }, [errorList]);++ const hasErrors = flatErrors.length > 0;++ useEffect(() => {+ onErrorsChange?.(flatErrors);+ }, [flatErrors, onErrorsChange]);++ const allowAddLabel = !hasErrors;++ const updateKey = (index: number, key: string) => {+ onChange(kvList.map((kv, i) => (i === index ? { ...kv, key } : kv)));+ };+ const updateValue = (index: number, value: string) => {+ onChange(kvList.map((kv, i) => (i === index ? { ...kv, value } : kv)));+ };+ const handleRemove = (index: number) => {+ onChange(kvList.filter((_, i) => i !== index));+ };+ const handleAdd = () => {+ onChange([...kvList, { key: "", value: "" }]);+ };++ return (+ <div className="flex flex-col gap-y-2">+ <div className="flex flex-wrap gap-x-2 gap-y-2">+ {kvList.map((kv, index) => {+ const errors = showErrors+ ? (errorList[index] ?? { key: [], value: [] })+ : { key: [], value: [] };+ const combinedErrors = [...errors.key, ...errors.value];+ return (+ <div key={index} className="flex flex-col gap-y-1">+ <div className="text-sm flex gap-x-2">+ <div className="flex flex-col">+ <span className="text-xs font-medium mb-1">+ Key {index + 1}+ </span>+ {readonly ? (+ <span className="leading-[34px]">{kv.key}</span>+ ) : (+ <Input+ value={kv.key}+ placeholder={t("setting.label.key-placeholder")}+ className={errors.key.length > 0 ? "border-error" : ""}+ onChange={(e) => updateKey(index, e.target.value)}+ />+ )}+ </div>+ <div className="flex flex-col">+ <span className="text-xs font-medium mb-1">+ Value {index + 1}+ </span>+ <div className="flex items-center gap-x-2">+ {readonly ? (+ <span className="leading-[34px]">+ {kv.value || (+ <span className="text-control-placeholder">+ {t("label.empty-label-value")}+ </span>+ )}+ </span>+ ) : (+ <Input+ value={kv.value}+ placeholder={t("setting.label.value-placeholder")}+ className={+ errors.value.length > 0 ? "border-error" : ""+ }+ onChange={(e) => updateValue(index, e.target.value)}+ />+ )}+ <button+ type="button"+ className={`ml-1 ${readonly ? "invisible" : "visible"} text-control-light hover:text-error`}+ onClick={() => handleRemove(index)}+ >+ <Trash2 className="w-4 h-4" />+ </button>+ </div>+ </div>+ </div>+ {combinedErrors.length > 0 && (+ <ul className="text-xs text-error list-disc list-outside pl-4">+ {combinedErrors.map((err) => (+ <li key={err}>{err}</li>+ ))}+ </ul>+ )}+ </div>+ );+ })}+ </div>+ <div>+ <Button+ variant="outline"+ size="sm"+ disabled={readonly || !allowAddLabel}+ onClick={handleAdd}+ >+ <Plus className="w-4 h-4 mr-1" />+ {t("label.add-label")}+ </Button>+ </div>+ </div>+ );+}++const MIN_SCAN_MINUTES = 30;++function ScanIntervalInput({+ scanInterval,+ allowEdit,+ onScanIntervalChange,+}: {+ scanInterval: Duration | undefined;+ allowEdit: boolean;+ onScanIntervalChange: (interval: Duration | undefined) => void;+}) {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const { instance: _instance, hideAdvancedFeatures } = ctx;++ const extractState = (+ duration: Duration | undefined+ ): { mode: "DEFAULT" | "CUSTOM"; minutes: number | undefined } => {+ if (!duration || Number(duration.seconds) === 0) {+ return { mode: "DEFAULT", minutes: undefined };+ }+ return {+ mode: "CUSTOM",+ minutes: Math.floor(Number(duration.seconds) / 60),+ };+ };++ const [mode, setMode] = useState<"DEFAULT" | "CUSTOM">(+ () => extractState(scanInterval).mode+ );+ const [minutes, setMinutes] = useState<number | undefined>(+ () => extractState(scanInterval).minutes+ );+ const [isValid, setIsValid] = useState(true);++ useEffect(() => {+ const s = extractState(scanInterval);+ setMode(s.mode);+ setMinutes(s.minutes);+ setIsValid(true);+ }, [scanInterval]);++ const handleModeChange = (targetMode: "DEFAULT" | "CUSTOM") => {+ if (targetMode === mode) return;+ setMode(targetMode);+ if (targetMode === "DEFAULT") {+ onScanIntervalChange(create(DurationSchema, { seconds: BigInt(0) }));+ } else {+ setMinutes(24 * 60);+ onScanIntervalChange(+ create(DurationSchema, { seconds: BigInt(24 * 60 * 60) })+ );+ }+ };++ const handleMinuteChange = (value: string) => {+ const num = parseInt(value, 10);+ if (Number.isNaN(num)) {+ setMinutes(undefined);+ setIsValid(false);+ return;+ }+ setMinutes(num);+ if (num < MIN_SCAN_MINUTES) {+ setIsValid(false);+ return;+ }+ setIsValid(true);+ onScanIntervalChange(create(DurationSchema, { seconds: BigInt(num * 60) }));+ };++ if (hideAdvancedFeatures) return null;++ return (+ <div className="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2">+ <div className="flex items-center gap-x-2">+ <label className="textlabel">{t("instance.scan-interval.self")}</label>+ </div>+ <div className="textinfolabel">+ {t("instance.scan-interval.description")}+ </div>+ <div className="flex items-center gap-x-6">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="radio"+ checked={mode === "DEFAULT"}+ disabled={!allowEdit}+ onChange={() => handleModeChange("DEFAULT")}+ />+ {t("instance.scan-interval.default-never")}+ </label>+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="radio"+ checked={mode === "CUSTOM"}+ disabled={!allowEdit}+ onChange={() => handleModeChange("CUSTOM")}+ />+ <span>{t("common.custom")}</span>+ <Input+ type="number"+ value={minutes ?? ""}+ className={`w-16 ${!isValid ? "border-error" : ""}`}+ placeholder={`>= ${MIN_SCAN_MINUTES}`}+ disabled={mode !== "CUSTOM"}+ onChange={(e) => handleMinuteChange(e.target.value)}+ />+ {!isValid ? (+ <span className="text-error text-sm">+ {t("instance.scan-interval.min-value", {+ value: MIN_SCAN_MINUTES,+ })}+ </span>+ ) : (+ <span className="text-sm">{t("common.minutes")}</span>+ )}+ </label>+ </div>+ </div>+ );+}++function SyncDatabases({+ isCreating: isCreatingProp,+ showLabel,+ allowEdit,+ syncDatabases,+ onSyncDatabasesChange,+}: {+ isCreating: boolean;+ showLabel: boolean;+ allowEdit: boolean;+ syncDatabases: string[];+ onSyncDatabasesChange: (databases: string[]) => void;+}) {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const { hideAdvancedFeatures, instance } = ctx;+ const instanceStore = useInstanceV1Store();++ const [syncAll, setSyncAll] = useState(syncDatabases.length === 0);+ const [selectedDatabases, setSelectedDatabases] = useState<string[]>([+ ...syncDatabases,+ ]);+ const [databaseList, setDatabaseList] = useState<Set<string>>(new Set());+ const [loading, setLoading] = useState(false);+ const [searchText, setSearchText] = useState("");+ const [inputDatabase, setInputDatabase] = useState("");++ useEffect(() => {+ if (syncAll) {+ onSyncDatabasesChange([]);+ } else {+ onSyncDatabasesChange(selectedDatabases);+ }+ }, [syncAll, selectedDatabases]);++ useEffect(() => {+ if (syncAll) return;+ const fetchDatabases = async () => {+ const inst = isCreatingProp ? ctx.pendingCreateInstance : instance;+ if (!inst) return;+ setLoading(true);+ try {+ const resp = await instanceStore.listInstanceDatabases(+ inst.name,+ isCreatingProp ? inst : undefined+ );+ setDatabaseList(new Set([...resp.databases, ...selectedDatabases]));+ } finally {+ setLoading(false);+ }+ };+ fetchDatabases();+ }, [syncAll]);++ if (hideAdvancedFeatures) return null;++ const filteredDatabases = [...databaseList].filter((db) =>+ db.toLowerCase().includes(searchText.toLowerCase())+ );++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.nativeEvent.isComposing) return;+ const trimmed = inputDatabase.trim();+ if (!trimmed) return;+ if (e.key === "Enter") {+ setDatabaseList((prev) => new Set([...prev, trimmed]));+ setSelectedDatabases((prev) => [...prev, trimmed]);+ setInputDatabase("");+ }+ };++ const toggleDatabase = (db: string) => {+ setSelectedDatabases((prev) =>+ prev.includes(db) ? prev.filter((d) => d !== db) : [...prev, db]+ );+ };++ return (+ <div className="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2">+ {showLabel && (+ <div className="flex items-center gap-x-2">+ <label className="textlabel">+ {t("instance.sync-databases.self")}+ </label>+ </div>+ )}+ <div className="textinfolabel">+ {t("instance.sync-databases.description")}+ </div>+ <div className="flex flex-col gap-y-2">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="checkbox"+ checked={syncAll}+ disabled={!allowEdit}+ onChange={(e) => setSyncAll(e.target.checked)}+ />+ {t("instance.sync-databases.sync-all")}+ </label>+ {!syncAll && (+ <div>+ {loading ? (+ <div className="opacity-60 text-sm text-control-light">+ {t("common.loading")}...+ </div>+ ) : (+ <div className="border rounded-xs p-2 flex flex-col gap-y-2">+ <Input+ value={searchText}+ className="w-full"+ placeholder={t("instance.sync-databases.search-database")}+ onChange={(e) => setSearchText(e.target.value)}+ />+ <div className="max-h-[250px] overflow-y-auto flex flex-col gap-y-1">+ {filteredDatabases.map((db) => (+ <label+ key={db}+ className="flex items-center gap-x-2 cursor-pointer text-sm"+ >+ <input+ type="checkbox"+ checked={selectedDatabases.includes(db)}+ disabled={!allowEdit}+ onChange={() => toggleDatabase(db)}+ />+ <span>{db}</span>+ </label>+ ))}+ </div>+ <Input+ value={inputDatabase}+ className="w-full"+ placeholder={t("instance.sync-databases.add-database")}+ disabled={!allowEdit}+ onChange={(e) => setInputDatabase(e.target.value)}+ onKeyDown={handleKeyDown}+ />+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ );+}++// --- Main component ---++interface InstanceFormBodyProps {+ onOpenInfoPanel?: (section: InfoSection) => void;+}++export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const {+ instance,+ state,+ specs,+ isCreating,+ allowEdit,+ allowCreate,+ environment,+ basicInfo,+ setBasicInfo,+ labelKVList,+ setLabelKVList,+ dataSourceEditState,+ setDataSourceEditState,+ adminDataSource,+ editingDataSource,+ checkDataSource,+ testConnection,+ resetDataSource,+ showConnectionOptionsEvent,+ emitShowConnectionOptions,+ setResourceIdValidated,+ } = ctx;+ const { isEngineBeta, defaultPort, instanceLink, allowEditPort } = specs;++ const instanceV1Store = useInstanceV1Store();+ const actuatorStore = useActuatorV1Store();+ const subscriptionStore = useSubscriptionV1Store();++ const [isEngineSelectorCollapsed, setIsEngineSelectorCollapsed] =+ useState(false);+ const [isConnectionOptionsCollapsed, setIsConnectionOptionsCollapsed] =+ useState(true);++ // Auto-expand connection options when configured+ const showConnectionOptionsCard =+ basicInfo.engine !== Engine.DYNAMODB && !!editingDataSource;++ const hasConfiguredConnectionOptions = useMemo(() => {+ const ds = editingDataSource;+ if (!ds) return false;+ const hasExtraParameters =+ Object.keys(ds.extraConnectionParameters ?? {}).length > 0;+ const hasSslConfig = !!(ds.useSsl || ds.sslCa || ds.sslCert || ds.sslKey);+ const hasSshConfig = !!(+ ds.sshHost ||+ ds.sshPort ||+ ds.sshUser ||+ ds.sshPassword ||+ ds.sshPrivateKey+ );+ return hasExtraParameters || hasSslConfig || hasSshConfig;+ }, [editingDataSource]);++ // Collapse state management based on visibility and configuration+ const prevShowRef = useRef(showConnectionOptionsCard);+ const prevConfiguredRef = useRef(hasConfiguredConnectionOptions);+ useEffect(() => {+ if (!showConnectionOptionsCard) {+ prevShowRef.current = false;+ return;+ }+ const becameVisible = !prevShowRef.current;+ if (becameVisible) {+ setIsConnectionOptionsCollapsed(+ isCreating ? true : !hasConfiguredConnectionOptions+ );+ prevShowRef.current = true;+ prevConfiguredRef.current = hasConfiguredConnectionOptions;+ return;+ }+ if (+ !isCreating &&+ hasConfiguredConnectionOptions &&+ !prevConfiguredRef.current+ ) {+ setIsConnectionOptionsCollapsed(false);+ }+ prevShowRef.current = showConnectionOptionsCard;+ prevConfiguredRef.current = hasConfiguredConnectionOptions;+ }, [showConnectionOptionsCard, isCreating, hasConfiguredConnectionOptions]);++ // Listen for show-connection-options event+ const prevEventRef = useRef(showConnectionOptionsEvent);+ useEffect(() => {+ if (showConnectionOptionsEvent !== prevEventRef.current) {+ prevEventRef.current = showConnectionOptionsEvent;+ if (showConnectionOptionsCard) {+ setIsConnectionOptionsCollapsed(false);+ }+ }+ }, [showConnectionOptionsEvent, showConnectionOptionsCard]);++ // --- Computed values ---++ const availableLicenseCount = useMemo(+ () =>+ Math.max(+ 0,+ subscriptionStore.instanceLicenseCount -+ actuatorStore.activatedInstanceCount+ ),+ [+ subscriptionStore.instanceLicenseCount,+ actuatorStore.activatedInstanceCount,+ ]+ );++ const availableLicenseCountText = useMemo((): string => {+ if (subscriptionStore.instanceLicenseCount === Number.MAX_VALUE) {+ return t("common.unlimited");+ }+ return `${availableLicenseCount}`;+ }, [subscriptionStore.instanceLicenseCount, availableLicenseCount, t]);++ const resourceId = useMemo(() => {+ const id = extractInstanceResourceName(basicInfo.name);+ if (id === String(UNKNOWN_ID)) return "";+ return id;+ }, [basicInfo.name]);++ const setResourceId = useCallback(+ (id: string) => {+ setBasicInfo((prev) => ({ ...prev, name: `instances/${id}` }));+ },+ [setBasicInfo]+ );++ const currentMongoDBConnectionSchema = useMemo(() => {+ return adminDataSource.srv === false+ ? MongoDBConnectionStringSchemaList[0]+ : MongoDBConnectionStringSchemaList[1];+ }, [adminDataSource.srv]);++ const currentRedisConnectionType = useMemo(() => {+ switch (adminDataSource.redisType) {+ case DataSource_RedisType.STANDALONE:+ return RedisConnectionType[0];+ case DataSource_RedisType.SENTINEL:+ return RedisConnectionType[1];+ case DataSource_RedisType.CLUSTER:+ return RedisConnectionType[2];+ default:+ return RedisConnectionType[0];+ }+ }, [adminDataSource.redisType]);++ const showAdditionalAddresses = useMemo(() => {+ if (basicInfo.engine === Engine.CASSANDRA) return true;+ if (basicInfo.engine === Engine.MONGODB && !adminDataSource.srv)+ return true;+ if (+ basicInfo.engine === Engine.REDIS &&+ (adminDataSource.redisType === DataSource_RedisType.CLUSTER ||+ adminDataSource.redisType === DataSource_RedisType.SENTINEL)+ )+ return true;+ return false;+ }, [basicInfo.engine, adminDataSource.srv, adminDataSource.redisType]);++ const allowTestConnection = useMemo(() => {+ if (!allowEdit || state.isRequesting || state.isTestingConnection) {+ return false;+ }+ const ds = editingDataSource;+ if (!ds) return false;+ if (basicInfo.engine === Engine.SPANNER) {+ return isValidSpannerHost(ds.host);+ }+ if (basicInfo.engine === Engine.BIGQUERY) {+ return ds.host !== "";+ }+ if (basicInfo.engine !== Engine.DYNAMODB && ds.host === "") {+ return false;+ }+ return checkDataSource([ds]);+ }, [allowEdit, state, editingDataSource, basicInfo.engine, checkDataSource]);++ const hasHostInfo = useMemo(+ () => hasInfoContent(basicInfo.engine, "host"),+ [basicInfo.engine]+ );++ // --- Handlers ---++ const updateBasicInfo = useCallback(+ (partial: Partial<typeof basicInfo>) => {+ setBasicInfo((prev) => ({ ...prev, ...partial }));+ },+ [setBasicInfo]+ );++ const updateAdminDS = useCallback(+ (partial: Partial<EditDataSource>) => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) =>+ ds.type === DataSourceType.ADMIN ? { ...ds, ...partial } : ds+ ),+ }));+ },+ [setDataSourceEditState]+ );++ const changeInstanceEngine = useCallback(+ (engine: Engine) => {+ resetDataSource();+ // After resetDataSource, we need to adjust the host based on the new engine.+ // Use a direct state update instead.+ setDataSourceEditState((prev) => {+ const dataSources = prev.dataSources.map((ds) => {+ if (ds.type !== DataSourceType.ADMIN) return ds;+ const updated = { ...ds };+ switch (engine) {+ case Engine.SNOWFLAKE:+ case Engine.DYNAMODB: {+ if (+ updated.host === "127.0.0.1" ||+ updated.host === "host.docker.internal"+ ) {+ updated.host = "";+ }+ break;+ }+ case Engine.SPANNER:+ case Engine.BIGQUERY: {+ updated.authenticationType =+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM;+ if (+ updated.host === "127.0.0.1" ||+ updated.host === "host.docker.internal"+ ) {+ updated.host = "";+ }+ break;+ }+ case Engine.COSMOSDB: {+ updated.authenticationType =+ DataSource_AuthenticationType.AZURE_IAM;+ break;+ }+ default: {+ if (!updated.host) {+ updated.host = isDev() ? "127.0.0.1" : "host.docker.internal";+ }+ break;+ }+ }+ return updated;+ });+ return { ...prev, dataSources };+ });+ setBasicInfo((prev) => ({ ...prev, engine }));+ },+ [resetDataSource, setDataSourceEditState, setBasicInfo]+ );++ const handleSelectInstanceEngine = useCallback(+ (engine: Engine) => {+ changeInstanceEngine(engine);+ setIsEngineSelectorCollapsed(true);+ },+ [changeInstanceEngine]+ );++ const handleSelectEnvironment = useCallback(+ (name: string | undefined) => {+ setBasicInfo((prev) => ({ ...prev, environment: name }));+ },+ [setBasicInfo]+ );++ const handleChangeSyncDatabases = useCallback(+ (databases: string[]) => {+ setBasicInfo((prev) => ({ ...prev, syncDatabases: [...databases] }));+ },+ [setBasicInfo]+ );++ const changeScanInterval = useCallback(+ (duration: Duration | undefined) => {+ setBasicInfo((prev) => ({ ...prev, syncInterval: duration }));+ },+ [setBasicInfo]+ );++ const handleRedisConnectionTypeChange = useCallback(+ (type: string) => {+ let redisType = DataSource_RedisType.STANDALONE;+ switch (type) {+ case RedisConnectionType[1]:+ redisType = DataSource_RedisType.SENTINEL;+ break;+ case RedisConnectionType[2]:+ redisType = DataSource_RedisType.CLUSTER;+ break;+ }+ updateAdminDS({ redisType });+ },+ [updateAdminDS]+ );++ const handleMongodbConnectionStringSchemaChange = useCallback(+ (type: string) => {+ if (type === MongoDBConnectionStringSchemaList[1]) {+ updateAdminDS({+ port: "",+ additionalAddresses: [],+ replicaSet: "",+ directConnection: false,+ srv: true,+ });+ } else {+ updateAdminDS({ srv: false });+ }+ },+ [updateAdminDS]+ );++ const removeDSAdditionalAddress = useCallback(+ (index: number) => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) => {+ if (ds.type !== DataSourceType.ADMIN) return ds;+ const newAddresses = [...ds.additionalAddresses];+ newAddresses.splice(index, 1);+ return {+ ...ds,+ additionalAddresses: newAddresses,+ directConnection:+ newAddresses.length === 0 ? false : ds.directConnection,+ };+ }),+ }));+ },+ [setDataSourceEditState]+ );++ const addDSAdditionalAddress = useCallback(() => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) => {+ if (ds.id !== dataSourceEditState.editingDataSourceId) return ds;+ const newAddresses = [+ ...ds.additionalAddresses,+ create(DataSource_AddressSchema, { host: "", port: "" }),+ ];+ return {+ ...ds,+ additionalAddresses: newAddresses,+ directConnection:+ newAddresses.length !== 0 ? false : ds.directConnection,+ };+ }),+ }));+ }, [setDataSourceEditState, dataSourceEditState.editingDataSourceId]);++ const changeInstanceActivation = useCallback(+ async (on: boolean) => {+ updateBasicInfo({ activation: on });+ if (instance) {+ const instancePatch = { ...instance, activation: on };+ const updated = await instanceV1Store.updateInstance(instancePatch, [+ "activation",+ ]);+ useDatabaseV1Store().updateDatabaseInstance(updated);+ await actuatorStore.fetchServerInfo(+ actuatorStore.workspaceResourceName+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ }+ },+ [instance, instanceV1Store, actuatorStore, updateBasicInfo, t]+ );++ const testConnectionForCurrentEditingDS = useCallback(async () => {+ const ds = editingDataSource;+ if (!ds) return;+ const result = await testConnection(ds, false);+ if (!result.success && hasConfiguredConnectionOptions) {+ emitShowConnectionOptions();+ }+ }, [+ editingDataSource,+ testConnection,+ hasConfiguredConnectionOptions,+ emitShowConnectionOptions,+ ]);++ const handleDataSourceChange = useCallback(+ (updated: EditDataSource) => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) =>+ ds.id === updated.id ? updated : ds+ ),+ }));+ },+ [setDataSourceEditState]+ );++ const openInfoPanel = useCallback(+ (section: InfoSection) => {+ if (!hasInfoContent(basicInfo.engine, section)) return;+ onOpenInfoPanel?.(section);+ },+ [basicInfo.engine, onOpenInfoPanel]+ );++ // Port-only numeric filter+ const handlePortChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const value = e.target.value;+ if (value === "" || /^\d+$/.test(value)) {+ updateAdminDS({ port: value });+ }+ },+ [updateAdminDS]+ );++ const handleAdditionalAddressHostChange = useCallback(+ (index: number, host: string) => {+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) => {+ if (ds.type !== DataSourceType.ADMIN) return ds;+ const newAddresses = [...ds.additionalAddresses];+ newAddresses[index] = { ...newAddresses[index], host };+ return { ...ds, additionalAddresses: newAddresses };+ }),+ }));+ },+ [setDataSourceEditState]+ );++ const handleAdditionalAddressPortChange = useCallback(+ (index: number, port: string) => {+ if (port !== "" && !/^\d+$/.test(port)) return;+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: prev.dataSources.map((ds) => {+ if (ds.type !== DataSourceType.ADMIN) return ds;+ const newAddresses = [...ds.additionalAddresses];+ newAddresses[index] = { ...newAddresses[index], port };+ return { ...ds, additionalAddresses: newAddresses };+ }),+ }));+ },+ [setDataSourceEditState]+ );++ return (+ <div className="flex flex-col gap-y-6 pb-2">+ <div className="w-full flex flex-col gap-y-6">+ {/* Engine Selector (create only) */}+ {isCreating && (+ <div className="rounded-lg border border-block-border bg-white">+ <button+ type="button"+ className="w-full flex items-center justify-between gap-x-3 px-4 py-3 text-left transition-colors hover:bg-gray-50"+ onClick={() => setIsEngineSelectorCollapsed((prev) => !prev)}+ >+ <div className="min-w-0">+ <p className="text-[11px] font-medium uppercase tracking-[0.14em] text-control-light">+ {t("database.engine")}+ </p>+ <div className="mt-1 flex items-center gap-x-1.5">+ {EngineIconPath[basicInfo.engine] && (+ <img+ src={EngineIconPath[basicInfo.engine]}+ alt=""+ className="w-4 h-4"+ />+ )}+ <span className="text-sm font-medium text-main">+ {engineNameV1(basicInfo.engine)}+ </span>+ {isEngineBeta(basicInfo.engine) && (+ <span className="rounded-full bg-blue-100 px-2 py-0.5 text-xs text-blue-600">+ Beta+ </span>+ )}+ </div>+ </div>+ <div className="shrink-0 text-control-light">+ {!isEngineSelectorCollapsed ? (+ <ChevronDown className="w-4 h-4" />+ ) : (+ <ChevronRight className="w-4 h-4" />+ )}+ </div>+ </button>++ {!isEngineSelectorCollapsed && (+ <div className="border-t border-block-border px-4 py-4">+ <InstanceEngineRadioGrid+ engine={basicInfo.engine}+ engineList={supportedEngineV1List()}+ onEngineChange={handleSelectInstanceEngine}+ isEngineBeta={isEngineBeta}+ />+ </div>+ )}+ </div>+ )}++ {/* Basic Info Card */}+ <div className="border border-block-border rounded-lg p-5">+ <h3 className="text-base font-medium text-main">+ {t("instance.section.basic-info")}+ </h3>++ <div className="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ {/* Instance Name */}+ <div className="sm:col-span-2 sm:col-start-1">+ <label+ htmlFor="name"+ className="textlabel flex flex-row items-center"+ >+ {t("instance.instance-name")}+ <span className="ml-0.5 text-error">*</span>+ {instance && (+ <div className="ml-2 flex items-center">+ {EngineIconPath[instance.engine] && (+ <img+ src={EngineIconPath[instance.engine]}+ alt=""+ className="w-4 h-4"+ />+ )}+ <span className="ml-1">{instance.engineVersion}</span>+ </div>+ )}+ </label>+ <Input+ value={basicInfo.title}+ required+ className="mt-1 w-full max-w-[40rem]"+ disabled={!allowEdit}+ maxLength={200}+ onChange={(e) => updateBasicInfo({ title: e.target.value })}+ />+ </div>++ {/* Activation toggle */}+ {subscriptionStore.currentPlan !== PlanType.FREE && allowEdit && (+ <div className="sm:col-span-2 ml-0 sm:ml-3">+ <label htmlFor="activation" className="textlabel block">+ {t("subscription.instance-assignment.assign-license")} (+ <a href="/setting/subscription" className="accent-link">+ {t("subscription.instance-assignment.n-license-remain", {+ n: availableLicenseCountText,+ })}+ </a>+ )+ </label>+ <div className="h-8.5 flex flex-row items-center mt-1">+ <label className="relative inline-flex items-center cursor-pointer">+ <input+ type="checkbox"+ className="sr-only peer"+ checked={basicInfo.activation}+ disabled={+ !basicInfo.activation && availableLicenseCount === 0+ }+ onChange={(e) =>+ changeInstanceActivation(e.target.checked)+ }+ />+ <div className="w-9 h-5 bg-gray-300 peer-focus:outline-none rounded-full peer peer-checked:bg-accent transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />+ </label>+ </div>+ </div>+ )}++ {/* Resource ID */}+ <div className="sm:col-span-3 sm:col-start-1 -mt-4">+ <ResourceIdField+ value={resourceId}+ onChange={setResourceId}+ onValidationChange={setResourceIdValidated}+ resourceTitle={basicInfo.title}+ readonly={!isCreating}+ fetchResource={(id) =>+ instanceV1Store.getOrFetchInstanceByName(+ `${instanceNamePrefix}${id}`,+ true /* silent */+ )+ }+ />+ </div>++ {/* Environment */}+ <div className="sm:col-span-2 sm:col-start-1">+ <label htmlFor="environment" className="textlabel">+ {t("common.environment")}+ </label>+ <EnvironmentSelect+ className="mt-1 w-full max-w-[40rem]"+ value={+ isValidEnvironmentName(+ `${environmentNamePrefix}${environment.id}`+ )+ ? `${environmentNamePrefix}${environment.id}`+ : ""+ }+ disabled={!allowEdit}+ onChange={(value) =>+ handleSelectEnvironment(value || undefined)+ }+ />+ </div>++ {/* Labels */}+ <div className="sm:col-span-3 sm:col-start-1">+ <label htmlFor="labels" className="textlabel">+ {t("common.labels")}+ </label>+ <div className="mt-1">+ <LabelListEditor+ kvList={labelKVList}+ onChange={setLabelKVList}+ readonly={!allowEdit}+ showErrors+ onErrorsChange={ctx.setLabelErrors}+ />+ </div>+ </div>++ {/* External link (edit mode only) */}+ {!isCreating && (+ <div className="sm:col-span-3 sm:col-start-1">+ <label+ htmlFor="external-link"+ className="textlabel inline-flex"+ >+ <span>+ {basicInfo.engine === Engine.SNOWFLAKE+ ? t("instance.snowflake-web-console")+ : t("instance.external-link")}+ </span>+ {(basicInfo.externalLink ?? "").trim().length > 0 && (+ <button+ className="ml-1 btn-icon"+ onClick={(e) => {+ e.preventDefault();+ window.open(+ urlfy(basicInfo.externalLink ?? ""),+ "_blank"+ );+ }}+ >+ <ExternalLink className="w-4 h-4" />+ </button>+ )}+ </label>+ {basicInfo.engine === Engine.SNOWFLAKE ? (+ <Input+ required+ className="mt-1 w-full"+ disabled+ value={instanceLink}+ />+ ) : (+ <>+ <div className="mt-1 textinfolabel">+ {t("instance.sentence.console.snowflake")}+ </div>+ <Input+ value={basicInfo.externalLink ?? ""}+ required+ className="textfield mt-1 w-full"+ disabled={!allowEdit}+ placeholder={SnowflakeExtraLinkPlaceHolder}+ onChange={(e) =>+ updateBasicInfo({ externalLink: e.target.value })+ }+ />+ </>+ )}+ </div>+ )}++ {/* Scan Interval (edit mode only) */}+ {!isCreating && instance && (+ <ScanIntervalInput+ scanInterval={basicInfo.syncInterval}+ allowEdit={allowEdit}+ onScanIntervalChange={changeScanInterval}+ />+ )}++ {/* Sync Databases (edit mode) */}+ {!isCreating && (+ <SyncDatabases+ isCreating={false}+ showLabel+ allowEdit={allowEdit}+ syncDatabases={basicInfo.syncDatabases}+ onSyncDatabasesChange={handleChangeSyncDatabases}+ />+ )}+ </div>+ </div>++ {/* Connection Card */}+ <div className="border border-block-border rounded-lg p-5">+ <h3 className="text-base font-medium text-main">+ {t("instance.section.connection")}+ </h3>++ <div className="mt-3 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ {/* Host input */}+ <div className="sm:col-span-3 sm:col-start-1">+ {basicInfo.engine === Engine.SPANNER ? (+ <SpannerHostInput+ host={adminDataSource.host}+ onHostChange={(host) => updateAdminDS({ host })}+ allowEdit={allowEdit}+ />+ ) : basicInfo.engine === Engine.BIGQUERY ? (+ <BigQueryHostInput+ host={adminDataSource.host}+ onHostChange={(host) => updateAdminDS({ host })}+ allowEdit={allowEdit}+ />+ ) : (+ <>+ <label htmlFor="host" className="textlabel block">+ {basicInfo.engine === Engine.SNOWFLAKE ? (+ <>+ {t("instance.account-locator")}+ <span className="mr-2 text-error"> *</span>+ <a+ href="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier"+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm normal-link"+ >+ {t("common.learn-more")}+ </a>+ </>+ ) : basicInfo.engine === Engine.COSMOSDB ? (+ <>+ {t("instance.endpoint")}+ <span className="text-error"> *</span>+ </>+ ) : adminDataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ? (+ <div>+ <span>+ {t(+ "instance.sentence.google-cloud-sql.instance-name"+ )}+ <span className="text-error"> *</span>+ </span>+ <div className="textinfolabel mb-1">+ {t(+ "instance.sentence.google-cloud-sql.instance-name-tips"+ ).replace(+ "{instance}",+ "{project-id}:{region}:{instance-name}"+ )}+ </div>+ </div>+ ) : (+ <>+ {t("instance.host-or-socket")}+ {basicInfo.engine !== Engine.DYNAMODB && (+ <span className="text-error"> *</span>+ )}+ {isCreating && onOpenInfoPanel && hasHostInfo && (+ <button+ type="button"+ className="ml-1 text-accent hover:text-accent-hover text-sm"+ onClick={() => openInfoPanel("host")}+ >+ ?+ </button>+ )}+ </>+ )}+ </label>+ <Input+ value={adminDataSource.host}+ required+ placeholder={+ basicInfo.engine === Engine.SNOWFLAKE+ ? t("instance.your-snowflake-account-locator")+ : t("instance.sentence.host.none-snowflake")+ }+ className="mt-1 w-full"+ disabled={!allowEdit}+ onChange={(e) => updateAdminDS({ host: e.target.value })}+ />+ {basicInfo.engine === Engine.SNOWFLAKE && (+ <div className="mt-2 textinfolabel">+ {t("instance.sentence.proxy.snowflake")}+ </div>+ )}+ </>+ )}+ </div>++ {/* Port input */}+ {basicInfo.engine !== Engine.SPANNER &&+ basicInfo.engine !== Engine.BIGQUERY &&+ basicInfo.engine !== Engine.DATABRICKS &&+ basicInfo.engine !== Engine.COSMOSDB &&+ adminDataSource.authenticationType !==+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (+ <div className="sm:col-span-1">+ <label htmlFor="port" className="textlabel block">+ {t("instance.port")}+ </label>+ <Input+ value={adminDataSource.port}+ className="mt-1 w-full"+ placeholder={defaultPort}+ disabled={!allowEdit || !allowEditPort}+ onChange={handlePortChange}+ />+ </div>+ )}++ {/* MongoDB connection string schema */}+ {basicInfo.engine === Engine.MONGODB && (+ <div className="sm:col-span-4 sm:col-start-1">+ <label+ htmlFor="connectionStringSchema"+ className="textlabel flex flex-row items-center"+ >+ {t("data-source.connection-string-schema")}+ </label>+ <div className="flex items-center gap-x-4 mt-1">+ {MongoDBConnectionStringSchemaList.map((type) => (+ <label+ key={type}+ className="flex items-center gap-x-2 cursor-pointer"+ >+ <input+ type="radio"+ checked={currentMongoDBConnectionSchema === type}+ onChange={() =>+ handleMongodbConnectionStringSchemaChange(type)+ }+ />+ {type}+ </label>+ ))}+ </div>+ </div>+ )}++ {/* Redis connection type */}+ {basicInfo.engine === Engine.REDIS && (+ <div className="sm:col-span-4 sm:col-start-1 flex flex-col gap-y-2">+ <label+ htmlFor="connectionStringSchema"+ className="textlabel flex flex-row items-center"+ >+ {t("data-source.connection-type")}+ </label>+ <div className="flex items-center gap-x-4">+ {RedisConnectionType.map((type) => (+ <label+ key={type}+ className="flex items-center gap-x-2 cursor-pointer"+ >+ <input+ type="radio"+ checked={currentRedisConnectionType === type}+ onChange={() => handleRedisConnectionTypeChange(type)}+ />+ {type}+ </label>+ ))}+ </div>+ </div>+ )}++ {/* Additional addresses */}+ {showAdditionalAddresses && (+ <div className="sm:col-span-4 sm:col-start-1">+ <label+ htmlFor="additionalAddresses"+ className="textlabel flex flex-row items-center"+ >+ {t("data-source.additional-node-addresses")}+ </label>+ <div className="mt-1 grid grid-cols-1 gap-y-1 gap-x-4 sm:grid-cols-12">+ {adminDataSource.additionalAddresses.map((addr, index) => (+ <div key={index} className="contents">+ <div className="sm:col-span-8 sm:col-start-1">+ {index === 0 && (+ <label+ htmlFor="additionalAddressesHost"+ className="textlabel font-normal! flex flex-row items-center"+ >+ {t("instance.host-or-socket")}+ </label>+ )}+ <Input+ value={addr.host}+ required+ className="mt-1 w-full"+ disabled={!allowEdit}+ onChange={(e) =>+ handleAdditionalAddressHostChange(+ index,+ e.target.value+ )+ }+ />+ </div>+ <div className="sm:col-span-3">+ {index === 0 && (+ <label+ htmlFor="additionalAddressesPort"+ className="textlabel font-normal! flex flex-row items-center"+ >+ {t("instance.port")}+ </label>+ )}+ <Input+ value={addr.port}+ className="mt-1 w-full"+ placeholder={defaultPort}+ disabled={!allowEdit || !allowEditPort}+ onChange={(e) =>+ handleAdditionalAddressPortChange(+ index,+ e.target.value+ )+ }+ />+ </div>+ <div className="h-8.5 flex flex-row items-center self-end">+ <button+ type="button"+ className="p-1 text-control-light hover:text-error disabled:opacity-50"+ disabled={!allowEdit}+ onClick={() => removeDSAdditionalAddress(index)}+ >+ <Trash2 className="w-4 h-4" />+ </button>+ </div>+ </div>+ ))}+ <div className="mt-1 sm:col-span-12 sm:col-start-1">+ <Button+ variant="outline"+ size="sm"+ className="ml-auto w-12!"+ onClick={(e) => {+ e.preventDefault();+ addDSAdditionalAddress();+ }}+ >+ {t("common.add")}+ </Button>+ </div>+ </div>+ </div>+ )}++ {/* MongoDB replica set */}+ {basicInfo.engine === Engine.MONGODB && !adminDataSource.srv && (+ <div className="sm:col-span-2 sm:col-start-1">+ <label htmlFor="replicaSet" className="textlabel">+ {t("data-source.replica-set")}+ </label>+ <Input+ value={adminDataSource.replicaSet}+ required+ className="mt-1 w-full"+ disabled={!allowEdit}+ onChange={(e) =>+ updateAdminDS({ replicaSet: e.target.value })+ }+ />+ </div>+ )}++ {/* MongoDB direct connection */}+ {basicInfo.engine === Engine.MONGODB &&+ !adminDataSource.srv &&+ adminDataSource.additionalAddresses.length === 0 && (+ <div className="sm:col-span-4 sm:col-start-1">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="checkbox"+ checked={adminDataSource.directConnection}+ disabled={!allowEdit}+ onChange={(e) =>+ updateAdminDS({+ directConnection: e.target.checked,+ })+ }+ />+ {t("data-source.direct-connection")}+ </label>+ </div>+ )}+ </div>++ {/* Credentials (auth method, username, password) */}+ {basicInfo.engine !== Engine.DYNAMODB && (+ <>+ <DataSourceSection+ hideOptions+ onOpenInfoPanel={onOpenInfoPanel}+ />++ {actuatorStore.isSaaSMode && (+ <div className="mt-4 rounded-md border-none bg-blue-50 p-3">+ <a+ href="https://docs.bytebase.com/get-started/cloud#prerequisites"+ target="_blank"+ rel="noopener noreferrer"+ className="normal-link text-sm"+ >+ {t("instance.sentence.firewall-info")}+ </a>+ </div>+ )}+ </>+ )}+ </div>++ {/* Connection Options Card */}+ {basicInfo.engine !== Engine.DYNAMODB && editingDataSource && (+ <div className="border border-block-border rounded-lg bg-white">+ <button+ type="button"+ className="w-full flex items-center justify-between gap-x-3 px-5 py-4 text-left transition-colors hover:bg-gray-50"+ onClick={() => setIsConnectionOptionsCollapsed((prev) => !prev)}+ >+ <h3 className="text-base font-medium text-main">+ {t("instance.connection-options")}+ </h3>+ <div className="shrink-0 text-control-light">+ {!isConnectionOptionsCollapsed ? (+ <ChevronDown className="w-4 h-4" />+ ) : (+ <ChevronRight className="w-4 h-4" />+ )}+ </div>+ </button>+ {!isConnectionOptionsCollapsed && (+ <div className="border-t border-block-border px-5 py-4">+ <DataSourceForm+ dataSource={editingDataSource}+ optionsOnly+ onDataSourceChange={handleDataSourceChange}+ onOpenInfoPanel={onOpenInfoPanel}+ />+ </div>+ )}+ </div>+ )}++ {/* Test Connection button (create only) */}+ {isCreating && !!editingDataSource && (+ <div className="flex justify-start">+ <Button+ variant="outline"+ disabled={!allowTestConnection || state.isTestingConnection}+ onClick={(e) => {+ e.preventDefault();+ testConnectionForCurrentEditingDS();+ }}+ >+ {state.isTestingConnection+ ? `${t("instance.test-connection")}...`+ : t("instance.test-connection")}+ </Button>+ </div>+ )}++ {/* Sync Databases Card (create only) */}+ {basicInfo.engine !== Engine.DYNAMODB && isCreating && (+ <div className="border border-block-border rounded-lg p-5 flex flex-col gap-y-1">+ <p className="w-full text-lg leading-6 font-medium text-gray-900">+ {t("instance.sync-databases.self")}+ </p>+ <SyncDatabases+ isCreating+ showLabel={false}+ allowEdit={allowEdit && !!allowCreate}+ syncDatabases={basicInfo.syncDatabases}+ onSyncDatabasesChange={handleChangeSyncDatabases}+ />+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/instance/InstanceFormButtons.tsx b/frontend/src/react/components/instance/InstanceFormButtons.tsxnew file mode 100644index 0000000000..621ebc868e--- /dev/null+++ b/frontend/src/react/components/instance/InstanceFormButtons.tsx@@ -0,0 +1,496 @@+import { create } from "@bufbuild/protobuf";+import { cloneDeep, isEqual } from "lodash-es";+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import { cn } from "@/react/lib/utils";+import { router } from "@/router";+import {+ pushNotification,+ useDatabaseV1Store,+ useInstanceV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type {+ DataSource,+ Instance,+} from "@/types/proto-es/v1/instance_service_pb";+import {+ DataSourceType,+ InstanceSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { convertKVListToLabels, isValidSpannerHost } from "@/utils";+import { Button } from "../ui/button";+import type { EditDataSource } from "./common";+import {+ calcDataSourceUpdateMask,+ extractBasicInfo,+ extractDataSourceEditState,+} from "./common";+import { useInstanceFormContext } from "./InstanceFormContext";++interface InstanceFormButtonsProps {+ allowCancel?: boolean;+ onCreated?: (instance: Instance) => void;+ onUpdated?: (instance: Instance) => void;+ className?: string;+}++export function InstanceFormButtons({+ allowCancel = true,+ onCreated,+ onUpdated,+ className,+}: InstanceFormButtonsProps) {+ const { t } = useTranslation();+ const instanceV1Store = useInstanceV1Store();+ const databaseStore = useDatabaseV1Store();+ const subscriptionStore = useSubscriptionV1Store();++ const context = useInstanceFormContext();+ const {+ state,+ setState,+ instance,+ isCreating,+ allowEdit,+ allowCreate,+ basicInfo,+ setBasicInfo,+ labelKVList,+ adminDataSource,+ editingDataSource,+ readonlyDataSourceList,+ setDataSourceEditState,+ hasReadonlyReplicaFeature,+ missingFeature: _missingFeature,+ setMissingFeature,+ testConnection,+ checkDataSource,+ extractDataSourceFromEdit,+ pendingCreateInstance,+ valueChanged,+ onDismiss,+ emitShowConnectionOptions,+ } = context;++ const hasExternalSecretFeature = useMemo(+ () =>+ subscriptionStore.hasFeature(PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER),+ [subscriptionStore]+ );++ const checkExternalSecretFeature = (dataSources: DataSource[]) => {+ if (hasExternalSecretFeature) return true;+ return dataSources.every(+ (ds) => !ds.externalSecret && !/^{{.+}}$/.test(ds.password)+ );+ };++ const checkRODataSourceFeature = (inst: Instance) => {+ if (hasReadonlyReplicaFeature) return true;+ if (readonlyDataSourceList.length === 0) return true;++ const checkOne = (ds: EditDataSource) => {+ if (ds.pendingCreate) return false;+ const editing = extractDataSourceFromEdit(inst.engine, ds);+ const original = inst.dataSources.find((d) => d.id === ds.id);+ if (original) {+ const updateMask = calcDataSourceUpdateMask(editing, original, ds);+ if (updateMask.length > 0) return false;+ }+ return true;+ };+ return readonlyDataSourceList.every(checkOne);+ };++ const allowUpdate = useMemo((): boolean => {+ if (!valueChanged) return false;+ if (basicInfo.engine === Engine.SPANNER) {+ if (!isValidSpannerHost(adminDataSource.host)) return false;+ if (readonlyDataSourceList.length > 0) {+ if (readonlyDataSourceList.some((ds) => !isValidSpannerHost(ds.host)))+ return false;+ }+ return !!basicInfo.title.trim();+ }+ if (basicInfo.engine === Engine.BIGQUERY) {+ if (!adminDataSource.host) return false;+ if (readonlyDataSourceList.length > 0) {+ if (readonlyDataSourceList.some((ds) => !ds.host)) return false;+ }+ return !!basicInfo.title.trim();+ }+ return checkDataSource([adminDataSource, ...readonlyDataSourceList]);+ }, [+ valueChanged,+ basicInfo,+ adminDataSource,+ readonlyDataSourceList,+ checkDataSource,+ ]);++ const hasConfiguredConnectionOptions = (ds: EditDataSource): boolean => {+ const hasExtraParameters =+ Object.keys(ds.extraConnectionParameters ?? {}).length > 0;+ const hasSslConfig = !!(ds.useSsl || ds.sslCa || ds.sslCert || ds.sslKey);+ const hasSshConfig = !!(+ ds.sshHost ||+ ds.sshPort ||+ ds.sshUser ||+ ds.sshPassword ||+ ds.sshPrivateKey+ );+ return hasExtraParameters || hasSslConfig || hasSshConfig;+ };++ const maybeOpenConnectionOptions = (ds: EditDataSource) => {+ if (!hasConfiguredConnectionOptions(ds)) return;+ emitShowConnectionOptions();+ };++ const confirmContinueWithConnectionFailure = (message: string): boolean => {+ return window.confirm(+ `${t("common.warning")}\n\n${t("instance.unable-to-connect", { 0: message })}\n\n${t("common.continue-anyway")}?`+ );+ };++ const getOriginalEditState = () => ({+ basicInfo: extractBasicInfo(instance),+ dataSources: extractDataSourceEditState(instance).dataSources,+ });++ const resetChanges = () => {+ const original = getOriginalEditState();+ setBasicInfo(cloneDeep(original.basicInfo));+ setDataSourceEditState((prev) => ({+ ...prev,+ dataSources: cloneDeep(original.dataSources),+ }));+ };++ const doCreate = async () => {+ if (!isCreating) return;++ if (!checkExternalSecretFeature(pendingCreateInstance.dataSources)) {+ setMissingFeature(PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER);+ return;+ }++ setState((prev) => ({ ...prev, isRequesting: true }));+ try {+ const createdInstance = await instanceV1Store.createInstance(+ pendingCreateInstance+ );+ if (onCreated) {+ onCreated(createdInstance);+ } else {+ router.push(`/${createdInstance.name}`);+ onDismiss?.();+ }++ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(+ "instance.successfully-created-instance-createdinstance-name",+ {+ 0: createdInstance.title,+ }+ ),+ });+ } finally {+ setState((prev) => ({ ...prev, isRequesting: false }));+ }+ };++ const tryCreate = async () => {+ const editingDS = adminDataSource;+ const testResult = await testConnection(editingDS, true);+ if (testResult.success) {+ doCreate();+ } else {+ maybeOpenConnectionOptions(editingDS);+ const confirmed = confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (confirmed) {+ doCreate();+ }+ }+ };++ const updateEditState = (inst: Instance) => {+ setBasicInfo(extractBasicInfo(inst));+ const updatedEditState = extractDataSourceEditState(inst);+ setDataSourceEditState((prev) => {+ const newDataSources = updatedEditState.dataSources;+ const editingId =+ newDataSources.findIndex((ds) => ds.id === prev.editingDataSourceId) >=+ 0+ ? prev.editingDataSourceId+ : updatedEditState.editingDataSourceId;+ return {+ dataSources: newDataSources,+ editingDataSourceId: editingId,+ };+ });+ };++ const doUpdate = async () => {+ const inst = instance;+ if (!inst) return;++ if (!checkRODataSourceFeature(inst)) {+ setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);+ return;+ }++ if (!checkExternalSecretFeature([adminDataSource])) {+ setMissingFeature(PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER);+ return;+ }++ if (+ !checkExternalSecretFeature([adminDataSource, ...readonlyDataSourceList])+ ) {+ setMissingFeature(PlanFeature.FEATURE_EXTERNAL_SECRET_MANAGER);+ return;+ }++ const pendingRequestRunners: (() => Promise<unknown>)[] = [];++ const maybeQueueUpdateInstanceBasicInfo = () => {+ const currentLabels = convertKVListToLabels(labelKVList, false);+ const instancePatch = create(InstanceSchema, {+ ...inst,+ ...basicInfo,+ labels: currentLabels,+ });+ const updateMask: string[] = [];+ if (instancePatch.title !== inst.title) updateMask.push("title");+ if (instancePatch.externalLink !== inst.externalLink)+ updateMask.push("external_link");+ if (instancePatch.activation !== inst.activation)+ updateMask.push("activation");+ if (instancePatch.environment !== inst.environment)+ updateMask.push("environment");+ if (+ Number(instancePatch.syncInterval?.seconds || 0n) !==+ Number(inst.syncInterval?.seconds || 0n)+ ) {+ updateMask.push("sync_interval");+ }+ if (!isEqual(instancePatch.syncDatabases, inst.syncDatabases))+ updateMask.push("sync_databases");+ if (!isEqual(instancePatch.labels, inst.labels))+ updateMask.push("labels");+ if (updateMask.length === 0) return;++ pendingRequestRunners.push(() =>+ instanceV1Store.updateInstance(instancePatch, updateMask).then(() => {+ if (updateMask.includes("sync_databases")) {+ return refreshInstanceDatabases(instancePatch.name);+ }+ })+ );+ };++ const refreshInstanceDatabases = async (instanceName: string) => {+ await instanceV1Store.syncInstance(instanceName, true);+ databaseStore.removeCacheByInstance(instanceName);+ };++ const maybeQueueUpdateDataSource = async (+ editing: DataSource,+ original: DataSource | undefined,+ editState: EditDataSource+ ): Promise<boolean | undefined> => {+ if (!original) return;+ const updateMask = calcDataSourceUpdateMask(editing, original, editState);+ if (updateMask.length === 0) return;++ const testResult = await testConnection(editState, true);+ if (!testResult.success) {+ maybeOpenConnectionOptions(editState);+ const continueAnyway = confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (!continueAnyway) return true;+ }++ pendingRequestRunners.push(() =>+ instanceV1Store.updateDataSource({+ instance: inst.name,+ dataSource: editing,+ updateMask,+ })+ );+ };++ const maybeQueueUpdateAdminDataSource = async () => {+ const original = inst.dataSources.find(+ (ds) => ds.type === DataSourceType.ADMIN+ );+ const editing = extractDataSourceFromEdit(inst.engine, adminDataSource);+ return await maybeQueueUpdateDataSource(+ editing,+ original,+ adminDataSource+ );+ };++ const maybeQueueUpsertReadonlyDataSources = async (): Promise<+ boolean | undefined+ > => {+ if (readonlyDataSourceList.length === 0) return false;++ for (let i = 0; i < readonlyDataSourceList.length; i++) {+ const editingDS = readonlyDataSourceList[i];+ const patch = extractDataSourceFromEdit(inst.engine, editingDS);++ if (editingDS.pendingCreate) {+ const testResult = await testConnection(editingDS, true);+ if (!testResult.success) {+ maybeOpenConnectionOptions(editingDS);+ const continueAnyway = confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (!continueAnyway) return true;+ }+ pendingRequestRunners.push(() =>+ instanceV1Store.createDataSource({+ instance: inst.name,+ dataSource: patch,+ })+ );+ } else {+ const original = inst.dataSources.find(+ (ds) => ds.id === editingDS.id+ );+ const blocked = await maybeQueueUpdateDataSource(+ patch,+ original,+ editingDS+ );+ if (blocked) return true;+ }+ }+ };++ // Prepare pending request runners+ maybeQueueUpdateInstanceBasicInfo();+ if (await maybeQueueUpdateAdminDataSource()) return;+ if (await maybeQueueUpsertReadonlyDataSources()) return;++ if (pendingRequestRunners.length === 0) return;++ setState((prev) => ({ ...prev, isRequesting: true }));+ try {+ for (let i = 0; i < pendingRequestRunners.length; i++) {+ await pendingRequestRunners[i]();+ }++ const updatedInstance = instanceV1Store.getInstanceByName(inst.name);+ updateEditState(updatedInstance);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-updated-instance-instance-name", {+ 0: updatedInstance.title,+ }),+ });++ if (onUpdated) {+ onUpdated(updatedInstance);+ }+ } finally {+ setState((prev) => ({ ...prev, isRequesting: false }));+ }+ };++ const testConnectionForCurrentEditingDS = async () => {+ if (!editingDataSource) return;+ const testResult = await testConnection(editingDataSource, false);+ if (!testResult.success) {+ maybeOpenConnectionOptions(editingDataSource);+ }+ };++ const cancel = () => {+ onDismiss?.();+ };++ if (isCreating) {+ return (+ <div+ className={cn(+ "w-full py-4 border-t border-block-border flex justify-between bg-white",+ className+ )}+ >+ {allowCancel && (+ <Button+ variant="outline"+ disabled={state.isRequesting || state.isTestingConnection}+ onClick={cancel}+ >+ {t("common.cancel")}+ </Button>+ )}+ <div className="flex items-center gap-x-2">+ <Button+ disabled={+ !allowCreate || state.isRequesting || state.isTestingConnection+ }+ onClick={tryCreate}+ >+ {state.isRequesting ? t("common.creating") : t("common.create")}+ </Button>+ </div>+ </div>+ );+ }++ if (!instance) return null;+ if (!valueChanged || !allowEdit) return null;++ return (+ <div+ className={cn(+ "w-full mt-4 py-4 border-t border-block-border flex justify-between bg-white",+ className+ )}+ >+ <Button+ variant="outline"+ disabled={state.isTestingConnection}+ onClick={resetChanges}+ >+ {t("common.cancel")}+ </Button>+ <div className="flex items-center gap-x-2">+ <Button+ variant="ghost"+ disabled={!allowUpdate || state.isRequesting || !allowEdit}+ onClick={testConnectionForCurrentEditingDS}+ >+ {state.isTestingConnection+ ? t("instance.testing-connection")+ : t("instance.test-connection")}+ </Button>+ <Button+ disabled={+ !allowUpdate || state.isRequesting || state.isTestingConnection+ }+ onClick={doUpdate}+ >+ {state.isRequesting+ ? t("common.updating")+ : t("common.confirm-and-update")}+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/instance/InstanceFormContext.tsx b/frontend/src/react/components/instance/InstanceFormContext.tsxnew file mode 100644index 0000000000..20b5c5d5b6--- /dev/null+++ b/frontend/src/react/components/instance/InstanceFormContext.tsx@@ -0,0 +1,583 @@+import { create } from "@bufbuild/protobuf";+import { cloneDeep, isEqual, omit } from "lodash-es";+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import {+ pushNotification,+ useEnvironmentV1Store,+ useInstanceV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { Engine, State } from "@/types/proto-es/v1/common_pb";+import type {+ DataSource,+ Instance,+} from "@/types/proto-es/v1/instance_service_pb";+import {+ DataSource_AuthenticationType,+ DataSource_RedisType,+ DataSourceExternalSecret_AuthType,+ DataSourceExternalSecret_SecretType,+ DataSourceType,+ InstanceSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ convertKVListToLabels,+ convertLabelsToKVList,+ hasWorkspacePermissionV2,+ isValidSpannerHost,+} from "@/utils";+import { extractGrpcErrorMessage } from "@/utils/connect";+import type { BasicInfo, DataSourceEditState, EditDataSource } from "./common";+import {+ calcDataSourceUpdateMask,+ extractBasicInfo,+ extractDataSourceEditState,+} from "./common";+import { type InstanceSpecs, useInstanceSpecs } from "./specs";++export type LocalState = {+ editingDataSourceId: string | undefined;+ isTestingConnection: boolean;+ isRequesting: boolean;+};++export interface InstanceFormContextValue {+ instance: Instance | undefined;+ hideAdvancedFeatures: boolean;+ state: LocalState;+ setState: React.Dispatch<React.SetStateAction<LocalState>>;+ specs: InstanceSpecs;+ isCreating: boolean;+ allowEdit: boolean;+ allowCreate: boolean;+ environment: ReturnType<+ ReturnType<typeof useEnvironmentV1Store>["getEnvironmentByName"]+ >;+ basicInfo: BasicInfo;+ setBasicInfo: React.Dispatch<React.SetStateAction<BasicInfo>>;+ labelKVList: { key: string; value: string }[];+ setLabelKVList: React.Dispatch<+ React.SetStateAction<{ key: string; value: string }[]>+ >;+ dataSourceEditState: DataSourceEditState;+ setDataSourceEditState: React.Dispatch<+ React.SetStateAction<DataSourceEditState>+ >;+ adminDataSource: EditDataSource;+ editingDataSource: EditDataSource | undefined;+ readonlyDataSourceList: EditDataSource[];+ hasReadOnlyDataSource: boolean;+ hasReadonlyReplicaFeature: boolean;+ missingFeature: PlanFeature | undefined;+ setMissingFeature: React.Dispatch<+ React.SetStateAction<PlanFeature | undefined>+ >;+ resourceIdValidated: boolean;+ setResourceIdValidated: React.Dispatch<React.SetStateAction<boolean>>;+ labelErrors: string[];+ setLabelErrors: React.Dispatch<React.SetStateAction<string[]>>;+ checkDataSource: (dataSources: DataSource[]) => boolean;+ resetDataSource: () => void;+ extractDataSourceFromEdit: (+ engine: Engine,+ edit: EditDataSource+ ) => DataSource;+ testConnection: (+ editingDS: EditDataSource,+ silent?: boolean+ ) => Promise<{ success: boolean; message: string }>;+ pendingCreateInstance: Instance;+ valueChanged: boolean;+ isEditing: boolean;+ onDismiss?: () => void;+ showConnectionOptionsEvent: number;+ emitShowConnectionOptions: () => void;+}++const InstanceFormCtx = createContext<InstanceFormContextValue | null>(null);++export const useInstanceFormContext = () => {+ const ctx = useContext(InstanceFormCtx);+ if (!ctx) {+ throw new Error(+ "useInstanceFormContext must be used within InstanceFormProvider"+ );+ }+ return ctx;+};++export function InstanceFormProvider({+ instance,+ hideAdvancedFeatures = false,+ onDismiss,+ children,+}: {+ instance?: Instance;+ hideAdvancedFeatures?: boolean;+ onDismiss?: () => void;+ children: ReactNode;+}) {+ const { t } = useTranslation();+ const instanceStore = useInstanceV1Store();+ const subscriptionStore = useSubscriptionV1Store();+ const environmentStore = useEnvironmentV1Store();++ const [state, setState] = useState<LocalState>(() => ({+ editingDataSourceId: instance?.dataSources.find(+ (ds) => ds.type === DataSourceType.ADMIN+ )?.id,+ isTestingConnection: false,+ isRequesting: false,+ }));++ const [basicInfo, setBasicInfo] = useState<BasicInfo>(() =>+ extractBasicInfo(instance)+ );+ const [dataSourceEditState, setDataSourceEditState] =+ useState<DataSourceEditState>(() => extractDataSourceEditState(instance));+ const [labelKVList, setLabelKVList] = useState(() =>+ convertLabelsToKVList(basicInfo.labels, true)+ );+ const [missingFeature, setMissingFeature] = useState<+ PlanFeature | undefined+ >();+ const [resourceIdValidated, setResourceIdValidated] = useState(false);+ const [labelErrors, setLabelErrors] = useState<string[]>([]);+ const [showConnectionOptionsEvent, setShowConnectionOptionsEvent] =+ useState(0);++ const emitShowConnectionOptions = useCallback(() => {+ setShowConnectionOptionsEvent((prev) => prev + 1);+ }, []);++ const isCreating = instance === undefined;+ const allowEdit = isCreating+ ? true+ : (instance?.state || State.STATE_UNSPECIFIED) === State.ACTIVE &&+ hasWorkspacePermissionV2("bb.instances.update");++ const adminDataSource = useMemo(+ () =>+ dataSourceEditState.dataSources.find(+ (ds) => ds.type === DataSourceType.ADMIN+ )!,+ [dataSourceEditState.dataSources]+ );++ const editingDataSource = useMemo(() => {+ const { dataSources, editingDataSourceId } = dataSourceEditState;+ if (editingDataSourceId === undefined) return undefined;+ return dataSources.find((ds) => ds.id === editingDataSourceId);+ }, [dataSourceEditState]);++ const readonlyDataSourceList = useMemo(+ () =>+ dataSourceEditState.dataSources.filter(+ (ds) => ds.type === DataSourceType.READ_ONLY+ ),+ [dataSourceEditState.dataSources]+ );++ const hasReadOnlyDataSource = readonlyDataSourceList.length > 0;++ const hasReadonlyReplicaFeature = useMemo(+ () =>+ subscriptionStore.hasInstanceFeature(+ PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION,+ instance+ ),+ [subscriptionStore, instance]+ );++ const specs = useInstanceSpecs(basicInfo, adminDataSource, editingDataSource);++ const environment = useMemo(+ () => environmentStore.getEnvironmentByName(basicInfo.environment ?? ""),+ [environmentStore, basicInfo.environment]+ );++ const checkDataSource = useCallback(+ (dataSources: DataSource[]) => {+ return dataSources.every((ds) => {+ if (+ ds.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ ) {+ return /.+:.+:.+/.test(ds.host);+ }+ if (+ ds.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM+ ) {+ return !!ds.region;+ }+ if (basicInfo.engine === Engine.ORACLE) {+ if (!ds.sid && !ds.serviceName) return false;+ } else if (basicInfo.engine === Engine.DATABRICKS) {+ if (!ds.warehouseId || !ds.authenticationPrivateKey) return false;+ }+ if (ds.saslConfig?.mechanism?.case === "krbConfig") {+ const krbConfig = ds.saslConfig.mechanism.value;+ if (+ !krbConfig.primary ||+ !krbConfig.realm ||+ !krbConfig.kdcHost ||+ !krbConfig.keytab+ )+ return false;+ }+ if (!ds.externalSecret) return true;+ switch (ds.externalSecret.secretType) {+ case DataSourceExternalSecret_SecretType.VAULT_KV_V2:+ if (+ !ds.externalSecret.url ||+ !ds.externalSecret.engineName ||+ !ds.externalSecret.secretName ||+ !ds.externalSecret.passwordKeyName+ )+ return false;+ break;+ case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:+ if (+ !ds.externalSecret.secretName ||+ !ds.externalSecret.passwordKeyName+ )+ return false;+ break;+ case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:+ if (!ds.externalSecret.secretName) return false;+ break;+ }+ switch (ds.externalSecret.authType) {+ case DataSourceExternalSecret_AuthType.TOKEN:+ return !!(+ ds.externalSecret.authOption?.case === "token" &&+ ds.externalSecret.authOption.value+ );+ case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:+ return !!(+ ds.externalSecret.authOption?.case === "appRole" &&+ ds.externalSecret.authOption.value.roleId &&+ ds.externalSecret.authOption.value.secretId+ );+ }+ return true;+ });+ },+ [basicInfo.engine]+ );++ const allowCreate = useMemo(() => {+ if (!hasWorkspacePermissionV2("bb.instances.create")) return false;+ if (basicInfo.engine === Engine.SPANNER) {+ return (+ !!basicInfo.title.trim() && isValidSpannerHost(adminDataSource.host)+ );+ }+ if (basicInfo.engine === Engine.BIGQUERY) {+ return !!basicInfo.title.trim() && adminDataSource.host !== "";+ }+ if (basicInfo.engine !== Engine.DYNAMODB) {+ if (adminDataSource.host === "") return false;+ }+ if (basicInfo.engine === Engine.REDIS) {+ if (+ adminDataSource.redisType === DataSource_RedisType.SENTINEL &&+ adminDataSource.masterName === ""+ )+ return false;+ }+ const hasLabelErrs = labelErrors.length > 0;+ return (+ !!basicInfo.title.trim() &&+ resourceIdValidated &&+ checkDataSource([adminDataSource]) &&+ !hasLabelErrs+ );+ }, [+ basicInfo,+ adminDataSource,+ resourceIdValidated,+ labelErrors,+ checkDataSource,+ ]);++ const resetDataSource = useCallback(() => {+ setDataSourceEditState(extractDataSourceEditState(instance));+ }, [instance]);++ const extractDataSourceFromEdit = useCallback(+ (engine: Engine, edit: EditDataSource): DataSource => {+ const ds = cloneDeep(+ omit(+ edit,+ "pendingCreate",+ "updatedPassword",+ "useEmptyPassword",+ "updatedMasterPassword",+ "useEmptyMasterPassword",+ "updateSsl"+ )+ );+ if (edit.updatedPassword) ds.password = edit.updatedPassword;+ if (edit.useEmptyPassword) ds.password = "";+ if (edit.updatedMasterPassword)+ ds.masterPassword = edit.updatedMasterPassword;+ if (edit.useEmptyMasterPassword) ds.masterPassword = "";+ if (!specs.showDatabase) ds.database = "";+ if (engine !== Engine.ORACLE) {+ ds.sid = "";+ ds.serviceName = "";+ }+ if (engine !== Engine.MONGODB) {+ ds.srv = false;+ ds.authenticationDatabase = "";+ }+ if (!specs.showSSH) {+ ds.sshHost = "";+ ds.sshPort = "";+ ds.sshUser = "";+ ds.sshPassword = "";+ ds.sshPrivateKey = "";+ }+ if (!specs.showSSL) {+ ds.sslCa = "";+ ds.sslCert = "";+ ds.sslKey = "";+ }+ return ds;+ },+ [specs]+ );++ const pendingCreateInstance = useMemo(() => {+ const currentLabels = convertKVListToLabels(labelKVList, false);+ const inst: Instance = create(InstanceSchema, {+ ...basicInfo,+ labels: currentLabels,+ engineVersion: "",+ dataSources: [],+ });+ if (editingDataSource) {+ const dataSourceCreate = extractDataSourceFromEdit(+ inst.engine,+ adminDataSource+ );+ inst.dataSources = [dataSourceCreate];+ }+ return inst;+ }, [+ basicInfo,+ labelKVList,+ editingDataSource,+ adminDataSource,+ extractDataSourceFromEdit,+ ]);++ // Use ref for testConnection to avoid stale closures+ const stateRef = useRef(state);+ stateRef.current = state;++ const testConnection = useCallback(+ async (+ editingDS: EditDataSource,+ silent = false+ ): Promise<{ success: boolean; message: string }> => {+ const ok = () => {+ if (!silent) {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-connected-instance"),+ });+ }+ setState((prev) => ({ ...prev, isTestingConnection: false }));+ return { success: true, message: "" };+ };+ const fail = (host: string, err: unknown) => {+ let error = extractGrpcErrorMessage(err);+ if (!silent) {+ if (host === "localhost" || host === "127.0.0.1") {+ error = `${error}\n\n${t("instance.failed-to-connect-instance-localhost")}`;+ }+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("instance.failed-to-connect-instance"),+ description: error,+ manualHide: true,+ });+ }+ setState((prev) => ({ ...prev, isTestingConnection: false }));+ return { success: false, message: error };+ };++ setState((prev) => ({ ...prev, isTestingConnection: true }));++ if (isCreating) {+ const inst: Instance = create(InstanceSchema, {+ ...basicInfo,+ engineVersion: "",+ dataSources: [],+ });+ const dataSourceCreate = extractDataSourceFromEdit(+ inst.engine,+ editingDS+ );+ inst.dataSources = [dataSourceCreate];+ try {+ await instanceStore.createInstance(inst, true);+ return ok();+ } catch (err) {+ return fail(dataSourceCreate.host, err);+ }+ } else {+ const ds = extractDataSourceFromEdit(instance!.engine, editingDS);+ if (editingDS.pendingCreate) {+ try {+ await instanceStore.createDataSource({+ instance: instance!.name,+ dataSource: ds,+ validateOnly: true,+ });+ return ok();+ } catch (err) {+ return fail(ds.host, err);+ }+ } else {+ try {+ const original = instance!.dataSources.find(+ (d) => d.id === editingDS.id+ );+ if (!original) throw new Error("should never reach this line");+ const updateMask = calcDataSourceUpdateMask(+ ds,+ original,+ editingDS+ );+ await instanceStore.updateDataSource({+ instance: instance!.name,+ dataSource: ds,+ updateMask,+ validateOnly: true,+ });+ return ok();+ } catch (err) {+ return fail(ds.host, err);+ }+ }+ }+ },+ [+ isCreating,+ basicInfo,+ instance,+ instanceStore,+ extractDataSourceFromEdit,+ t,+ ]+ );++ const valueChanged = useMemo(() => {+ if (instance?.state === State.DELETED) return false;+ const original = {+ basicInfo: extractBasicInfo(instance),+ dataSources: extractDataSourceEditState(instance).dataSources,+ };+ const currentLabels = convertKVListToLabels(labelKVList, false);+ const editing = {+ basicInfo: { ...basicInfo, labels: currentLabels },+ dataSources: dataSourceEditState.dataSources,+ };+ return !isEqual(editing, original);+ }, [instance, basicInfo, labelKVList, dataSourceEditState.dataSources]);++ const isEditing = valueChanged && allowEdit;++ const value: InstanceFormContextValue = useMemo(+ () => ({+ instance,+ hideAdvancedFeatures,+ state,+ setState,+ specs,+ isCreating,+ allowEdit,+ allowCreate,+ environment,+ basicInfo,+ setBasicInfo,+ labelKVList,+ setLabelKVList,+ dataSourceEditState,+ setDataSourceEditState,+ adminDataSource,+ editingDataSource,+ readonlyDataSourceList,+ hasReadOnlyDataSource,+ hasReadonlyReplicaFeature,+ missingFeature,+ setMissingFeature,+ resourceIdValidated,+ setResourceIdValidated,+ labelErrors,+ setLabelErrors,+ checkDataSource,+ resetDataSource,+ extractDataSourceFromEdit,+ testConnection,+ pendingCreateInstance,+ valueChanged,+ isEditing,+ onDismiss,+ showConnectionOptionsEvent,+ emitShowConnectionOptions,+ }),+ [+ instance,+ hideAdvancedFeatures,+ state,+ specs,+ isCreating,+ allowEdit,+ allowCreate,+ environment,+ basicInfo,+ labelKVList,+ dataSourceEditState,+ adminDataSource,+ editingDataSource,+ readonlyDataSourceList,+ hasReadOnlyDataSource,+ hasReadonlyReplicaFeature,+ missingFeature,+ resourceIdValidated,+ labelErrors,+ checkDataSource,+ resetDataSource,+ extractDataSourceFromEdit,+ testConnection,+ pendingCreateInstance,+ valueChanged,+ isEditing,+ onDismiss,+ showConnectionOptionsEvent,+ emitShowConnectionOptions,+ ]+ );++ return (+ <InstanceFormCtx.Provider value={value}>+ {children}+ </InstanceFormCtx.Provider>+ );+}diff --git a/frontend/src/react/components/instance/InstanceRoleTable.tsx b/frontend/src/react/components/instance/InstanceRoleTable.tsxnew file mode 100644index 0000000000..a342964f76--- /dev/null+++ b/frontend/src/react/components/instance/InstanceRoleTable.tsx@@ -0,0 +1,53 @@+import { useTranslation } from "react-i18next";+import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";++interface InstanceRoleTableProps {+ instanceRoleList: InstanceRole[];+}++export function InstanceRoleTable({+ instanceRoleList,+}: InstanceRoleTableProps) {+ const { t } = useTranslation();++ return (+ <table className="w-full text-sm border border-block-border rounded-md">+ <thead>+ <tr className="bg-gray-50 border-b border-block-border">+ <th className="text-left px-4 py-2 w-[200px] font-medium">+ {t("common.user")}+ </th>+ <th className="text-left px-4 py-2 font-medium">+ {t("instance.grants")}+ </th>+ </tr>+ </thead>+ <tbody>+ {instanceRoleList.length === 0 ? (+ <tr>+ <td+ colSpan={2}+ className="px-4 py-8 text-center text-control-light"+ >+ {t("common.no-data")}+ </td>+ </tr>+ ) : (+ instanceRoleList.map((role, index) => (+ <tr+ key={role.roleName}+ className={index % 2 === 1 ? "bg-gray-50/50" : ""}+ >+ <td className="px-4 py-2 border-b border-block-border">+ {role.roleName}+ </td>+ <td className="px-4 py-2 border-b border-block-border whitespace-pre-wrap break-all">+ {(role.attribute ?? "").replaceAll("\n", "\n\n")}+ </td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ );+}diff --git a/frontend/src/react/components/instance/InstanceSyncButton.tsx b/frontend/src/react/components/instance/InstanceSyncButton.tsxnew file mode 100644index 0000000000..d1dce84189--- /dev/null+++ b/frontend/src/react/components/instance/InstanceSyncButton.tsx@@ -0,0 +1,156 @@+import { ChevronDown } from "lucide-react";+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { pushNotification, useDatabaseV1Store } from "@/store";+import { SyncStatus } from "@/types/proto-es/v1/database_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";++interface InstanceSyncButtonProps {+ type?: "default" | "primary";+ size?: "small" | "medium";+ disabled?: boolean;+ instanceName?: string;+ instanceTitle?: string;+ onSyncSchema: (enableFullSync: boolean) => void;+}++export function InstanceSyncButton({+ disabled = false,+ instanceName = "",+ instanceTitle = "",+ onSyncSchema,+}: InstanceSyncButtonProps) {+ const { t } = useTranslation();+ const [syncing, setSyncing] = useState(false);+ const [open, setOpen] = useState(false);++ const hasPermission = hasWorkspacePermissionV2("bb.instances.sync");++ const syncSchema = useCallback(+ async (option: "sync-all" | "sync-new") => {+ setOpen(false);+ try {+ setSyncing(true);+ const displayName = instanceTitle || instanceName || "";+ if (displayName) {+ pushNotification({+ module: "bytebase",+ style: "INFO",+ title: t("db.syncing-databases-for-instance", { 0: displayName }),+ });+ } else {+ pushNotification({+ module: "bytebase",+ style: "INFO",+ title: t("db.start-to-sync-schema"),+ });+ }++ onSyncSchema(option === "sync-all");++ if (instanceName) {+ const displayName = instanceTitle || instanceName;+ let notificationShown = false;++ const checkSyncStatus = async () => {+ const databaseStore = useDatabaseV1Store();+ const { databases } = await databaseStore.fetchDatabases({+ parent: instanceName,+ pageSize: 1000,+ silent: true,+ });+ const stillSyncing = databases.filter(+ (db) => db.syncStatus === SyncStatus.SYNC_STATUS_UNSPECIFIED+ );+ const failed = databases.filter(+ (db) => db.syncStatus === SyncStatus.FAILED+ );+ if (stillSyncing.length > 0) return "syncing";+ if (failed.length > 0) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("db.n-databases-had-sync-errors", {+ 0: failed.length,+ }),+ });+ } else {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("database.sync-complete-for-instance", {+ 0: displayName,+ }),+ });+ }+ notificationShown = true;+ return "complete";+ };++ setTimeout(async () => {+ try {+ await checkSyncStatus();+ } catch {+ /* retry at 30s */+ }+ }, 15000);++ setTimeout(async () => {+ if (notificationShown) return;+ try {+ await checkSyncStatus();+ } catch {+ /* user can check database list */+ }+ }, 30000);+ }+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("db.failed-to-sync-schema"),+ description: (error as Error).message,+ });+ } finally {+ setSyncing(false);+ }+ },+ [instanceName, instanceTitle, onSyncSchema, t]+ );++ return (+ <div className="relative">+ <Button+ variant="outline"+ disabled={!hasPermission || disabled || syncing}+ onClick={() => setOpen(!open)}+ >+ {syncing ? t("instance.syncing") : t("instance.sync.self")}+ <ChevronDown className="ml-1 w-4 h-4" />+ </Button>+ {open && (+ <>+ <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />+ <div className="absolute left-0 top-full mt-1 z-50 min-w-[140px] rounded-md border bg-white shadow-md py-1">+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-100"+ title={t("instance.sync.sync-all-tip")}+ onClick={() => syncSchema("sync-all")}+ >+ {t("instance.sync.sync-all")}+ </button>+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-100"+ onClick={() => syncSchema("sync-new")}+ >+ {t("instance.sync.sync-new")}+ </button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/react/components/instance/SshConnectionForm.tsx b/frontend/src/react/components/instance/SshConnectionForm.tsxnew file mode 100644index 0000000000..e51d78d4b7--- /dev/null+++ b/frontend/src/react/components/instance/SshConnectionForm.tsx@@ -0,0 +1,203 @@+import { type DragEvent, useCallback, useEffect, useId, useState } from "react";+import { useTranslation } from "react-i18next";+import { Input } from "@/react/components/ui/input";+import type { Instance } from "@/types/proto-es/v1/instance_service_pb";++const SSH_TYPES = ["NONE", "TUNNEL+PK"] as const;+type SshType = (typeof SSH_TYPES)[number];++interface SshValue {+ sshHost: string;+ sshPort: string;+ sshUser: string;+ sshPassword: string;+ sshPrivateKey: string;+}++interface SshConnectionFormProps {+ value: SshValue;+ instance?: Instance;+ disabled?: boolean;+ onChange: (value: Partial<SshValue>) => void;+}++function guessSshType(value: Partial<SshValue>): SshType {+ if (value.sshPort) {+ return "TUNNEL+PK";+ }+ return "NONE";+}++export function SshConnectionForm({+ value,+ instance: _instance,+ disabled = false,+ onChange,+}: SshConnectionFormProps) {+ const { t } = useTranslation();+ const radioGroupId = useId();+ const [sshType, setSshType] = useState<SshType>(() => guessSshType(value));++ // Sync type from props when value changes externally.+ useEffect(() => {+ setSshType(guessSshType(value));+ }, [value]);++ const handleSelectType = useCallback(+ (type: SshType) => {+ setSshType(type);+ if (type === "NONE") {+ onChange({+ sshHost: "",+ sshPort: "",+ sshUser: "",+ sshPassword: "",+ sshPrivateKey: "",+ });+ }+ },+ [onChange]+ );++ const getSshTypeLabel = (type: SshType): string => {+ if (type === "TUNNEL+PK") {+ return t("data-source.ssh-type.tunnel-and-private-key");+ }+ return t("data-source.ssh-type.none");+ };++ const handleDrop = useCallback(+ (e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ const file = e.dataTransfer.files[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ if (typeof reader.result === "string") {+ onChange({ sshPrivateKey: reader.result });+ }+ };+ reader.readAsText(file);+ },+ [onChange]+ );++ const handleDragOver = useCallback((e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ }, []);++ return (+ <>+ {/* SSH type radio buttons */}+ <div className="flex flex-row items-center gap-x-4 mt-2">+ {SSH_TYPES.map((type) => {+ const id = `${radioGroupId}-${type}`;+ return (+ <label+ key={type}+ htmlFor={id}+ className="flex items-center gap-x-1.5 cursor-pointer text-sm text-main"+ >+ <input+ id={id}+ type="radio"+ name={radioGroupId}+ value={type}+ checked={sshType === type}+ disabled={disabled}+ onChange={() => handleSelectType(type)}+ className="accent-accent"+ />+ {getSshTypeLabel(type)}+ </label>+ );+ })}+ </div>++ {sshType !== "NONE" && (+ <>+ {/* Host and Port */}+ <div className="sm:col-span-1 sm:col-start-1 mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ <div className="sm:col-span-3 sm:col-start-1">+ <label htmlFor="sshHost" className="textlabel block">+ {t("data-source.ssh.host")}+ </label>+ <Input+ id="sshHost"+ className="mt-2 w-full"+ value={value.sshHost}+ disabled={disabled}+ onChange={(e) => onChange({ sshHost: e.target.value })}+ />+ </div>+ <div className="sm:col-span-1">+ <label htmlFor="sshPort" className="textlabel block">+ {t("data-source.ssh.port")}+ </label>+ <Input+ id="sshPort"+ className="mt-2 w-full"+ value={value.sshPort}+ disabled={disabled}+ onChange={(e) => {+ const val = e.target.value;+ if (val === "" || /^\d+$/.test(val)) {+ onChange({ sshPort: val });+ }+ }}+ />+ </div>+ </div>++ {/* User and Password */}+ <div className="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3">+ <div className="mt-2 sm:col-span-3 sm:col-start-1">+ <label htmlFor="sshUser" className="textlabel block">+ {t("data-source.ssh.user")}+ </label>+ <Input+ id="sshUser"+ className="mt-2 w-full"+ value={value.sshUser}+ disabled={disabled}+ onChange={(e) => onChange({ sshUser: e.target.value })}+ />+ </div>+ <div className="mt-2 sm:col-span-3 sm:col-start-1">+ <label htmlFor="sshPassword" className="textlabel block">+ {t("data-source.ssh.password")}+ </label>+ <Input+ id="sshPassword"+ className="mt-2 w-full"+ placeholder={t("instance.password-write-only")}+ value={value.sshPassword}+ disabled={disabled}+ onChange={(e) => onChange({ sshPassword: e.target.value })}+ />+ </div>+ </div>++ {/* Private Key textarea with drag-and-drop */}+ <div className="mt-4 sm:col-span-3 sm:col-start-1">+ <div className="mt-2 sm:col-span-1 sm:col-start-1 flex flex-col">+ <label htmlFor="sshPrivateKey" className="textlabel block">+ {t("data-source.ssh.ssh-key")} ({t("common.optional")})+ </label>+ <textarea+ id="sshPrivateKey"+ className="w-full h-24 mt-2 whitespace-pre-wrap rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm text-main transition-colors placeholder:text-control-placeholder focus:outline-hidden focus:ring-2 focus:ring-accent focus:border-accent disabled:cursor-not-allowed disabled:bg-control-bg disabled:opacity-50 resize-none"+ value={value.sshPrivateKey}+ disabled={disabled}+ placeholder={t("common.sensitive-placeholder")}+ onDrop={handleDrop}+ onDragOver={handleDragOver}+ onChange={(e) => onChange({ sshPrivateKey: e.target.value })}+ />+ </div>+ </div>+ </>+ )}+ </>+ );+}diff --git a/frontend/src/react/components/instance/SslCertificateForm.tsx b/frontend/src/react/components/instance/SslCertificateForm.tsxnew file mode 100644index 0000000000..999a2dcf7b--- /dev/null+++ b/frontend/src/react/components/instance/SslCertificateForm.tsx@@ -0,0 +1,173 @@+import { Info } from "lucide-react";+import { type DragEvent, useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Switch } from "@/react/components/ui/switch";+import {+ Tabs,+ TabsList,+ TabsPanel,+ TabsTrigger,+} from "@/react/components/ui/tabs";+import { Tooltip } from "@/react/components/ui/tooltip";+import { Engine } from "@/types/proto-es/v1/common_pb";++interface SslCertificateFormProps {+ useSsl?: boolean;+ onUseSslChange?: (val: boolean) => void;+ ca?: string;+ onCaChange?: (val: string) => void;+ cert?: string;+ onCertChange?: (val: string) => void;+ sslKey?: string;+ onKeyChange?: (val: string) => void;+ disabled?: boolean;+ showVerify?: boolean;+ showKeyAndCert?: boolean;+ verifyLabel?: string;+ caLabel?: string;+ certLabel?: string;+ keyLabel?: string;+ showTooltip?: boolean;+ verify?: boolean;+ onVerifyChange?: (val: boolean) => void;+ engineType?: Engine;+}++function DroppableTextarea({+ value,+ onChange,+ disabled,+ placeholder,+}: {+ value: string;+ onChange: (val: string) => void;+ disabled?: boolean;+ placeholder: string;+}) {+ const handleDrop = useCallback(+ (e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ const file = e.dataTransfer.files[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ if (typeof reader.result === "string") {+ onChange(reader.result);+ }+ };+ reader.readAsText(file);+ },+ [onChange]+ );++ const handleDragOver = useCallback((e: DragEvent<HTMLTextAreaElement>) => {+ e.preventDefault();+ }, []);++ return (+ <textarea+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onDrop={handleDrop}+ onDragOver={handleDragOver}+ disabled={disabled}+ placeholder={placeholder}+ className="w-full h-24 whitespace-pre-wrap resize-none rounded border border-control-border bg-white px-3 py-2 text-sm focus:outline-hidden focus:ring-2 focus:ring-accent disabled:cursor-not-allowed disabled:opacity-50"+ />+ );+}++export function SslCertificateForm({+ ca = "",+ onCaChange,+ cert = "",+ onCertChange,+ sslKey = "",+ onKeyChange,+ disabled = false,+ showVerify = true,+ showKeyAndCert = false,+ verifyLabel,+ caLabel,+ certLabel,+ keyLabel,+ showTooltip = true,+ verify = false,+ onVerifyChange,+ engineType = Engine.ENGINE_UNSPECIFIED,+}: SslCertificateFormProps) {+ const { t } = useTranslation();++ const resolvedVerifyLabel =+ verifyLabel ?? t("data-source.ssl.verify-certificate");+ const resolvedCaLabel = caLabel ?? t("data-source.ssl.ca-cert");+ const resolvedCertLabel = certLabel ?? t("data-source.ssl.client-cert");+ const resolvedKeyLabel = keyLabel ?? t("data-source.ssl.client-key");++ const hasSSLKeyField = showKeyAndCert || ![Engine.MSSQL].includes(engineType);+ const hasSSLCertField =+ showKeyAndCert || ![Engine.MSSQL].includes(engineType);++ return (+ <div className="mt-2 flex flex-col gap-y-1">+ {showVerify && (+ <div className="flex flex-row items-center gap-x-1">+ <Switch+ checked={verify}+ onCheckedChange={(val) => onVerifyChange?.(val)}+ disabled={disabled}+ />+ <label className="textlabel block">{resolvedVerifyLabel}</label>+ {showTooltip && (+ <Tooltip+ content={t("data-source.ssl.verify-certificate-tooltip")}+ side="right"+ >+ <Info className="w-4 h-4 text-yellow-600" />+ </Tooltip>+ )}+ </div>+ )}++ <Tabs defaultValue="CA">+ <TabsList>+ <TabsTrigger value="CA">{resolvedCaLabel}</TabsTrigger>+ {hasSSLKeyField && (+ <TabsTrigger value="KEY">{resolvedKeyLabel}</TabsTrigger>+ )}+ {hasSSLCertField && (+ <TabsTrigger value="CERT">{resolvedCertLabel}</TabsTrigger>+ )}+ </TabsList>+ <TabsPanel value="CA" className="pt-1">+ <DroppableTextarea+ value={ca}+ onChange={(val) => onCaChange?.(val)}+ disabled={disabled}+ placeholder="Input or drag and drop YOUR_CA_CERTIFICATE"+ />+ </TabsPanel>+ {hasSSLKeyField && (+ <TabsPanel value="KEY" className="pt-1">+ <DroppableTextarea+ value={sslKey}+ onChange={(val) => onKeyChange?.(val)}+ disabled={disabled}+ placeholder="Input or drag and drop YOUR_CLIENT_KEY"+ />+ </TabsPanel>+ )}+ {hasSSLCertField && (+ <TabsPanel value="CERT" className="pt-1">+ <DroppableTextarea+ value={cert}+ onChange={(val) => onCertChange?.(val)}+ disabled={disabled}+ placeholder="Input or drag and drop YOUR_CLIENT_CERT"+ />+ </TabsPanel>+ )}+ </Tabs>+ </div>+ );+}diff --git a/frontend/src/components/InstanceForm/common.ts b/frontend/src/react/components/instance/common.tssimilarity index 90%rename from frontend/src/components/InstanceForm/common.tsrename to frontend/src/react/components/instance/common.tsindex c5aec7d9d9..d7b1881871 100644--- a/frontend/src/components/InstanceForm/common.ts+++ b/frontend/src/react/components/instance/common.ts@@ -95,29 +95,21 @@ export const wrapEditDataSource = (ds: DataSource | undefined) => {};};-/**- * Applies the extra connection parameters from an EditDataSource to a DataSource object- * This ensures that the extraConnectionParameters are properly handled as plain objects- */export const applyExtraConnectionParameters = (dataSource: DataSource,editState: EditDataSource): DataSource => {- // Make sure dataSource has the correct extraConnectionParametersif (editState.extraConnectionParameters) {- // Clone the map manually to ensure it's a plain object, not a Proxyconst params: Record<string, string> = {};Object.entries(editState.extraConnectionParameters).forEach(([key, value]) => {params[key] = value;});-dataSource.extraConnectionParameters = params;} else {dataSource.extraConnectionParameters = {};}-return dataSource;};@@ -131,8 +123,6 @@ export const calcDataSourceUpdateMask = ();const { useEmptyPassword, updateSsl } = editState;if (useEmptyPassword) {- // We need to implicitly set "password" need to be updated- // if the "use empty password" option if checkedediting.password = "";updateMask.add("password");}diff --git a/frontend/src/react/components/instance/constants.ts b/frontend/src/react/components/instance/constants.tsnew file mode 100644index 0000000000..fde5733775--- /dev/null+++ b/frontend/src/react/components/instance/constants.ts@@ -0,0 +1,109 @@+import { Engine } from "@/types/proto-es/v1/common_pb";+import { supportedEngineV1List } from "@/utils";++export const defaultPortForEngine = (engine: Engine) => {+ switch (engine) {+ case Engine.CLICKHOUSE:+ return "9000";+ case Engine.MYSQL:+ return "3306";+ case Engine.POSTGRES:+ return "5432";+ case Engine.SNOWFLAKE:+ return "";+ case Engine.SQLITE:+ return "";+ case Engine.TIDB:+ return "4000";+ case Engine.MONGODB:+ return "27017";+ case Engine.REDIS:+ return "6379";+ case Engine.ORACLE:+ return "1521";+ case Engine.SPANNER:+ return "";+ case Engine.MSSQL:+ return "1433";+ case Engine.REDSHIFT:+ return "5439";+ case Engine.MARIADB:+ return "3306";+ case Engine.OCEANBASE:+ return "2883";+ case Engine.STARROCKS:+ return "9030";+ case Engine.DORIS:+ return "9030";+ case Engine.HIVE:+ return "10000";+ case Engine.ELASTICSEARCH:+ return "9200";+ case Engine.BIGQUERY:+ return "";+ case Engine.DYNAMODB:+ return "";+ case Engine.DATABRICKS:+ return "";+ case Engine.COCKROACHDB:+ return "26257";+ case Engine.COSMOSDB:+ return "";+ case Engine.CASSANDRA:+ return "9042";+ case Engine.TRINO:+ return "8080";+ }+ throw new Error("engine port unknown");+};++export const getEngineList = () => supportedEngineV1List();++export const MongoDBConnectionStringSchemaList = [+ "mongodb://",+ "mongodb+srv://",+];++export const RedisConnectionType = ["Standalone", "Sentinel", "Cluster"];++export const EngineIconPath: Record<string, string> = {+ [Engine.MYSQL]: new URL("@/assets/db/mysql.png", import.meta.url).href,+ [Engine.POSTGRES]: new URL("@/assets/db/postgres.png", import.meta.url).href,+ [Engine.TIDB]: new URL("@/assets/db/tidb.png", import.meta.url).href,+ [Engine.SNOWFLAKE]: new URL("@/assets/db/snowflake.png", import.meta.url)+ .href,+ [Engine.CLICKHOUSE]: new URL("@/assets/db/clickhouse.png", import.meta.url)+ .href,+ [Engine.MONGODB]: new URL("@/assets/db/mongodb.png", import.meta.url).href,+ [Engine.SPANNER]: new URL("@/assets/db/spanner.png", import.meta.url).href,+ [Engine.REDIS]: new URL("@/assets/db/redis.png", import.meta.url).href,+ [Engine.ORACLE]: new URL("@/assets/db/oracle.svg", import.meta.url).href,+ [Engine.MSSQL]: new URL("@/assets/db/mssql.svg", import.meta.url).href,+ [Engine.REDSHIFT]: new URL("@/assets/db/redshift.svg", import.meta.url).href,+ [Engine.MARIADB]: new URL("@/assets/db/mariadb.png", import.meta.url).href,+ [Engine.OCEANBASE]: new URL(+ "@/assets/db/oceanbase-mysql.svg",+ import.meta.url+ ).href,+ [Engine.STARROCKS]: new URL("@/assets/db/starrocks.png", import.meta.url)+ .href,+ [Engine.DORIS]: new URL("@/assets/db/doris.png", import.meta.url).href,+ [Engine.HIVE]: new URL("@/assets/db/hive.svg", import.meta.url).href,+ [Engine.ELASTICSEARCH]: new URL(+ "@/assets/db/elasticsearch.svg",+ import.meta.url+ ).href,+ [Engine.BIGQUERY]: new URL("@/assets/db/bigquery.svg", import.meta.url).href,+ [Engine.DYNAMODB]: new URL("@/assets/db/dynamodb.svg", import.meta.url).href,+ [Engine.DATABRICKS]: new URL("@/assets/db/databricks.svg", import.meta.url)+ .href,+ [Engine.COCKROACHDB]: new URL("@/assets/db/cockroachdb.png", import.meta.url)+ .href,+ [Engine.COSMOSDB]: new URL("@/assets/db/cosmosdb.svg", import.meta.url).href,+ [Engine.CASSANDRA]: new URL("@/assets/db/cassandra.svg", import.meta.url)+ .href,+ [Engine.TRINO]: new URL("@/assets/db/trino.svg", import.meta.url).href,+};++export const SnowflakeExtraLinkPlaceHolder =+ "https://us-west-1.console.aws.amazon.com/rds/home?region=us-west-1#database:id=mysql-instance-foo;is-cluster=false";diff --git a/frontend/src/react/components/instance/index.tsx b/frontend/src/react/components/instance/index.tsxnew file mode 100644index 0000000000..6c321c87a0--- /dev/null+++ b/frontend/src/react/components/instance/index.tsx@@ -0,0 +1,18 @@+export { CreateDataSourceExample } from "./CreateDataSourceExample";+export { CredentialSourceForm } from "./CredentialSourceForm";+export type { BasicInfo, DataSourceEditState, EditDataSource } from "./common";+export { DataSourceForm } from "./DataSourceForm";+export { DataSourceSection } from "./DataSourceSection";+export { InfoPanel, InfoPanelContent } from "./InfoPanel";+export { InstanceActionDropdown } from "./InstanceActionDropdown";+export { InstanceFormBody } from "./InstanceFormBody";+export { InstanceFormButtons } from "./InstanceFormButtons";+export {+ InstanceFormProvider,+ useInstanceFormContext,+} from "./InstanceFormContext";+export { InstanceRoleTable } from "./InstanceRoleTable";+export { InstanceSyncButton } from "./InstanceSyncButton";+export type { InfoSection } from "./info-content";+export { SshConnectionForm } from "./SshConnectionForm";+export { SslCertificateForm } from "./SslCertificateForm";diff --git a/frontend/src/components/InstanceForm/info-content.ts b/frontend/src/react/components/instance/info-content.tssimilarity index 100%rename from frontend/src/components/InstanceForm/info-content.tsrename to frontend/src/react/components/instance/info-content.tsdiff --git a/frontend/src/react/components/instance/specs.ts b/frontend/src/react/components/instance/specs.tsnew file mode 100644index 0000000000..67f8918103--- /dev/null+++ b/frontend/src/react/components/instance/specs.ts@@ -0,0 +1,81 @@+import { useMemo } from "react";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";+import {+ instanceV1HasExtraParameters,+ instanceV1HasSSH,+ instanceV1HasSSL,+} from "@/utils";+import type { BasicInfo, EditDataSource } from "./common";+import { defaultPortForEngine } from "./constants";++export interface InstanceSpecs {+ showDatabase: boolean;+ showSSL: boolean;+ showSSH: boolean;+ isEngineBeta: (engine: Engine) => boolean;+ defaultPort: string;+ instanceLink: string;+ allowEditPort: boolean;+ allowUsingEmptyPassword: boolean;+ showAuthenticationDatabase: boolean;+ hasReadonlyReplicaHost: boolean;+ hasReadonlyReplicaPort: boolean;+ hasExtraParameters: boolean;+}++export const useInstanceSpecs = (+ basicInfo: BasicInfo,+ adminDataSource: EditDataSource,+ editingDataSource: EditDataSource | undefined+): InstanceSpecs => {+ return useMemo(() => {+ const showDatabase =+ (basicInfo.engine === Engine.POSTGRES ||+ basicInfo.engine === Engine.REDSHIFT ||+ basicInfo.engine === Engine.COCKROACHDB ||+ basicInfo.engine === Engine.MSSQL) &&+ editingDataSource?.type === DataSourceType.ADMIN;++ const showSSL = instanceV1HasSSL(basicInfo.engine);+ const showSSH = instanceV1HasSSH(basicInfo.engine);++ const isEngineBeta = (_engine: Engine): boolean => false;++ const defaultPort = defaultPortForEngine(basicInfo.engine);++ let instanceLink = basicInfo.externalLink ?? "";+ if (basicInfo.engine === Engine.SNOWFLAKE) {+ if (adminDataSource.host) {+ instanceLink = `https://${+ adminDataSource.host.split("@")[0]+ }.snowflakecomputing.com/console`;+ }+ }++ const allowEditPort = !(+ basicInfo.engine === Engine.MONGODB && editingDataSource?.srv+ );++ const allowUsingEmptyPassword = basicInfo.engine !== Engine.SPANNER;+ const showAuthenticationDatabase = basicInfo.engine === Engine.MONGODB;+ const hasReadonlyReplicaHost = basicInfo.engine !== Engine.SPANNER;+ const hasReadonlyReplicaPort = basicInfo.engine !== Engine.SPANNER;+ const hasExtraParameters = instanceV1HasExtraParameters(basicInfo.engine);++ return {+ showDatabase,+ showSSL,+ showSSH,+ isEngineBeta,+ defaultPort,+ instanceLink,+ allowEditPort,+ allowUsingEmptyPassword,+ showAuthenticationDatabase,+ hasReadonlyReplicaHost,+ hasReadonlyReplicaPort,+ hasExtraParameters,+ };+ }, [basicInfo, adminDataSource, editingDataSource]);+};diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 70e1bbf63c..b17381f02c 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -218,6 +218,47 @@"untitled": "Untitled","you": "you"},+ "common.add": "Add",+ "common.admin": "Admin",+ "common.archive": "Archive",+ "common.archived": "Archived",+ "common.cancel": "Cancel",+ "common.cannot-undo-this-action": "You cannot undo this action",+ "common.confirm-and-update": "Confirm and update",+ "common.continue-anyway": "Continue anyway",+ "common.create": "Create",+ "common.creating": "Creating",+ "common.custom": "Custom",+ "common.database": "Database",+ "common.databases": "Databases",+ "common.default": "default",+ "common.delete": "Delete",+ "common.delete-resource": "Delete {{type}}",+ "common.deleted": "Deleted",+ "common.detailed-guide": "detailed guide",+ "common.edit": "Edit",+ "common.environment": "Environment",+ "common.key": "Key",+ "common.labels": "Labels",+ "common.learn-more": "Learn more",+ "common.loading": "Loading",+ "common.minutes": "Minutes",+ "common.no-data": "No data",+ "common.optional": "Optional",+ "common.overview": "Overview",+ "common.password": "Password",+ "common.project": "Project",+ "common.read-only": "Read-only",+ "common.restore": "Restore",+ "common.sensitive-placeholder": "Sensitive - write only",+ "common.unlimited": "Unlimited",+ "common.updated": "Updated",+ "common.updating": "Updating",+ "common.user": "User",+ "common.username": "Username",+ "common.value": "Value",+ "common.warning": "Warning",+ "common.write-only": "write only","create-db": {"cluster": "Cluster","database-owner-name": "Database owner name",@@ -293,6 +334,36 @@},"self": "Custom Approval"},+ "data-source.additional-node-addresses": "Additional Node Addresses",+ "data-source.connection-string-schema": "Connection String Schema",+ "data-source.connection-type": "Connection Type",+ "data-source.delete-read-only-data-source": "Delete read-only data source",+ "data-source.direct-connection": "Direct Connection",+ "data-source.extra-params.description": "Additional parameters for database connection string",+ "data-source.extra-params.self": "Extra Parameters",+ "data-source.no-read-only-data-source": "No read-only data source",+ "data-source.private-key-passphrase": "Private Key Passphrase",+ "data-source.private-key-passphrase-placeholder": "Leave empty if your private key is not encrypted",+ "data-source.private-key-passphrase-tip": "Optional passphrase for encrypted private keys",+ "data-source.read-replica-host": "Read-replica Host",+ "data-source.read-replica-port": "Read-replica Port",+ "data-source.replica-set": "Replica Set",+ "data-source.snowflake-keypair-tip": "Key-pair authentication",+ "data-source.ssh-connection": "SSH Connection",+ "data-source.ssh-type.none": "None",+ "data-source.ssh-type.tunnel-and-private-key": "Tunnel + Private Key",+ "data-source.ssh.host": "Server",+ "data-source.ssh.password": "Password",+ "data-source.ssh.port": "Port",+ "data-source.ssh.private-key": "Private Key",+ "data-source.ssh.ssh-key": "SSH Key",+ "data-source.ssh.user": "User",+ "data-source.ssl-connection": "SSL Connection",+ "data-source.ssl.ca-cert": "CA Certificate",+ "data-source.ssl.client-cert": "Client Certificate",+ "data-source.ssl.client-key": "Client Key",+ "data-source.ssl.verify-certificate": "Verify TLS certificate",+ "data-source.ssl.verify-certificate-tooltip": "Enable TLS certificate verification for secure connections. Disable only for development or when certificates cannot be properly validated (e.g., self-signed certs, VPN environments). Warning: Disabling verification is insecure","database": {"all": "All databases","change-database": "Change Database",@@ -349,6 +420,9 @@"select": "Select database group","unmatched-database": "Unmatched database"},+ "database.engine": "Engine",+ "database.filter-database": "Filter database",+ "database.sync-complete-for-instance": "Sync complete for instance '{{0}}'","db": {"character-set": "Character set","collation": "Collation",@@ -357,6 +431,11 @@"start-to-sync-schema": "Start to sync schema","successfully-synced-schema": "Successfully synced schema"},+ "db.failed-to-sync-schema": "Failed to sync schema",+ "db.n-databases-had-sync-errors": "{{0}} database(s) had sync errors",+ "db.start-to-sync-schema": "Start to sync schema",+ "db.syncing-databases-for-instance": "Syncing databases for {{0}}...",+ "dynamic.resource.instance": "Instance ID","environment": {"create": "Create Environment","delete": "Delete this environment",@@ -371,6 +450,9 @@"export-center": {"data-export": "Data Export"},+ "export-data": {+ "password-optional": "Encrypt with password (Optional)"+ },"gitops": {"checklist": {"database-group-recommendation": "For databases sharing the same schema, a database group lets you migrate them together in one change. Define the group once and reuse it across migrations without picking individual databases every time.",@@ -450,6 +532,128 @@},"syncing": "Syncing ..."},+ "instance.account-locator": "Account Locator",+ "instance.archive-instance-instance-name": "Archive instance '{{0}}'?",+ "instance.archived-instances-will-not-be-displayed": "Archived instances will not be displayed.",+ "instance.authentication-database": "Authentication Database",+ "instance.connection-info": "Connection info",+ "instance.connection-options": "Connection Options",+ "instance.create-gcp-credentials": "To create credentials, see",+ "instance.database-region": "Database Region",+ "instance.endpoint": "Endpoint",+ "instance.external-id": "External ID",+ "instance.external-id-description": "External ID for additional security when assuming role (optional)",+ "instance.external-id-placeholder": "optional-external-id",+ "instance.external-link": "External Link",+ "instance.external-secret-azure.secret-name": "Secret name",+ "instance.external-secret-azure.secret-name-tips": "The name of the secret stored in Azure Key Vault.",+ "instance.external-secret-azure.vault-url": "Key Vault URL",+ "instance.external-secret-azure.vault-url-tips": "The Key Vault URL should be like \"https://myvault.vault.azure.net/\".",+ "instance.external-secret-gcp.secret-name": "Secret full name",+ "instance.external-secret-gcp.secret-name-tips": "The secret name should be like \"projects/project-id/secrets/secret-id\".",+ "instance.external-secret-vault.vault-auth-type.approle.role-id": "Auth role id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name": "Environment name",+ "instance.external-secret-vault.vault-auth-type.approle.secret-id": "Auth secret id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text": "Plain text",+ "instance.external-secret-vault.vault-auth-type.approle.self": "AppRole",+ "instance.external-secret-vault.vault-auth-type.self": "Auth type",+ "instance.external-secret-vault.vault-auth-type.token.self": "Token",+ "instance.external-secret-vault.vault-secret-engine-name": "Secret engine name",+ "instance.external-secret-vault.vault-secret-engine-tips": "Only support KV v2 engine.",+ "instance.external-secret-vault.vault-secret-key": "Secret key",+ "instance.external-secret-vault.vault-secret-path": "Secret path",+ "instance.external-secret-vault.vault-tls-config": "Vault TLS Configuration (Optional)",+ "instance.external-secret-vault.vault-url": "Vault URL",+ "instance.external-secret.key-name": "Secret key",+ "instance.external-secret.secret-name": "Secret name",+ "instance.failed-to-connect-instance": "Failed to connect instance.",+ "instance.failed-to-connect-instance-localhost": "If you run Bytebase with Docker, please try \"host.docker.internal\" for the host address.",+ "instance.find-gcp-project-id": "To find GCP Project ID, see",+ "instance.find-gcp-project-id-and-instance-id": "To find GCP Project ID and instance ID, see",+ "instance.force-archive-description": "Force to archive. All databases will be unassigned.",+ "instance.grants": "Grants",+ "instance.host-or-socket": "Host or Socket",+ "instance.iam-extension.client-id": "Client ID",+ "instance.iam-extension.client-secret": "Client Secret",+ "instance.iam-extension.credential-source": "Credential Source",+ "instance.iam-extension.saas-default-credential-restriction": "Default credentials are not available in Bytebase Cloud for security. Please provide specific credentials.",+ "instance.iam-extension.specific-credential": "Specific Credential",+ "instance.iam-extension.tenant-id": "Tenant ID",+ "instance.info-panel.no-info": "No additional information available for this engine.",+ "instance.instance-id": "Instance ID",+ "instance.instance-name": "Instance Name",+ "instance.new-instance": "New Instance",+ "instance.no-environment": "This instance has not been bound to the environment",+ "instance.no-extra-params-configured": "No extra connection parameters configured",+ "instance.no-params-yet-add-above": "No parameters configured yet. Add parameters using the form above.",+ "instance.no-password": "No password",+ "instance.parameter-name-placeholder": "Parameter name",+ "instance.parameter-value-placeholder": "Parameter value",+ "instance.password-type.aws-iam": "AWS RDS IAM",+ "instance.password-type.azure-iam": "Azure IAM",+ "instance.password-type.external-secret-aws": "AWS Secrets Manager",+ "instance.password-type.external-secret-azure": "Azure Key Vault",+ "instance.password-type.external-secret-gcp": "GCP Secret Manager",+ "instance.password-type.external-secret-vault": "Vault (KV v2)",+ "instance.password-type.google-iam": "Google Cloud SQL IAM",+ "instance.password-type.password": "Password",+ "instance.password-write-only": "YOUR_DB_PWD - write only",+ "instance.port": "Port",+ "instance.project-id": "Project ID",+ "instance.restore-instance-instance-name-to-normal-state": "Restore instance '{{0}}' to normal state?",+ "instance.role-arn": "Role ARN",+ "instance.role-arn-description": "IAM role to assume for cross-account access. Leave empty for same-account access.",+ "instance.role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "instance.scan-interval.default-never": "Default (never)",+ "instance.scan-interval.description": "Bytebase periodically syncs instance schema and detects anomalies.",+ "instance.scan-interval.min-value": "Min value {{value}} minutes",+ "instance.scan-interval.self": "Scan Interval",+ "instance.section.basic-info": "Basic Info",+ "instance.section.connection": "Connection",+ "instance.sentence.aws-rds.mysql.template": "Below is an example to create user {{user}}@% and grant the user with the needed privileges.",+ "instance.sentence.aws-rds.postgresql.template": "Below is an example to create user '{{user}}' and grant the user with the needed privileges.",+ "instance.sentence.console.snowflake": "The external console URL managing this instance (e.g. AWS RDS console, your in-house DB instance console)",+ "instance.sentence.create-admin-user": "This is the connection user used by Bytebase to perform DDL and DML (non-SELECT) operations.",+ "instance.sentence.create-admin-user-non-sql": "This is the connection user used by Bytebase to perform write and admin operations.",+ "instance.sentence.create-readonly-user": "This is the connection used by Bytebase to perform read-only operations such as SELECT query.",+ "instance.sentence.create-readonly-user-non-sql": "This is the connection used by Bytebase to perform read-only operations.",+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow": "SQL-driven workflow",+ "instance.sentence.create-user-example.clickhouse.template": "Below is an example to create user '{{user}}' with password {{password}} and grant the user with the needed privileges. First you need to enable ClickHouse SQL-driven workflow {{link}} and then run the following query to create the user.",+ "instance.sentence.create-user-example.mysql.template": "Below is an example to create user {{user}}@% with password {{password}} and grant the user with the needed privileges.",+ "instance.sentence.create-user-example.postgresql.template": "Below is an example to create user '{{user}}' with password {{password}} and grant the user with the needed privileges. If the connecting instance is self-hosted, then you can grant SUPERUSER.",+ "instance.sentence.create-user-example.postgresql.warn": "If the connecting instance is managed by the cloud provider, then SUPERUSER is not available and you should create the user via that provider's admin console. The created user will have provider specific semi-SUPERUSER privileges. You should grant Bytebase privileges with 'GRANT role_name TO bytebase;' for all existing roles, otherwise Bytebase may not access existing databases or tables.",+ "instance.sentence.create-user-example.redis.template": "Below is an example to create user {{user}} with password {{password}} and grant the user with the needed privileges.",+ "instance.sentence.create-user-example.snowflake.template": "Below is an example to create user '{{user}}' with password {{password}} for {{warehouse}} and grant the user with the needed privileges.",+ "instance.sentence.firewall-info": "If you use inbound firewall rules for your database instance, please refer to Bytebase Cloud connection instruction.",+ "instance.sentence.google-cloud-sql.instance-name": "Instance Connection Name",+ "instance.sentence.google-cloud-sql.instance-name-tips": "The instance connection name should like {{instance}}.",+ "instance.sentence.google-cloud-sql.mysql.template": "Create a service account named {{user}}, then add it in your Google Cloud SQL as IAM user {{user}}@'%'. Grant this user with the needed privileges.",+ "instance.sentence.google-cloud-sql.postgresql.template": "Create a service account named {{user}}, then add it in your Google Cloud SQL as IAM user {{user}}@project-id.iam. Grant the user with the needed privileges.",+ "instance.sentence.host.none-snowflake": "e.g. host.docker.internal {'|'} host ip {'|'} local socket",+ "instance.sentence.proxy.snowflake": "For proxy server, append {'@'}PROXY_HOST and specify PROXY_PORT in the port",+ "instance.show-how-to-create": "Show how to create",+ "instance.snowflake-web-console": "Snowflake Web Console",+ "instance.successfully-archived-instance": "Successfully archived the instance '{{0}}'.",+ "instance.successfully-connected-instance": "Successfully connected instance.",+ "instance.successfully-created-instance-createdinstance-name": "Successfully created instance '{{0}}'.",+ "instance.successfully-restored-instance": "Successfully restored the instance '{{0}}'.",+ "instance.successfully-updated-instance-instance-name": "Successfully updated instance '{{0}}'.",+ "instance.sync-databases.add-database": "+ Add database, press enter to submit",+ "instance.sync-databases.description": "Only sync selected databases.",+ "instance.sync-databases.search-database": "Search database",+ "instance.sync-databases.self": "Sync Databases",+ "instance.sync-databases.sync-all": "Sync all databases",+ "instance.sync.self": "Sync instance",+ "instance.sync.sync-all": "Sync all databases",+ "instance.sync.sync-all-tip": "Database sync is asynchronous and might take a few seconds to minutes",+ "instance.sync.sync-new": "Only sync new databases",+ "instance.syncing": "Syncing ...",+ "instance.test-connection": "Test Connection",+ "instance.testing-connection": "Testing connection",+ "instance.type-or-paste-credentials-write-only": "Type or paste CREDENTIALS - write only",+ "instance.unable-to-connect": "Bytebase is unable to connect the instance. We recommend you to review the connection info again. But it's OK to ignore this warning for now. You can still fix the connection info from the instance detail page after creation.\n\nError detail: {{0}}",+ "instance.users": "Users",+ "instance.your-snowflake-account-locator": "Your Snowflake account locator","issue": {"advanced-search": {"filter": "Filter"@@ -486,6 +690,12 @@"max-value-length-exceeded": "Value's length cannot exceed {{length}} characters"}},+ "label.add-label": "Add label",+ "label.empty-label-value": "Empty",+ "label.error.key-duplicated": "Duplicated keys",+ "label.error.key-necessary": "Key is required",+ "label.error.max-value-length-exceeded": "Value's length cannot exceed {{length}} characters",+ "label.error.value-necessary": "Value is required","landing": {"changelog-for-version": "Changelog for {{version}}","last-visit": "Last visit",@@ -677,6 +887,7 @@"new-project": "New Project","request-export-data": "Request Export"},+ "quick-action.add-instance": "@:common.add @:common.instance","release": {"releases": "Releases"},@@ -701,6 +912,13 @@"pattern": "The {{resource}} ID can have lowercase letters, digits, or hyphens. It must start with a lowercase letter and end with a letter or number."}},+ "resource-id.cannot-be-changed-later": "It cannot be changed later.",+ "resource-id.description": "The {{resource}} ID is a unique identifier. You cannot change it after created.",+ "resource-id.self": "{{resource}} ID",+ "resource-id.validation.duplicated": "The {{resource}} ID already exists. Please choose another one.",+ "resource-id.validation.empty": "The {{resource}} ID cannot be empty",+ "resource-id.validation.overflow": "The {{resource}} ID is too long. It should have less than 64 characters.",+ "resource-id.validation.pattern": "The {{resource}} ID can have lowercase letters, digits, or hyphens. It must start with a lowercase letter and end with a letter or number.","role": {"custom-roles": {"self": "Custom roles"@@ -731,6 +949,8 @@"search": "Search classification"}},+ "setting.label.key-placeholder": "Label key...",+ "setting.label.value-placeholder": "Label value...","settings": {"general": {"workspace": {@@ -1384,6 +1604,10 @@}}},+ "subscription.instance-assignment.assign-license": "Assign License",+ "subscription.instance-assignment.n-license-remain": "{{n}} remaining",+ "subscription.usage.instance-count.runoutof": "You have run out of your {{total}} instance quota.",+ "subscription.usage.instance-count.title": "Instance count limit","two-factor": {"description": "Two-factor authentication provides an extra layer of security for member accounts. When signing in, you will be required to enter the security code generated by your Authenticator App.","disable": {@@ -1431,8 +1655,5 @@"description": "Copy the code and enter it in your TOTP app manually.","self": "Your two-factor secret"}- },- "export-data": {- "password-optional": "Encrypt with password (Optional)"}}diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex dad7453c39..1294b8ac51 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -218,6 +218,47 @@"webhooks": "Webhooks","you": "tu"},+ "common.add": "Agregar",+ "common.admin": "Admin",+ "common.archive": "Archivo",+ "common.archived": "Archivada",+ "common.cancel": "Cancelar",+ "common.cannot-undo-this-action": "No se puede deshacer esta acción",+ "common.confirm-and-update": "Confirmar y actualizar",+ "common.continue-anyway": "De todas maneras, continúe",+ "common.create": "Crear",+ "common.creating": "Creando...",+ "common.custom": "Personalizado",+ "common.database": "Base de datos",+ "common.databases": "Bases de datos",+ "common.default": "predeterminado",+ "common.delete": "Eliminar",+ "common.delete-resource": "Delete {{type}}",+ "common.deleted": "Eliminado",+ "common.detailed-guide": "guía detallada",+ "common.edit": "Editar",+ "common.environment": "Entorno",+ "common.key": "Clave",+ "common.labels": "Etiquetas",+ "common.learn-more": "Aprender más",+ "common.loading": "Cargando",+ "common.minutes": "Minutos",+ "common.no-data": "Sin datos",+ "common.optional": "Opcional",+ "common.overview": "Resumen",+ "common.password": "Contraseña",+ "common.project": "Proyecto",+ "common.read-only": "Solo lectura",+ "common.restore": "Restaurar",+ "common.sensitive-placeholder": "Sensible - solo escritura",+ "common.unlimited": "Ilimitado",+ "common.updated": "Actualizado",+ "common.updating": "Actualizando",+ "common.user": "Usuario",+ "common.username": "Nombre de usuario",+ "common.value": "Valor",+ "common.warning": "Advertencia",+ "common.write-only": "solo escritura","create-db": {"cluster": "Clúster","database-owner-name": "Nombre del propietario de la base de datos",@@ -293,6 +334,36 @@},"self": "Aprobación personalizada"},+ "data-source.additional-node-addresses": "Direcciones de nodos adicionales",+ "data-source.connection-string-schema": "Esquema de cadena de conexión",+ "data-source.connection-type": "Tipo de conección",+ "data-source.delete-read-only-data-source": "Eliminar origen de datos de solo lectura",+ "data-source.direct-connection": "Direct Connection",+ "data-source.extra-params.description": "Parámetros adicionales para la cadena de conexión de la base de datos",+ "data-source.extra-params.self": "Parámetros adicionales",+ "data-source.no-read-only-data-source": "Sin fuente de datos de solo lectura",+ "data-source.private-key-passphrase": "Frase de contraseña de clave privada",+ "data-source.private-key-passphrase-placeholder": "Deje vacío si su clave privada no está cifrada",+ "data-source.private-key-passphrase-tip": "Frase de contraseña opcional para claves privadas cifradas",+ "data-source.read-replica-host": "Anfitrión de réplica de lectura",+ "data-source.read-replica-port": "Puerto de réplica de lectura",+ "data-source.replica-set": "Conjunto de réplicas",+ "data-source.snowflake-keypair-tip": "Autenticación de par de claves",+ "data-source.ssh-connection": "Conexión SSH",+ "data-source.ssh-type.none": "Ninguno",+ "data-source.ssh-type.tunnel-and-private-key": "Túnel + Clave Privada",+ "data-source.ssh.host": "Anfitrión",+ "data-source.ssh.password": "Contraseña",+ "data-source.ssh.port": "Puerto",+ "data-source.ssh.private-key": "Clave Privada",+ "data-source.ssh.ssh-key": "Clave del SSH",+ "data-source.ssh.user": "Nombre de usuario",+ "data-source.ssl-connection": "Conexión SSL",+ "data-source.ssl.ca-cert": "Certificado de CA",+ "data-source.ssl.client-cert": "Certificado del cliente",+ "data-source.ssl.client-key": "Clave del cliente",+ "data-source.ssl.verify-certificate": "Verificar certificado TLS",+ "data-source.ssl.verify-certificate-tooltip": "Habilitar la verificación del certificado TLS para conexiones seguras. Deshabilitar solo para desarrollo o cuando los certificados no se pueden validar correctamente (por ejemplo, certificados autofirmados, entornos VPN). Advertencia: Deshabilitar la verificación es inseguro","database": {"all": "Todas las bases de datos","change-database": "Modificar base de datos",@@ -349,6 +420,9 @@"select": "Select database group","unmatched-database": "Unmatched database"},+ "database.engine": "Motor",+ "database.filter-database": "Filtrar base de datos",+ "database.sync-complete-for-instance": "Sincronización completada para la instancia '{{0}}'","db": {"character-set": "Juego de caracteres","collation": "Colación",@@ -357,6 +431,11 @@"start-to-sync-schema": "Comenzar a sincronizar el esquema","successfully-synced-schema": "Esquema sincronizado exitosamente"},+ "db.failed-to-sync-schema": "No se pudo sincronizar el esquema",+ "db.n-databases-had-sync-errors": "{{0}} base(s) de datos tuvieron errores de sincronización",+ "db.start-to-sync-schema": "Comenzar a sincronizar el esquema",+ "db.syncing-databases-for-instance": "Sincronizando bases de datos para {{0}}...",+ "dynamic.resource.instance": "ID de instancia","environment": {"create": "Crear entorno","delete": "Eliminar este entorno",@@ -453,6 +532,128 @@},"syncing": "Sincronizando..."},+ "instance.account-locator": "Localizadora de cuentas",+ "instance.archive-instance-instance-name": "¿Archivar la instancia '{{0}}'?",+ "instance.archived-instances-will-not-be-displayed": "Las instancias archivadas no se mostrarán.",+ "instance.authentication-database": "Base de datos de autenticación",+ "instance.connection-info": "Información de conexión",+ "instance.connection-options": "Opciones de conexión",+ "instance.create-gcp-credentials": "Para crear credenciales, consulte",+ "instance.database-region": "Región de la base de datos",+ "instance.endpoint": "Punto final",+ "instance.external-id": "ID externo",+ "instance.external-id-description": "ID externo para seguridad adicional al asumir el rol (opcional)",+ "instance.external-id-placeholder": "ID externo opcional",+ "instance.external-link": "Enlace externo",+ "instance.external-secret-azure.secret-name": "Nombre del secreto",+ "instance.external-secret-azure.secret-name-tips": "El nombre del secreto almacenado en Azure Key Vault.",+ "instance.external-secret-azure.vault-url": "URL del Key Vault",+ "instance.external-secret-azure.vault-url-tips": "La URL del Key Vault debe ser similar a \"https://myvault.vault.azure.net/\".",+ "instance.external-secret-gcp.secret-name": "nombre completo secreto",+ "instance.external-secret-gcp.secret-name-tips": "El nombre secreto debería ser similar a \"projects/project-id/secrets/secret-id\".",+ "instance.external-secret-vault.vault-auth-type.approle.role-id": "Auth role id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name": "Nombre del entorno",+ "instance.external-secret-vault.vault-auth-type.approle.secret-id": "Auth secret id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text": "Texto sin formato",+ "instance.external-secret-vault.vault-auth-type.approle.self": "AppRole",+ "instance.external-secret-vault.vault-auth-type.self": "Tipo de autenticación",+ "instance.external-secret-vault.vault-auth-type.token.self": "Token",+ "instance.external-secret-vault.vault-secret-engine-name": "Secret engine name",+ "instance.external-secret-vault.vault-secret-engine-tips": "Solo admite motor KV v2.",+ "instance.external-secret-vault.vault-secret-key": "Secret key",+ "instance.external-secret-vault.vault-secret-path": "Secret path",+ "instance.external-secret-vault.vault-tls-config": "Configuración TLS de Vault (opcional)",+ "instance.external-secret-vault.vault-url": "Vault URL",+ "instance.external-secret.key-name": "Clave secreta",+ "instance.external-secret.secret-name": "Nombre secreto",+ "instance.failed-to-connect-instance": "Error al conectar la instancia.",+ "instance.failed-to-connect-instance-localhost": "Si ejecuta Bytebase con Docker, intente \"host.docker.internal\" para la dirección del host.",+ "instance.find-gcp-project-id": "Para encontrar el ID del proyecto de GCP, consulta",+ "instance.find-gcp-project-id-and-instance-id": "Para encontrar el ID de proyecto y el ID de instancia de GCP, consulte",+ "instance.force-archive-description": "Forzar a archivar. Todas las bases de datos quedarán desasignadas.",+ "instance.grants": "Concesiones",+ "instance.host-or-socket": "Host o Socket",+ "instance.iam-extension.client-id": "Client ID",+ "instance.iam-extension.client-secret": "Client Secret",+ "instance.iam-extension.credential-source": "Credential Source",+ "instance.iam-extension.saas-default-credential-restriction": "Las credenciales predeterminadas no están disponibles en Bytebase Cloud por seguridad. Proporcione credenciales específicas.",+ "instance.iam-extension.specific-credential": "Credencial específica",+ "instance.iam-extension.tenant-id": "Tenant ID",+ "instance.info-panel.no-info": "No hay información adicional disponible para este motor.",+ "instance.instance-id": "ID de la instancia",+ "instance.instance-name": "Nombre de la instancia",+ "instance.new-instance": "Nueva instancia",+ "instance.no-environment": "Esta instancia no ha sido ligada al entorno.",+ "instance.no-extra-params-configured": "No hay parámetros de conexión adicionales configurados",+ "instance.no-params-yet-add-above": "No hay parámetros configurados todavía. \nAgregue parámetros usando el formulario anterior.",+ "instance.no-password": "Sin contraseña",+ "instance.parameter-name-placeholder": "Nombre de parámetro",+ "instance.parameter-value-placeholder": "Valor de parámetro",+ "instance.password-type.aws-iam": "AWS RDS IAM",+ "instance.password-type.azure-iam": "Azure IAM",+ "instance.password-type.external-secret-aws": "AWS Secrets Manager",+ "instance.password-type.external-secret-azure": "Azure Key Vault",+ "instance.password-type.external-secret-gcp": "GCP Secret Manager",+ "instance.password-type.external-secret-vault": "Vault (KV v2)",+ "instance.password-type.google-iam": "Google Cloud SQL IAM",+ "instance.password-type.password": "Contraseña",+ "instance.password-write-only": "SU_DB_PWD - solo escritura",+ "instance.port": "Puerto",+ "instance.project-id": "ID del proyecto",+ "instance.restore-instance-instance-name-to-normal-state": "¿Restaurar la instancia '{{0}}' al estado normal?",+ "instance.role-arn": "ARN del rol",+ "instance.role-arn-description": "Rol IAM para asumir en acceso entre cuentas. Dejar vacío para acceso en la misma cuenta.",+ "instance.role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "instance.scan-interval.default-never": "Predeterminado (nunca)",+ "instance.scan-interval.description": "Bytebase sincroniza periódicamente el esquema de instancia y detecta anomalías.",+ "instance.scan-interval.min-value": "Valor mínimo {{value}} minutos",+ "instance.scan-interval.self": "Intervalo de escaneo",+ "instance.section.basic-info": "Información básica",+ "instance.section.connection": "Conexión",+ "instance.sentence.aws-rds.mysql.template": "A continuación se muestra un ejemplo para crear el usuario {{user}}@% y otorgarle los privilegios necesarios.",+ "instance.sentence.aws-rds.postgresql.template": "A continuación se muestra un ejemplo para crear el usuario '{{user}}' y otorgarle los privilegios necesarios.",+ "instance.sentence.console.snowflake": "La URL de la consola externa que administra esta instancia (por ejemplo, la consola de AWS RDS, la consola de la instancia de base de datos interna)",+ "instance.sentence.create-admin-user": "Este es el usuario de conexión utilizado por Bytebase para realizar operaciones DDL y DML (no SELECT).",+ "instance.sentence.create-admin-user-non-sql": "Este es el usuario de conexión utilizado por Bytebase para realizar operaciones de escritura y administración.",+ "instance.sentence.create-readonly-user": "Esta es la conexión utilizada por Bytebase para realizar operaciones de solo lectura como la consulta SELECT.",+ "instance.sentence.create-readonly-user-non-sql": "Esta es la conexión utilizada por Bytebase para realizar operaciones de solo lectura.",+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow": "Flujo de trabajo impulsado por SQL",+ "instance.sentence.create-user-example.clickhouse.template": "A continuación se muestra un ejemplo para crear el usuario '{{user}}' con la contraseña {{password}} y otorgar al usuario los privilegios necesarios. Primero debe habilitar el flujo de trabajo impulsado por SQL de ClickHouse {{link}} y luego ejecutar la siguiente consulta para crear el usuario.",+ "instance.sentence.create-user-example.mysql.template": "A continuación se muestra un ejemplo para crear el usuario {{user}}@% con la contraseña {{password}} y otorgarle al usuario los privilegios necesarios.",+ "instance.sentence.create-user-example.postgresql.template": "A continuación se muestra un ejemplo para crear el usuario '{{user}}' con la contraseña {{password}} y otorgar al usuario los privilegios necesarios. Si la instancia de conexión está alojada por ti mismo, puedes otorgar SUPERUSER.",+ "instance.sentence.create-user-example.postgresql.warn": "Si la instancia de conexión es administrada por el proveedor de la nube, entonces SUPERUSER no está disponible y debes crear el usuario a través de la consola de administración del proveedor. El usuario creado tendrá privilegios semi-SUPERUSER específicos del proveedor. Debes otorgar privilegios de Bytebase con 'GRANT role_name TO bytebase;' para todos los roles existentes, de lo contrario Bytebase puede no tener acceso a las bases de datos o tablas existentes.",+ "instance.sentence.create-user-example.redis.template": "A continuación se muestra un ejemplo para crear el usuario {{user}} con la contraseña {{password}} y otorgar al usuario los privilegios necesarios.",+ "instance.sentence.create-user-example.snowflake.template": "A continuación se muestra un ejemplo para crear el usuario 'bytebase' con la contraseña {{password}} para {{warehouse}} y otorgar al usuario los privilegios necesarios.",+ "instance.sentence.firewall-info": "Si usa reglas de firewall entrante para su instancia de base de datos, consulte la instrucción de conexión de Bytebase Cloud.",+ "instance.sentence.google-cloud-sql.instance-name": "Nombre de conexión de instancia",+ "instance.sentence.google-cloud-sql.instance-name-tips": "El nombre de la conexión de la instancia debería ser {{instance}}.",+ "instance.sentence.google-cloud-sql.mysql.template": "Cree una cuenta de servicio llamada {{user}} y luego agréguela en su Google Cloud SQL como usuario de IAM {{user}}@'%'. Otorgue a este usuario los privilegios necesarios.",+ "instance.sentence.google-cloud-sql.postgresql.template": "Cree una cuenta de servicio llamada {{user}} y luego agréguela en su Google Cloud SQL como usuario de IAM {{user}}@project-id.iam. Otorgue al usuario los privilegios necesarios.",+ "instance.sentence.host.none-snowflake": "por ejemplo, host.docker.internal {'|'} host ip {'|'} local socket",+ "instance.sentence.proxy.snowflake": "Para el servidor proxy, agregue {'@'}PROXY_HOST y especifique PROXY_PORT en el puerto",+ "instance.show-how-to-create": "Mostrar cómo crear",+ "instance.snowflake-web-console": "Consola web de Snowflake",+ "instance.successfully-archived-instance": "Se archivó exitosamente la instancia '{{0}}'.",+ "instance.successfully-connected-instance": "Instancia conectada correctamente.",+ "instance.successfully-created-instance-createdinstance-name": "Se ha creado correctamente la instancia '{{0}}'.",+ "instance.successfully-restored-instance": "Se restauró exitosamente la instancia '{{0}}'.",+ "instance.successfully-updated-instance-instance-name": "Se ha actualizado correctamente la instancia '{{0}}'.",+ "instance.sync-databases.add-database": "+ Agregar base de datos, presione enter para enviar",+ "instance.sync-databases.description": "Sincronizar sólo bases de datos seleccionadas.",+ "instance.sync-databases.search-database": "Buscar en la base de datos",+ "instance.sync-databases.self": "Sincronizar bases de datos",+ "instance.sync-databases.sync-all": "Sincronizar todas las bases de datos",+ "instance.sync.self": "Instancia de sincronización",+ "instance.sync.sync-all": "Sincronizar todas las bases de datos",+ "instance.sync.sync-all-tip": "La sincronización de la base de datos es asincrónica y puede tardar entre unos segundos y minutos.",+ "instance.sync.sync-new": "Sincronizar únicamente bases de datos nuevas",+ "instance.syncing": "Sincronizando...",+ "instance.test-connection": "Probar conexión",+ "instance.testing-connection": "Probando conexión",+ "instance.type-or-paste-credentials-write-only": "Escriba o pegue las CREDENCIALES - solo escritura",+ "instance.unable-to-connect": "Bytebase no puede conectar la instancia. Le recomendamos que revise la información de conexión nuevamente. Pero está bien ignorar esta advertencia por ahora. Aún puede solucionar la información de conexión desde la página de detalles de la instancia después de la creación.\n\nDetalle del error: {{0}}",+ "instance.users": "Usuarios",+ "instance.your-snowflake-account-locator": "Su localizador de cuentas Snowflake","issue": {"advanced-search": {"filter": "Filtrar"@@ -489,6 +690,12 @@"max-value-length-exceeded": "La longitud del valor no puede exceder {{length}} caracteres"}},+ "label.add-label": "Agregar etiqueta",+ "label.empty-label-value": "Valor",+ "label.error.key-duplicated": "Claves duplicadas",+ "label.error.key-necessary": "Se requiere una clave",+ "label.error.max-value-length-exceeded": "La longitud del valor no puede exceder {{longitud}} caracteres",+ "label.error.value-necessary": "Se requiere un valor","landing": {"changelog-for-version": "Registro de cambios para {{version}}","last-visit": "Última visita",@@ -680,6 +887,7 @@"new-project": "Nuevo Proyecto","request-export-data": "Solicitar exportación"},+ "quick-action.add-instance": "@:common.add @:common.instance","release": {"releases": "Lanzamientos"},@@ -704,6 +912,13 @@"pattern": "La identificación {{recurso}} puede tener letras, dígitos o guiones minúsculas. Debe comenzar con una letra minúscula y terminar con una letra o número."}},+ "resource-id.cannot-be-changed-later": "No se puede cambiar posteriormente.",+ "resource-id.description": "El ID de {{resource}} es un identificador único. No se puede cambiar una vez creado.",+ "resource-id.self": "ID de {{resource}}",+ "resource-id.validation.duplicated": "El ID de {{resource}} ya existe. Por favor, elige otro.",+ "resource-id.validation.empty": "El ID {{resource}} no puede estar vacío",+ "resource-id.validation.overflow": "El ID de {{resource}} es demasiado largo. Debe tener menos de 64 caracteres.",+ "resource-id.validation.pattern": "La identificación {{recurso}} puede tener letras, dígitos o guiones minúsculas. Debe comenzar con una letra minúscula y terminar con una letra o número.","role": {"custom-roles": {"self": "Roles personalizados"@@ -734,6 +949,8 @@"search": "Clasificación de búsqueda"}},+ "setting.label.key-placeholder": "Clave de etiqueta...",+ "setting.label.value-placeholder": "Valor de etiqueta...","settings": {"general": {"workspace": {@@ -1387,6 +1604,10 @@}}},+ "subscription.instance-assignment.assign-license": "Asignar licencia",+ "subscription.instance-assignment.n-license-remain": "permanecer {{n}}",+ "subscription.usage.instance-count.runoutof": "Te has quedado sin tu cuota de instancias {{total}}.",+ "subscription.usage.instance-count.title": "Límite de cantidad de instancias","two-factor": {"description": "La autenticación de dos factores proporciona una capa adicional de seguridad para las cuentas de los miembros. Al iniciar sesión, se te pedirá que ingreses el código de seguridad generado por tu aplicación de autenticación.","disable": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 9ea17048c3..ce37c5c3dc 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -218,6 +218,47 @@"webhooks": "Webhook","you": "あなた"},+ "common.add": "追加",+ "common.admin": "管理者",+ "common.archive": "アーカイブ",+ "common.archived": "アーカイブ済み",+ "common.cancel": "キャンセル",+ "common.cannot-undo-this-action": "この操作は元に戻せません",+ "common.confirm-and-update": "確認して更新する",+ "common.continue-anyway": "まだ続けたい",+ "common.create": "作成する",+ "common.creating": "作成...",+ "common.custom": "カスタマイズ",+ "common.database": "データベース",+ "common.databases": "データベース",+ "common.default": "デフォルト",+ "common.delete": "消去",+ "common.delete-resource": "Delete {{type}}",+ "common.deleted": "削除されました",+ "common.detailed-guide": "詳細ガイド",+ "common.edit": "編集",+ "common.environment": "環境",+ "common.key": "キー",+ "common.labels": "ラベル",+ "common.learn-more": "もっと詳しく知る",+ "common.loading": "読み込み中",+ "common.minutes": "分",+ "common.no-data": "データなし",+ "common.optional": "オプション",+ "common.overview": "概要",+ "common.password": "パスワード",+ "common.project": "プロジェクト",+ "common.read-only": "読み取り専用",+ "common.restore": "復元する",+ "common.sensitive-placeholder": "機密データ - 書き込みのみ",+ "common.unlimited": "無制限",+ "common.updated": "更新しました",+ "common.updating": "更新中",+ "common.user": "ユーザー",+ "common.username": "ユーザー名",+ "common.value": "値",+ "common.warning": "警告する",+ "common.write-only": "書き込み専用","create-db": {"cluster": "集まる","database-owner-name": "データベース所有者",@@ -293,6 +334,36 @@},"self": "カスタム承認"},+ "data-source.additional-node-addresses": "追加のノードアドレス",+ "data-source.connection-string-schema": "接続文字列モード",+ "data-source.connection-type": "接続タイプ",+ "data-source.delete-read-only-data-source": "読み取り専用データソースを削除する",+ "data-source.direct-connection": "Direct Connection",+ "data-source.extra-params.description": "データベース接続文字列の追加パラメーター",+ "data-source.extra-params.self": "追加のパラメーター",+ "data-source.no-read-only-data-source": "読み取り専用データソースがありません",+ "data-source.private-key-passphrase": "秘密鍵のパスフレーズ",+ "data-source.private-key-passphrase-placeholder": "秘密鍵が暗号化されていない場合は空のままにしてください",+ "data-source.private-key-passphrase-tip": "暗号化された秘密鍵のオプションパスフレーズ",+ "data-source.read-replica-host": "リードレプリカホスト",+ "data-source.read-replica-port": "リードレプリカポート",+ "data-source.replica-set": "レプリカセット",+ "data-source.snowflake-keypair-tip": "キーペア認証",+ "data-source.ssh-connection": "SSH接続",+ "data-source.ssh-type.none": "なし",+ "data-source.ssh-type.tunnel-and-private-key": "トンネル + 秘密鍵",+ "data-source.ssh.host": "サーバ",+ "data-source.ssh.password": "パスワード",+ "data-source.ssh.port": "ポート",+ "data-source.ssh.private-key": "秘密鍵",+ "data-source.ssh.ssh-key": "SSHキー",+ "data-source.ssh.user": "ユーザー名",+ "data-source.ssl-connection": "SSL接続",+ "data-source.ssl.ca-cert": "CA証明書",+ "data-source.ssl.client-cert": "クライアント証明書",+ "data-source.ssl.client-key": "クライアントキー",+ "data-source.ssl.verify-certificate": "TLS証明書を検証",+ "data-source.ssl.verify-certificate-tooltip": "安全な接続のためにTLS証明書の検証を有効にします。開発環境や証明書が適切に検証できない場合(自己署名証明書、VPN環境など)にのみ無効にしてください。警告:検証を無効にすることは安全ではありません","database": {"all": "すべてのデータベース","change-database": "データベースの変更",@@ -349,6 +420,9 @@"select": "Select database group","unmatched-database": "Unmatched database"},+ "database.engine": "エンジン",+ "database.filter-database": "フィルターデータベース",+ "database.sync-complete-for-instance": "インスタンス '{{0}}' の同期が完了しました","db": {"character-set": "文字セット","collation": "照合順序",@@ -357,6 +431,11 @@"start-to-sync-schema": "スキーマの同期を開始します","successfully-synced-schema": "スキーマの同期に成功しました"},+ "db.failed-to-sync-schema": "スキーマの同期に失敗しました",+ "db.n-databases-had-sync-errors": "{{0}} 個のデータベースで同期エラーが発生しました",+ "db.start-to-sync-schema": "スキーマの同期を開始します",+ "db.syncing-databases-for-instance": "{{0}} のデータベースを同期中...",+ "dynamic.resource.instance": "インスタンス ID","environment": {"create": "環境を作成する","delete": "この環境を削除します",@@ -453,6 +532,128 @@},"syncing": "同期中 ..."},+ "instance.account-locator": "アカウントロケーター",+ "instance.archive-instance-instance-name": "インスタンス '{{0}}' をアーカイブしますか?",+ "instance.archived-instances-will-not-be-displayed": "アーカイブされたインスタンスは表示されなくなります。",+ "instance.authentication-database": "認証データベース",+ "instance.connection-info": "接続情報",+ "instance.connection-options": "接続オプション",+ "instance.create-gcp-credentials": "認証情報の作成方法については、を参照してください",+ "instance.database-region": "データベース領域",+ "instance.endpoint": "エンドポイント",+ "instance.external-id": "外部 ID",+ "instance.external-id-description": "ロールを引き受ける際の追加セキュリティ用の外部 ID(オプション)",+ "instance.external-id-placeholder": "オプションの外部 ID",+ "instance.external-link": "外部リンク",+ "instance.external-secret-azure.secret-name": "シークレット名",+ "instance.external-secret-azure.secret-name-tips": "Azure Key Vault に保存されているシークレットの名前。",+ "instance.external-secret-azure.vault-url": "Key Vault URL",+ "instance.external-secret-azure.vault-url-tips": "Key Vault URL は「https://myvault.vault.azure.net/」のような形式である必要があります。",+ "instance.external-secret-gcp.secret-name": "キーのフルパス",+ "instance.external-secret-gcp.secret-name-tips": "キーへのフルパスは、「projects/project-id/secrets/secret-id」のようなものである必要があります。",+ "instance.external-secret-vault.vault-auth-type.approle.role-id": "認証ロールID",+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name": "環境変数名",+ "instance.external-secret-vault.vault-auth-type.approle.secret-id": "認証シークレットID",+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text": "プレーンテキスト",+ "instance.external-secret-vault.vault-auth-type.approle.self": "AppRole",+ "instance.external-secret-vault.vault-auth-type.self": "認証タイプ",+ "instance.external-secret-vault.vault-auth-type.token.self": "トークン",+ "instance.external-secret-vault.vault-secret-engine-name": "シークレットエンジン名",+ "instance.external-secret-vault.vault-secret-engine-tips": "KV v2 ストレージのみをサポートします",+ "instance.external-secret-vault.vault-secret-key": "秘密鍵",+ "instance.external-secret-vault.vault-secret-path": "秘密の道",+ "instance.external-secret-vault.vault-tls-config": "Vault TLS 構成 (オプション)",+ "instance.external-secret-vault.vault-url": "ボールトの URL",+ "instance.external-secret.key-name": "秘密鍵",+ "instance.external-secret.secret-name": "秘密の名前",+ "instance.failed-to-connect-instance": "インスタンスへの接続に失敗しました。",+ "instance.failed-to-connect-instance-localhost": "Docker デプロイメントを使用している場合は、ホスト アドレスとして「host.docker.internal」を使用してみてください。",+ "instance.find-gcp-project-id": "GCP プロジェクト ID とインスタンス ID を表示するには、次を参照してください。",+ "instance.find-gcp-project-id-and-instance-id": "GCP プロジェクト ID の確認方法については、次を参照してください",+ "instance.force-archive-description": "アーカイブを強制します。すべてのデータベースの割り当てが解除されます。",+ "instance.grants": "権限",+ "instance.host-or-socket": "ホストまたはソケット",+ "instance.iam-extension.client-id": "Client ID",+ "instance.iam-extension.client-secret": "Client Secret",+ "instance.iam-extension.credential-source": "Credential Source",+ "instance.iam-extension.saas-default-credential-restriction": "セキュリティ上の理由により、Bytebase Cloud ではデフォルトの認証情報は使用できません。具体的な認証情報を入力してください。",+ "instance.iam-extension.specific-credential": "特定の資格情報",+ "instance.iam-extension.tenant-id": "Tenant ID",+ "instance.info-panel.no-info": "このエンジンの追加情報はありません。",+ "instance.instance-id": "インスタンスID",+ "instance.instance-name": "@:common.instance@:instance.name",+ "instance.new-instance": "新しいインスタンス",+ "instance.no-environment": "このインスタンスは環境にバインドされていません",+ "instance.no-extra-params-configured": "追加の接続パラメーターは構成されていません",+ "instance.no-params-yet-add-above": "まだ構成されていません。\n上記のフォームを使用してパラメーターを追加します。",+ "instance.no-password": "パスワードがありません",+ "instance.parameter-name-placeholder": "パラメーター名",+ "instance.parameter-value-placeholder": "パラメーター値",+ "instance.password-type.aws-iam": "AWS RDS IAM",+ "instance.password-type.azure-iam": "Azure IAM",+ "instance.password-type.external-secret-aws": "AWS シークレットマネージャー",+ "instance.password-type.external-secret-azure": "Azure Key Vault",+ "instance.password-type.external-secret-gcp": "GCP シークレット マネージャー",+ "instance.password-type.external-secret-vault": "ボールト (KV v2)",+ "instance.password-type.google-iam": "Google Cloud SQL IAM",+ "instance.password-type.password": "パスワード",+ "instance.password-write-only": "YOUR_DB_PWD - 書き込み専用",+ "instance.port": "ポート",+ "instance.project-id": "プロジェクトID",+ "instance.restore-instance-instance-name-to-normal-state": "インスタンス '{{0}}' を通常の状態に復元しますか?",+ "instance.role-arn": "ロール ARN",+ "instance.role-arn-description": "クロスアカウントアクセス用の IAM ロール。同一アカウントアクセスの場合は空のままにしてください。",+ "instance.role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "instance.scan-interval.default-never": "デフォルト (なし)",+ "instance.scan-interval.description": "Bytebase は定期的にインスタンスのスキーマを同期し、異常検出を実行します。",+ "instance.scan-interval.min-value": "最短 {{value}} 分",+ "instance.scan-interval.self": "スキャン間隔",+ "instance.section.basic-info": "基本情報",+ "instance.section.connection": "接続",+ "instance.sentence.aws-rds.mysql.template": "以下は、ユーザー {{user}}@% を作成し、そのユーザーに必要な権限を付与する例です。",+ "instance.sentence.aws-rds.postgresql.template": "以下は、ユーザー '{{user}}' を作成し、そのユーザーに必要な権限を付与する例です。",+ "instance.sentence.console.snowflake": "この インスタンス を管理する外部コンソール URL (AWS RDS コンソール、データベース コンソールなど)",+ "instance.sentence.create-admin-user": "これは、データベースに接続し、DDL および DML (非 SELECT) 操作を実行するために Bytebase によって使用されるユーザーです。",+ "instance.sentence.create-admin-user-non-sql": "これは、データベースに接続し、書き込みおよび管理操作を実行するために Bytebase によって使用されるユーザーです。",+ "instance.sentence.create-readonly-user": "これは、データベースに接続し、SELECT などの読み取り専用操作を実行するために Bytebase によって使用されるユーザーです。",+ "instance.sentence.create-readonly-user-non-sql": "これは、データベースに接続して読み取り専用操作を実行するために Bytebase によって使用されるユーザーです。",+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow": "SQLワークフロー",+ "instance.sentence.create-user-example.clickhouse.template": "ユーザー {{user}}、パスワード {{password}} を作成し、必要な権限を付与する例は次のとおりです。次のコマンドを実行してユーザーを作成する前に、{{link}} を有効にする必要があります。",+ "instance.sentence.create-user-example.mysql.template": "ユーザー {{user}}、パスワード {{password}} を作成し、必要な権限を付与する例は次のとおりです。",+ "instance.sentence.create-user-example.postgresql.template": "ユーザー {{user}}、パスワード {{password}} を作成し、必要な権限を付与する例は次のとおりです。接続しているインスタンスが自己ホスト型の場合は、SUPERUSER を付与できます。",+ "instance.sentence.create-user-example.postgresql.warn": "接続しているインスタンスがクラウド サービス プロバイダーによって管理されている場合、SUPERUSER は使用できないため、プロバイダーの管理者コンソールを通じてユーザーを作成する必要があります。作成したユーザーには、ベンダー固有の準 SUPERUSER 権限が与えられます。 「GRANT role_name TO bytebase;」ステートメントを使用して、すべてのロールに Bytebase 権限を付与する必要があります。そうしないと、Bytebase に既存のデータベースまたはテーブルを操作する権限がない可能性があり、操作が失敗します。",+ "instance.sentence.create-user-example.redis.template": "ユーザー {{user}}、パスワード {{password}} を作成し、必要な権限を付与する例は次のとおりです。",+ "instance.sentence.create-user-example.snowflake.template": "ユーザー {{user}}、パスワード {{password}}、ウェアハウス {{warehouse}} を作成し、必要な権限を付与する例は次のとおりです。",+ "instance.sentence.firewall-info": "データベースインスタンスにインバウンドファイアウォールルールを使用する場合は、ByteBase Cloud Connection命令を参照してください。",+ "instance.sentence.google-cloud-sql.instance-name": "インスタンス接続名",+ "instance.sentence.google-cloud-sql.instance-name-tips": "インスタンス接続名は {{instance}} である必要があります。",+ "instance.sentence.google-cloud-sql.mysql.template": "{{user}} という名前のサービス アカウントを作成し、IAM ユーザー {{user}}@'%' として Google Cloud SQL に追加します。このユーザーに必要な権限を付与します。",+ "instance.sentence.google-cloud-sql.postgresql.template": "{{user}} という名前のサービス アカウントを作成し、IAM ユーザー {{user}}@project-id.iam として Google Cloud SQL に追加します。ユーザーに必要な権限を付与します。",+ "instance.sentence.host.none-snowflake": "たとえば、host.docker.internal {'|'} host ip {'|'} local socket",+ "instance.sentence.proxy.snowflake": "プロキシ サーバーの場合は、{'@'}PROXY_HOST を追加し、ポートに PROXY_PORT を指定します。",+ "instance.show-how-to-create": "作成方法",+ "instance.snowflake-web-console": "スノーフレークウェブコンソール",+ "instance.successfully-archived-instance": "インスタンス '{{0}}' を正常にアーカイブしました。",+ "instance.successfully-connected-instance": "インスタンスに正常に接続されました。",+ "instance.successfully-created-instance-createdinstance-name": "インスタンス '{{0}}' が正常に作成されました。",+ "instance.successfully-restored-instance": "インスタンス '{{0}}' を正常に復元しました。",+ "instance.successfully-updated-instance-instance-name": "インスタンス '{{0}}' が正常に更新されました。",+ "instance.sync-databases.add-database": "+ データベースを追加し、Enterキーを押して送信します",+ "instance.sync-databases.description": "選択したデータベースのみを同期します。",+ "instance.sync-databases.search-database": "データベースを検索",+ "instance.sync-databases.self": "データベースを同期する",+ "instance.sync-databases.sync-all": "すべてのデータベースを同期する",+ "instance.sync.self": "インスタンスの同期",+ "instance.sync.sync-all": "すべてのデータベースを同期する",+ "instance.sync.sync-all-tip": "データベースの同期は非同期で、数秒から数分かかる場合があります。",+ "instance.sync.sync-new": "新しいデータベースのみを同期する",+ "instance.syncing": "同期中 ...",+ "instance.test-connection": "テスト接続",+ "instance.testing-connection": "接続をテスト中",+ "instance.type-or-paste-credentials-write-only": "資格情報を入力または貼り付けます - 書き込みのみ",+ "instance.unable-to-connect": "Bytebase はインスタンスに接続できません。接続情報を再度確認することをお勧めします。ただし、今のところこの警告は無視してかまいません。作成後もインスタンスの詳細ページで接続情報を修正できます。\n\nエラーの詳細:{{0}}",+ "instance.users": "ユーザー",+ "instance.your-snowflake-account-locator": "Snowflake アカウント ロケーター","issue": {"advanced-search": {"filter": "フィルター"@@ -489,6 +690,12 @@"max-value-length-exceeded": "値は {{length}} 文字を超えることはできません"}},+ "label.add-label": "タグ付けする",+ "label.empty-label-value": "ヌル",+ "label.error.key-duplicated": "キーが繰り返されました",+ "label.error.key-necessary": "キーを指定する必要があります",+ "label.error.max-value-length-exceeded": "値は {{length}} 文字を超えることはできません",+ "label.error.value-necessary": "値を指定する必要があります","landing": {"changelog-for-version": "{{version}} の変更履歴","last-visit": "最終訪問",@@ -680,6 +887,7 @@"new-project": "作成するプロジェクト","request-export-data": "データ出力を申請する"},+ "quick-action.add-instance": "@:common.instance@:common.add","release": {"releases": "リリース"},@@ -704,6 +912,13 @@"pattern": "{{resource}} ID には、小文字、数字、またはハイフンを持つことができます。\n小文字から始めて、文字または番号で終わる必要があります。"}},+ "resource-id.cannot-be-changed-later": "作成後に変更することはできません。",+ "resource-id.description": "{{resource}} ID は一意の識別子です。作成後に変更することはできません。",+ "resource-id.self": "{{resource}} ID",+ "resource-id.validation.duplicated": "{{resource}} ID はすでに存在します。別のIDを使用してください。",+ "resource-id.validation.empty": "{{resource}} ID は空にできません",+ "resource-id.validation.overflow": "{{resource}} ID は 64 文字未満である必要があります。",+ "resource-id.validation.pattern": "{{resource}} ID には、小文字、数字、またはハイフンを持つことができます。\n小文字から始めて、文字または番号で終わる必要があります。","role": {"custom-roles": {"self": "カスタムロール"@@ -734,6 +949,8 @@"search": "カテゴリを検索する"}},+ "setting.label.key-placeholder": "タグキー...",+ "setting.label.value-placeholder": "タグ値…","settings": {"general": {"workspace": {@@ -1387,6 +1604,10 @@}}},+ "subscription.instance-assignment.assign-license": "ライセンスの割り当て",+ "subscription.instance-assignment.n-license-remain": "残り {{n}}",+ "subscription.usage.instance-count.runoutof": "すべての {{total}} インスタンス クレジットが使用されました。",+ "subscription.usage.instance-count.title": "インスタンスの制限","two-factor": {"description": "2 要素認証は、システム メンバーに追加のセキュリティ層を提供します。ログインするとき、ユーザーは認証アプリケーションによって生成されたセキュリティ コードを入力する必要があります。","disable": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 9e2d3885a2..bf32423901 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -218,6 +218,47 @@"webhooks": "Webhooks","you": "bạn"},+ "common.add": "Thêm",+ "common.admin": "Quản trị viên",+ "common.archive": "Lưu trữ",+ "common.archived": "Đã lưu trữ",+ "common.cancel": "Hủy",+ "common.cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.",+ "common.confirm-and-update": "Xác nhận và Cập nhật",+ "common.continue-anyway": "Tiếp tục",+ "common.create": "Tạo",+ "common.creating": "Đang tạo...",+ "common.custom": "Tùy chỉnh",+ "common.database": "Cơ sở dữ liệu",+ "common.databases": "Cơ sở dữ liệu",+ "common.default": "Mặc định",+ "common.delete": "Xóa",+ "common.delete-resource": "Delete {{type}}",+ "common.deleted": "Đã xóa",+ "common.detailed-guide": "Hướng dẫn chi tiết",+ "common.edit": "Chỉnh sửa",+ "common.environment": "Môi trường",+ "common.key": "Khóa",+ "common.labels": "Nhãn",+ "common.learn-more": "Tìm hiểu thêm",+ "common.loading": "Đang tải",+ "common.minutes": "Phút",+ "common.no-data": "Không có dữ liệu",+ "common.optional": "Tùy chọn",+ "common.overview": "Tổng quan",+ "common.password": "Mật khẩu",+ "common.project": "Dự án",+ "common.read-only": "Chỉ đọc",+ "common.restore": "Khôi phục",+ "common.sensitive-placeholder": "Nhạy cảm - Chỉ ghi",+ "common.unlimited": "Không giới hạn",+ "common.updated": "Đã cập nhật",+ "common.updating": "Đang cập nhật",+ "common.user": "Người dùng",+ "common.username": "Tên người dùng",+ "common.value": "Giá trị",+ "common.warning": "Cảnh báo",+ "common.write-only": "chỉ ghi","create-db": {"cluster": "Cụm","database-owner-name": "Tên chủ sở hữu cơ sở dữ liệu",@@ -293,6 +334,36 @@},"self": "Phê duyệt tùy chỉnh"},+ "data-source.additional-node-addresses": "Địa chỉ nút bổ sung",+ "data-source.connection-string-schema": "Lược đồ chuỗi kết nối",+ "data-source.connection-type": "Loại kết nối",+ "data-source.delete-read-only-data-source": "Xóa nguồn dữ liệu chỉ đọc",+ "data-source.direct-connection": "Kết nối trực tiếp",+ "data-source.extra-params.description": "Các tham số bổ sung cho chuỗi kết nối cơ sở dữ liệu",+ "data-source.extra-params.self": "Thông số bổ sung",+ "data-source.no-read-only-data-source": "Không có nguồn dữ liệu chỉ đọc",+ "data-source.private-key-passphrase": "Mật khẩu khóa riêng",+ "data-source.private-key-passphrase-placeholder": "Để trống nếu khóa riêng của bạn không được mã hóa",+ "data-source.private-key-passphrase-tip": "Mật khẩu tùy chọn cho khóa riêng được mã hóa",+ "data-source.read-replica-host": "Máy chủ bản sao đọc",+ "data-source.read-replica-port": "Cổng bản sao đọc",+ "data-source.replica-set": "Bộ bản sao",+ "data-source.snowflake-keypair-tip": "Xác thực cặp khóa",+ "data-source.ssh-connection": "Kết nối SSH",+ "data-source.ssh-type.none": "Không có",+ "data-source.ssh-type.tunnel-and-private-key": "Đường hầm + Khóa riêng",+ "data-source.ssh.host": "Máy chủ",+ "data-source.ssh.password": "Mật khẩu",+ "data-source.ssh.port": "Cổng",+ "data-source.ssh.private-key": "Khóa riêng",+ "data-source.ssh.ssh-key": "Khóa SSH",+ "data-source.ssh.user": "Người dùng",+ "data-source.ssl-connection": "Kết nối SSL",+ "data-source.ssl.ca-cert": "Chứng chỉ CA",+ "data-source.ssl.client-cert": "Chứng chỉ máy khách",+ "data-source.ssl.client-key": "Khóa máy khách",+ "data-source.ssl.verify-certificate": "Xác minh chứng chỉ TLS",+ "data-source.ssl.verify-certificate-tooltip": "Bật xác minh chứng chỉ TLS để kết nối an toàn. Chỉ tắt cho môi trường phát triển hoặc khi không thể xác thực chứng chỉ đúng cách (ví dụ: chứng chỉ tự ký, môi trường VPN). Cảnh báo: Tắt xác minh là không an toàn","database": {"all": "Tất cả cơ sở dữ liệu","change-database": "Thay đổi cơ sở dữ liệu",@@ -349,6 +420,9 @@"select": "Select database group","unmatched-database": "Unmatched database"},+ "database.engine": "Engine",+ "database.filter-database": "Lọc cơ sở dữ liệu",+ "database.sync-complete-for-instance": "Đồng bộ hoàn tất cho instance '{{0}}'","db": {"character-set": "Bộ ký tự","collation": "Đối chiếu",@@ -357,6 +431,11 @@"start-to-sync-schema": "Bắt đầu đồng bộ hóa lược đồ","successfully-synced-schema": "Đồng bộ hóa lược đồ thành công"},+ "db.failed-to-sync-schema": "Không đồng bộ hóa được lược đồ",+ "db.n-databases-had-sync-errors": "{{0}} cơ sở dữ liệu gặp lỗi đồng bộ",+ "db.start-to-sync-schema": "Bắt đầu đồng bộ hóa lược đồ",+ "db.syncing-databases-for-instance": "Đang đồng bộ hóa cơ sở dữ liệu cho {{0}}...",+ "dynamic.resource.instance": "ID phiên bản","environment": {"create": "Tạo môi trường","delete": "Xóa môi trường này",@@ -453,6 +532,128 @@},"syncing": "Đang đồng bộ hóa ..."},+ "instance.account-locator": "Định vị tài khoản",+ "instance.archive-instance-instance-name": "Lưu trữ phiên bản '{{0}}'?",+ "instance.archived-instances-will-not-be-displayed": "Các phiên bản đã lưu trữ sẽ không được hiển thị.",+ "instance.authentication-database": "Cơ sở dữ liệu xác thực",+ "instance.connection-info": "Thông tin kết nối",+ "instance.connection-options": "Tùy chọn kết nối",+ "instance.create-gcp-credentials": "Để tạo thông tin xác thực, xem",+ "instance.database-region": "Khu vực cơ sở dữ liệu",+ "instance.endpoint": "Điểm cuối",+ "instance.external-id": "ID bên ngoài",+ "instance.external-id-description": "ID bên ngoài để bảo mật bổ sung khi đảm nhận vai trò (tùy chọn)",+ "instance.external-id-placeholder": "ID bên ngoài tùy chọn",+ "instance.external-link": "Liên kết ngoài",+ "instance.external-secret-azure.secret-name": "Tên bí mật",+ "instance.external-secret-azure.secret-name-tips": "Tên của bí mật được lưu trữ trong Azure Key Vault.",+ "instance.external-secret-azure.vault-url": "URL Key Vault",+ "instance.external-secret-azure.vault-url-tips": "URL Key Vault phải giống như \"https://myvault.vault.azure.net/\".",+ "instance.external-secret-gcp.secret-name": "Tên đầy đủ bí mật",+ "instance.external-secret-gcp.secret-name-tips": "Tên bí mật phải giống như \"projects/project-id/secrets/secret-id\".",+ "instance.external-secret-vault.vault-auth-type.approle.role-id": "ID vai trò xác thực",+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name": "Tên môi trường",+ "instance.external-secret-vault.vault-auth-type.approle.secret-id": "ID bí mật xác thực",+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text": "Văn bản thuần",+ "instance.external-secret-vault.vault-auth-type.approle.self": "AppRole",+ "instance.external-secret-vault.vault-auth-type.self": "Loại xác thực",+ "instance.external-secret-vault.vault-auth-type.token.self": "Mã thông báo",+ "instance.external-secret-vault.vault-secret-engine-name": "Tên công cụ bí mật",+ "instance.external-secret-vault.vault-secret-engine-tips": "Chỉ hỗ trợ công cụ KV v2.",+ "instance.external-secret-vault.vault-secret-key": "Khóa bí mật",+ "instance.external-secret-vault.vault-secret-path": "Đường dẫn bí mật",+ "instance.external-secret-vault.vault-tls-config": "Cấu hình Vault TLS (Tùy chọn)",+ "instance.external-secret-vault.vault-url": "URL Vault",+ "instance.external-secret.key-name": "Khóa bí mật",+ "instance.external-secret.secret-name": "Tên bí mật",+ "instance.failed-to-connect-instance": "Không kết nối được với phiên bản.",+ "instance.failed-to-connect-instance-localhost": "Nếu bạn chạy Bytebase bằng Docker, vui lòng thử \"host.docker.internal\" cho địa chỉ máy chủ.",+ "instance.find-gcp-project-id": "Để tìm ID dự án GCP, xem",+ "instance.find-gcp-project-id-and-instance-id": "Để tìm ID dự án GCP và ID phiên bản, xem",+ "instance.force-archive-description": "Buộc lưu trữ. Tất cả cơ sở dữ liệu sẽ bị hủy gán.",+ "instance.grants": "Quyền",+ "instance.host-or-socket": "Máy chủ hoặc Socket",+ "instance.iam-extension.client-id": "Client ID",+ "instance.iam-extension.client-secret": "Client Secret",+ "instance.iam-extension.credential-source": "Credential Source",+ "instance.iam-extension.saas-default-credential-restriction": "Thông tin xác thực mặc định không khả dụng trong Bytebase Cloud vì lý do bảo mật. Vui lòng cung cấp thông tin xác thực cụ thể.",+ "instance.iam-extension.specific-credential": "Chứng chỉ cụ thể",+ "instance.iam-extension.tenant-id": "Tenant ID",+ "instance.info-panel.no-info": "Không có thông tin bổ sung cho engine này.",+ "instance.instance-id": "ID phiên bản",+ "instance.instance-name": "Tên phiên bản",+ "instance.new-instance": "Phiên bản mới",+ "instance.no-environment": "Trường hợp này không bị ràng buộc với môi trường",+ "instance.no-extra-params-configured": "Không có thông số kết nối bổ sung được cấu hình",+ "instance.no-params-yet-add-above": "Chưa có thông số nào được cấu hình. \nThêm tham số bằng cách sử dụng biểu mẫu trên.",+ "instance.no-password": "Không có mật khẩu",+ "instance.parameter-name-placeholder": "Tên tham số",+ "instance.parameter-value-placeholder": "Giá trị tham số",+ "instance.password-type.aws-iam": "AWS RDS IAM",+ "instance.password-type.azure-iam": "Azure IAM",+ "instance.password-type.external-secret-aws": "AWS Secrets Manager",+ "instance.password-type.external-secret-azure": "Azure Key Vault",+ "instance.password-type.external-secret-gcp": "GCP Secret Manager",+ "instance.password-type.external-secret-vault": "Vault (KV v2)",+ "instance.password-type.google-iam": "Google Cloud SQL IAM",+ "instance.password-type.password": "Mật khẩu",+ "instance.password-write-only": "YOUR_DB_PWD - chỉ ghi",+ "instance.port": "Cổng",+ "instance.project-id": "ID dự án",+ "instance.restore-instance-instance-name-to-normal-state": "Khôi phục phiên bản '{{0}}' về trạng thái bình thường?",+ "instance.role-arn": "ARN vai trò",+ "instance.role-arn-description": "Vai trò IAM để đảm nhận cho truy cập xuyên tài khoản. Để trống cho truy cập cùng tài khoản.",+ "instance.role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "instance.scan-interval.default-never": "Mặc định (không bao giờ)",+ "instance.scan-interval.description": "Bytebase định kỳ đồng bộ lược đồ phiên bản và phát hiện bất thường.",+ "instance.scan-interval.min-value": "Giá trị nhỏ nhất {{value}} phút",+ "instance.scan-interval.self": "Khoảng thời gian quét",+ "instance.section.basic-info": "Thông tin cơ bản",+ "instance.section.connection": "Kết nối",+ "instance.sentence.aws-rds.mysql.template": "Dưới đây là ví dụ để tạo người dùng {{user}}@% và cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.aws-rds.postgresql.template": "Dưới đây là ví dụ để tạo người dùng '{{user}}' và cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.console.snowflake": "URL bảng điều khiển bên ngoài quản lý phiên bản này (ví dụ: bảng điều khiển AWS RDS, bảng điều khiển phiên bản cơ sở dữ liệu nội bộ của bạn)",+ "instance.sentence.create-admin-user": "Đây là người dùng kết nối được Bytebase sử dụng để thực hiện các hoạt động DDL và DML (không phải SELECT).",+ "instance.sentence.create-admin-user-non-sql": "Đây là người dùng kết nối được Bytebase sử dụng để thực hiện các hoạt động ghi và quản trị.",+ "instance.sentence.create-readonly-user": "Đây là kết nối được Bytebase sử dụng để thực hiện các hoạt động chỉ đọc như truy vấn SELECT.",+ "instance.sentence.create-readonly-user-non-sql": "Đây là kết nối được Bytebase sử dụng để thực hiện các hoạt động chỉ đọc.",+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow": "Quy trình công việc dựa trên SQL",+ "instance.sentence.create-user-example.clickhouse.template": "Dưới đây là ví dụ để tạo người dùng '{{user}}' với mật khẩu {{password}} và cấp cho người dùng các đặc quyền cần thiết. Đầu tiên, bạn cần bật {{link}} quy trình công việc dựa trên SQL và sau đó chạy truy vấn sau để tạo người dùng.",+ "instance.sentence.create-user-example.mysql.template": "Dưới đây là ví dụ để tạo người dùng {{user}}@% với mật khẩu {{password}} và cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.create-user-example.postgresql.template": "Dưới đây là ví dụ để tạo người dùng '{{user}}' với mật khẩu {{password}} và cấp cho người dùng các đặc quyền cần thiết. Nếu phiên bản kết nối được tự lưu trữ, thì bạn có thể cấp SUPERUSER.",+ "instance.sentence.create-user-example.postgresql.warn": "Nếu phiên bản kết nối được quản lý bởi nhà cung cấp đám mây, thì SUPERUSER không khả dụng và bạn nên tạo người dùng thông qua bảng điều khiển quản trị của nhà cung cấp đó. Người dùng đã tạo sẽ có các đặc quyền bán SUPERUSER cụ thể của nhà cung cấp. Bạn nên cấp các đặc quyền Bytebase với 'GRANT role_name TO bytebase;' cho tất cả các vai trò hiện có, nếu không Bytebase có thể không truy cập được các cơ sở dữ liệu hoặc bảng hiện có.",+ "instance.sentence.create-user-example.redis.template": "Dưới đây là ví dụ để tạo người dùng {{user}} với mật khẩu {{password}} và cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.create-user-example.snowflake.template": "Dưới đây là ví dụ để tạo người dùng '{{user}}' với mật khẩu {{password}} cho {{warehouse}} và cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.firewall-info": "Nếu bạn sử dụng các quy tắc tường lửa gửi đến cho thể hiện cơ sở dữ liệu của mình, vui lòng tham khảo Hướng dẫn kết nối đám mây Bytebase.",+ "instance.sentence.google-cloud-sql.instance-name": "Tên kết nối phiên bản",+ "instance.sentence.google-cloud-sql.instance-name-tips": "Tên kết nối phiên bản phải giống như {{instance}}.",+ "instance.sentence.google-cloud-sql.mysql.template": "Tạo một tài khoản dịch vụ có tên {{user}}, sau đó thêm nó vào Google Cloud SQL của bạn với tư cách là người dùng IAM {{user}}@'%'. Cấp cho người dùng này các đặc quyền cần thiết.",+ "instance.sentence.google-cloud-sql.postgresql.template": "Tạo một tài khoản dịch vụ có tên {{user}}, sau đó thêm nó vào Google Cloud SQL của bạn với tư cách là người dùng IAM {{user}}@project-id.iam. Cấp cho người dùng các đặc quyền cần thiết.",+ "instance.sentence.host.none-snowflake": "ví dụ: host.docker.internal {'|'} địa chỉ IP máy chủ {'|'} local socket",+ "instance.sentence.proxy.snowflake": "Đối với máy chủ proxy, thêm {'@'}PROXY_HOST và chỉ định PROXY_PORT trong cổng",+ "instance.show-how-to-create": "Hiển thị cách tạo",+ "instance.snowflake-web-console": "Bảng điều khiển web Snowflake",+ "instance.successfully-archived-instance": "Đã lưu trữ thành công phiên bản '{{0}}'.",+ "instance.successfully-connected-instance": "Đã kết nối thành công với phiên bản.",+ "instance.successfully-created-instance-createdinstance-name": "Đã tạo thành công phiên bản '{{0}}'.",+ "instance.successfully-restored-instance": "Đã khôi phục thành công trường hợp '{{0}}'.",+ "instance.successfully-updated-instance-instance-name": "Đã cập nhật thành công phiên bản '{{0}}'.",+ "instance.sync-databases.add-database": "+ Thêm cơ sở dữ liệu, nhấn enter để gửi",+ "instance.sync-databases.description": "Chỉ đồng bộ các cơ sở dữ liệu đã chọn.",+ "instance.sync-databases.search-database": "Tìm kiếm cơ sở dữ liệu",+ "instance.sync-databases.self": "Đồng bộ cơ sở dữ liệu",+ "instance.sync-databases.sync-all": "Đồng bộ tất cả cơ sở dữ liệu",+ "instance.sync.self": "Đồng bộ phiên bản",+ "instance.sync.sync-all": "Đồng bộ tất cả cơ sở dữ liệu",+ "instance.sync.sync-all-tip": "Đồng bộ cơ sở dữ liệu không đồng bộ và có thể mất vài giây đến vài phút",+ "instance.sync.sync-new": "Chỉ đồng bộ cơ sở dữ liệu mới",+ "instance.syncing": "Đang đồng bộ hóa ...",+ "instance.test-connection": "Kiểm tra kết nối",+ "instance.testing-connection": "Đang kiểm tra kết nối",+ "instance.type-or-paste-credentials-write-only": "Nhập hoặc dán THÔNG TIN XÁC THỰC - chỉ ghi",+ "instance.unable-to-connect": "Bytebase không thể kết nối với phiên bản. Chúng tôi khuyên bạn nên xem xét lại thông tin kết nối. Nhưng bạn có thể bỏ qua cảnh báo này ngay bây giờ. Bạn vẫn có thể sửa thông tin kết nối từ trang chi tiết phiên bản sau khi tạo.\n\nChi tiết lỗi: {{0}}",+ "instance.users": "Người dùng",+ "instance.your-snowflake-account-locator": "Định vị tài khoản Snowflake của bạn","issue": {"advanced-search": {"filter": "Bộ lọc"@@ -489,6 +690,12 @@"max-value-length-exceeded": "Độ dài giá trị không được vượt quá {{length}} ký tự"}},+ "label.add-label": "Thêm nhãn",+ "label.empty-label-value": "Trống",+ "label.error.key-duplicated": "Khóa trùng lặp",+ "label.error.key-necessary": "Khóa là bắt buộc",+ "label.error.max-value-length-exceeded": "Độ dài giá trị không được vượt quá {{length}} ký tự",+ "label.error.value-necessary": "Giá trị là bắt buộc","landing": {"changelog-for-version": "Nhật ký thay đổi cho phiên bản {{version}}","last-visit": "Lần truy cập cuối",@@ -680,6 +887,7 @@"new-project": "Mới Dự án","request-export-data": "Yêu cầu Xuất"},+ "quick-action.add-instance": "@:common.add @:common.instance","release": {"releases": "Bản phát hành"},@@ -704,6 +912,13 @@"pattern": "ID {{resource}} có thể có chữ thường, chữ số hoặc dấu gạch nối. \nNó phải bắt đầu với một chữ cái viết thường và kết thúc bằng một chữ cái hoặc số."}},+ "resource-id.cannot-be-changed-later": "Nó không thể được thay đổi sau này.",+ "resource-id.description": "ID {{resource}} là một mã định danh duy nhất. Bạn không thể thay đổi nó sau khi tạo.",+ "resource-id.self": "ID {{resource}}",+ "resource-id.validation.duplicated": "ID {{resource}} đã tồn tại. Vui lòng chọn một ID khác.",+ "resource-id.validation.empty": "ID {{resource}} không được để trống",+ "resource-id.validation.overflow": "ID {{resource}} quá dài. Nó phải có ít hơn 64 ký tự.",+ "resource-id.validation.pattern": "ID {{resource}} có thể có chữ thường, chữ số hoặc dấu gạch nối. \nNó phải bắt đầu với một chữ cái viết thường và kết thúc bằng một chữ cái hoặc số.","role": {"custom-roles": {"self": "Vai trò tùy chỉnh"@@ -734,6 +949,8 @@"search": "Tìm kiếm phân loại"}},+ "setting.label.key-placeholder": "Khóa nhãn...",+ "setting.label.value-placeholder": "Giá trị nhãn...","settings": {"general": {"workspace": {@@ -1387,6 +1604,10 @@}}},+ "subscription.instance-assignment.assign-license": "Gán giấy phép",+ "subscription.instance-assignment.n-license-remain": "còn lại {{n}}",+ "subscription.usage.instance-count.runoutof": "Bạn đã hết hạn ngạch {{total}} phiên bản của mình.",+ "subscription.usage.instance-count.title": "Giới hạn số lượng phiên bản","two-factor": {"description": "Xác thực hai yếu tố cung cấp một lớp bảo mật bổ sung cho các tài khoản thành viên. Khi đăng nhập, bạn sẽ được yêu cầu nhập mã bảo mật do Ứng dụng xác thực của bạn tạo.","disable": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 08e091debf..32f4210c14 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -218,6 +218,47 @@"webhooks": "Webhook","you": "您"},+ "common.add": "添加",+ "common.admin": "管理员",+ "common.archive": "归档",+ "common.archived": "已归档",+ "common.cancel": "取消",+ "common.cannot-undo-this-action": "这个操作无法撤销",+ "common.confirm-and-update": "确认并更新",+ "common.continue-anyway": "仍要继续",+ "common.create": "创建",+ "common.creating": "创建中...",+ "common.custom": "自定义",+ "common.database": "数据库",+ "common.databases": "数据库",+ "common.default": "默认",+ "common.delete": "删除",+ "common.delete-resource": "删除{{type}}",+ "common.deleted": "已删除",+ "common.detailed-guide": "详细指南",+ "common.edit": "编辑",+ "common.environment": "环境",+ "common.key": "键",+ "common.labels": "标签",+ "common.learn-more": "了解更多",+ "common.loading": "加载中",+ "common.minutes": "分钟",+ "common.no-data": "无数据",+ "common.optional": "可选",+ "common.overview": "概览",+ "common.password": "密码",+ "common.project": "项目",+ "common.read-only": "只读",+ "common.restore": "恢复",+ "common.sensitive-placeholder": "敏感数据 - 仅写入",+ "common.unlimited": "无限制",+ "common.updated": "已更新",+ "common.updating": "更新中",+ "common.user": "用户",+ "common.username": "用户名",+ "common.value": "值",+ "common.warning": "警告",+ "common.write-only": "仅写入","create-db": {"cluster": "集群","database-owner-name": "数据库所有者",@@ -293,6 +334,36 @@},"self": "自定义审批"},+ "data-source.additional-node-addresses": "附加节点地址",+ "data-source.connection-string-schema": "连接串模式",+ "data-source.connection-type": "连接类型",+ "data-source.delete-read-only-data-source": "删除只读数据源",+ "data-source.direct-connection": "Direct Connection",+ "data-source.extra-params.description": "数据库连接字符串的其他参数",+ "data-source.extra-params.self": "额外的参数",+ "data-source.no-read-only-data-source": "没有只读数据源",+ "data-source.private-key-passphrase": "私钥密码",+ "data-source.private-key-passphrase-placeholder": "如果私钥未加密,请留空",+ "data-source.private-key-passphrase-tip": "加密私钥的可选密码",+ "data-source.read-replica-host": "只读副本 Host",+ "data-source.read-replica-port": "只读副本端口",+ "data-source.replica-set": "副本集",+ "data-source.snowflake-keypair-tip": "密钥对认证",+ "data-source.ssh-connection": "SSH 连接",+ "data-source.ssh-type.none": "不使用",+ "data-source.ssh-type.tunnel-and-private-key": "隧道 + 私钥",+ "data-source.ssh.host": "服务器",+ "data-source.ssh.password": "密码",+ "data-source.ssh.port": "端口",+ "data-source.ssh.private-key": "私钥",+ "data-source.ssh.ssh-key": "SSH 密钥",+ "data-source.ssh.user": "用户名",+ "data-source.ssl-connection": "SSL 连接",+ "data-source.ssl.ca-cert": "CA 证书",+ "data-source.ssl.client-cert": "客户端证书",+ "data-source.ssl.client-key": "客户端密钥",+ "data-source.ssl.verify-certificate": "验证 TLS 证书",+ "data-source.ssl.verify-certificate-tooltip": "启用 TLS 证书验证以确保安全连接。仅在开发环境或证书无法正确验证的情况下禁用(例如自签名证书、VPN 环境)。警告:禁用验证是不安全的","database": {"all": "所有数据库","change-database": "变更数据库",@@ -349,6 +420,9 @@"select": "Select database group","unmatched-database": "Unmatched database"},+ "database.engine": "引擎",+ "database.filter-database": "过滤数据库",+ "database.sync-complete-for-instance": "实例 '{{0}}' 同步完成","db": {"character-set": "字符集","collation": "排序规则",@@ -357,6 +431,11 @@"start-to-sync-schema": "开始同步 schema","successfully-synced-schema": "成功同步 schema"},+ "db.failed-to-sync-schema": "同步 schema 失败",+ "db.n-databases-had-sync-errors": "{{0}} 个数据库同步出错",+ "db.start-to-sync-schema": "开始同步 schema",+ "db.syncing-databases-for-instance": "正在同步 {{0}} 的数据库...",+ "dynamic.resource.instance": "实例 ID","environment": {"create": "创建环境","delete": "删除此环境",@@ -453,6 +532,128 @@},"syncing": "同步中 ..."},+ "instance.account-locator": "账户定位符",+ "instance.archive-instance-instance-name": "归档实例'{{0}}'?",+ "instance.archived-instances-will-not-be-displayed": "不再会显示已归档实例。",+ "instance.authentication-database": "认证数据库",+ "instance.connection-info": "连接信息",+ "instance.connection-options": "连接选项",+ "instance.create-gcp-credentials": "创建凭据的方法见",+ "instance.database-region": "数据库区域",+ "instance.endpoint": "端点",+ "instance.external-id": "外部 ID",+ "instance.external-id-description": "承担角色时用于额外安全性的外部 ID(可选)",+ "instance.external-id-placeholder": "可选的外部 ID",+ "instance.external-link": "外部链接",+ "instance.external-secret-azure.secret-name": "密钥名称",+ "instance.external-secret-azure.secret-name-tips": "存储在 Azure Key Vault 中的密钥名称。",+ "instance.external-secret-azure.vault-url": "Key Vault URL",+ "instance.external-secret-azure.vault-url-tips": "Key Vault URL 应类似于 \"https://myvault.vault.azure.net/\"",+ "instance.external-secret-gcp.secret-name": "密钥完整路径",+ "instance.external-secret-gcp.secret-name-tips": "密钥完整路径应类似于 \"projects/project-id/secrets/secret-id\"",+ "instance.external-secret-vault.vault-auth-type.approle.role-id": "Auth role id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-env-name": "环境变量名",+ "instance.external-secret-vault.vault-auth-type.approle.secret-id": "Auth secret id",+ "instance.external-secret-vault.vault-auth-type.approle.secret-plain-text": "明文",+ "instance.external-secret-vault.vault-auth-type.approle.self": "AppRole",+ "instance.external-secret-vault.vault-auth-type.self": "认证方式",+ "instance.external-secret-vault.vault-auth-type.token.self": "Token",+ "instance.external-secret-vault.vault-secret-engine-name": "Secret engine name",+ "instance.external-secret-vault.vault-secret-engine-tips": "仅支持 KV v2 储存",+ "instance.external-secret-vault.vault-secret-key": "Secret key",+ "instance.external-secret-vault.vault-secret-path": "Secret path",+ "instance.external-secret-vault.vault-tls-config": "Vault TLS 配置(可选)",+ "instance.external-secret-vault.vault-url": "Vault URL",+ "instance.external-secret.key-name": "Secret key",+ "instance.external-secret.secret-name": "Secret name",+ "instance.failed-to-connect-instance": "连接到实例失败。",+ "instance.failed-to-connect-instance-localhost": "如果您使用的 Docker 部署,请尝试使用 \"host.docker.internal\" 作为 Host 地址。",+ "instance.find-gcp-project-id": "查看 GCP 项目 ID 的方法见",+ "instance.find-gcp-project-id-and-instance-id": "查看 GCP 项目 ID 与实例 ID 的方法见",+ "instance.force-archive-description": "强制归档。所有数据库均将被取消分配。",+ "instance.grants": "权限",+ "instance.host-or-socket": "Host 或 Socket",+ "instance.iam-extension.client-id": "Client ID",+ "instance.iam-extension.client-secret": "Client Secret",+ "instance.iam-extension.credential-source": "凭证来源",+ "instance.iam-extension.saas-default-credential-restriction": "出于安全考虑,Bytebase Cloud 不支持使用默认凭证。请提供具体凭证。",+ "instance.iam-extension.specific-credential": "指定凭证",+ "instance.iam-extension.tenant-id": "Tenant ID",+ "instance.info-panel.no-info": "暂无该引擎的额外信息。",+ "instance.instance-id": "实例 ID",+ "instance.instance-name": "实例名称",+ "instance.new-instance": "新实例",+ "instance.no-environment": "此实例尚未绑定到环境",+ "instance.no-extra-params-configured": "没有配置的额外连接参数",+ "instance.no-params-yet-add-above": "尚未配置参数。\n使用上面的形式添加参数。",+ "instance.no-password": "无密码",+ "instance.parameter-name-placeholder": "参数名称",+ "instance.parameter-value-placeholder": "参数值",+ "instance.password-type.aws-iam": "AWS RDS IAM",+ "instance.password-type.azure-iam": "Azure IAM",+ "instance.password-type.external-secret-aws": "AWS Secrets Manager",+ "instance.password-type.external-secret-azure": "Azure Key Vault",+ "instance.password-type.external-secret-gcp": "GCP Secret Manager",+ "instance.password-type.external-secret-vault": "Vault (KV v2)",+ "instance.password-type.google-iam": "Google Cloud SQL IAM",+ "instance.password-type.password": "密码",+ "instance.password-write-only": "YOUR_DB_PWD - 仅写入",+ "instance.port": "端口",+ "instance.project-id": "项目 ID",+ "instance.restore-instance-instance-name-to-normal-state": "恢复实例'{{0}}'到正常状态?",+ "instance.role-arn": "角色 ARN",+ "instance.role-arn-description": "用于跨账户访问的 IAM 角色。同账户访问请留空。",+ "instance.role-arn-placeholder": "arn:aws:iam::123456789012:role/CrossAccountRole",+ "instance.scan-interval.default-never": "默认(永不)",+ "instance.scan-interval.description": "Bytebase 会定期同步实例的 schema 以及进行异常检测。",+ "instance.scan-interval.min-value": "最小值 {{value}} 分钟",+ "instance.scan-interval.self": "扫描间隔",+ "instance.section.basic-info": "基本信息",+ "instance.section.connection": "连接",+ "instance.sentence.aws-rds.mysql.template": "下面是创建用户 {{user}}@% 并授予该用户所需权限的示例。",+ "instance.sentence.aws-rds.postgresql.template": "下面是创建用户“{{user}}”并授予该用户所需权限的示例。",+ "instance.sentence.console.snowflake": "\b管理该实例的外部控制台 URL(如 AWS RDS 控制台,您的数据库控制台)",+ "instance.sentence.create-admin-user": "这是 Bytebase 用于连接数据库,执行 DDL 和 DML (非 SELECT) 操作的用户。",+ "instance.sentence.create-admin-user-non-sql": "这是 Bytebase 用于连接数据库,执行写和管理操作的用户。",+ "instance.sentence.create-readonly-user": "这是 Bytebase 用于连接数据库,执行诸如 SELECT 的只读操作的用户。",+ "instance.sentence.create-readonly-user-non-sql": "这是 Bytebase 用于连接数据库,执行只读操作的用户。",+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow": "SQL 工作流",+ "instance.sentence.create-user-example.clickhouse.template": "创建用户 {{user}},密码 {{password}},并授予必要权限的例子如下。您需要首先启用 {{link}},才能执行以下创建用户的命令。",+ "instance.sentence.create-user-example.mysql.template": "创建用户 {{user}},密码 {{password}},并授予必要权限的例子如下。",+ "instance.sentence.create-user-example.postgresql.template": "创建用户 {{user}},密码 {{password}},并授予必要权限的例子如下。如果您将要连接到的实例是自己托管的,那么您可以 grant SUPERUSER。",+ "instance.sentence.create-user-example.postgresql.warn": "如果您将要连接到的实例是由云服务供应商管理的话,那么 SUPERUSER 是不可用的,您需要通过供应商的管理员控制台来创建用户。您所创建的用户会拥有供应商特定的 semi-SUPERUSER 的权限。 您应该对所有 role 用 'GRANT role_name TO bytebase;' 语句赋予 Bytebase 权限,否则 Bytebase 可能没有权限操作已有的数据库或者表导致操作失败。",+ "instance.sentence.create-user-example.redis.template": "创建用户 {{user}},密码 {{password}},并授予必要权限的例子如下。",+ "instance.sentence.create-user-example.snowflake.template": "创建用户 {{user}},密码 {{password}},warehouse 为{{warehouse}},并授予必要权限的例子如下。",+ "instance.sentence.firewall-info": "如果您为数据库实例使用入站防火墙规则,请参阅 ByteBase Cloud Connection 文档。",+ "instance.sentence.google-cloud-sql.instance-name": "实例连接名称",+ "instance.sentence.google-cloud-sql.instance-name-tips": "实例连接名称应为 {{instance}}。",+ "instance.sentence.google-cloud-sql.mysql.template": "创建一个名为 {{user}} 的服务帐户,然后将其作为 IAM 用户 {{user}}@'%' 添加到您的 Google Cloud SQL 中。授予此用户所需的权限。",+ "instance.sentence.google-cloud-sql.postgresql.template": "创建一个名为 {{user}} 的服务帐户,然后将其作为 IAM 用户 {{user}}@project-id.iam 添加到您的 Google Cloud SQL 中。授予用户所需的权限。",+ "instance.sentence.host.none-snowflake": "例如 host.docker.internal {'|'} ip {'|'} local socket",+ "instance.sentence.proxy.snowflake": "对于代理服务器,加上 {'@'}PROXY_HOST,并在端口里指定 PROXY_PORT",+ "instance.show-how-to-create": "如何创建",+ "instance.snowflake-web-console": "Snowflake Web 控制台",+ "instance.successfully-archived-instance": "成功归档实例'{{0}}'。",+ "instance.successfully-connected-instance": "成功连接到实例。",+ "instance.successfully-created-instance-createdinstance-name": "成功创建实例'{{0}}'。",+ "instance.successfully-restored-instance": "已成功恢复实例“{{0}}”。",+ "instance.successfully-updated-instance-instance-name": "成功更新实例'{{0}}'。",+ "instance.sync-databases.add-database": "+ 添加数据库,按回车键提交",+ "instance.sync-databases.description": "仅同步选定的数据库。",+ "instance.sync-databases.search-database": "搜索数据库",+ "instance.sync-databases.self": "同步数据库",+ "instance.sync-databases.sync-all": "同步所有数据库",+ "instance.sync.self": "同步实例",+ "instance.sync.sync-all": "同步所有数据库",+ "instance.sync.sync-all-tip": "数据库同步是异步的,可能需要几秒到几分钟",+ "instance.sync.sync-new": "仅同步新数据库",+ "instance.syncing": "同步中 ...",+ "instance.test-connection": "测试连接",+ "instance.testing-connection": "测试连接中",+ "instance.type-or-paste-credentials-write-only": "输入或粘贴 CREDENTIALS - 仅写入",+ "instance.unable-to-connect": "Bytebase 无法连接到实例。我们推荐您再检查一遍连接信息。但也可以暂时忽略此警告。您在创建后仍能在实例详细页里修复连接信息。\n\n错误详情:{{0}}",+ "instance.users": "用户",+ "instance.your-snowflake-account-locator": "您的 Snowflake 账户定位符","issue": {"advanced-search": {"filter": "过滤"@@ -489,6 +690,12 @@"max-value-length-exceeded": "值的长度不能超过 {{length}} 字符"}},+ "label.add-label": "添加标签",+ "label.empty-label-value": "空",+ "label.error.key-duplicated": "Key 重复了",+ "label.error.key-necessary": "需要指定 Key",+ "label.error.max-value-length-exceeded": "值的长度不能超过 {{length}} 字符",+ "label.error.value-necessary": "需要指定值","landing": {"changelog-for-version": "{{version}} 的更新日志","last-visit": "上次访问",@@ -680,6 +887,7 @@"new-project": "创建项目","request-export-data": "申请导出数据"},+ "quick-action.add-instance": "@:common.add@:common.instance","release": {"releases": "发布包"},@@ -704,6 +912,13 @@"pattern": "{{resource}} ID 可以具有小写字母,数字或连字符。\n它必须从小写字母开始,并以字母或数字结尾。"}},+ "resource-id.cannot-be-changed-later": "创建之后无法修改。",+ "resource-id.description": "{{resource}} ID 是一个唯一的标识符。创建之后无法修改。",+ "resource-id.self": "{{resource}} ID",+ "resource-id.validation.duplicated": "{{resource}} ID 已存在。请使用其他 ID。",+ "resource-id.validation.empty": "{{resource}} ID 不能为空",+ "resource-id.validation.overflow": "{{resource}} ID 应该少于 64 个字符。",+ "resource-id.validation.pattern": "{{resource}} ID 可以具有小写字母,数字或连字符。\n它必须从小写字母开始,并以字母或数字结尾。","role": {"custom-roles": {"self": "自定义角色"@@ -734,6 +949,8 @@"search": "搜索分类"}},+ "setting.label.key-placeholder": "标签 key...",+ "setting.label.value-placeholder": "标签值…","settings": {"general": {"workspace": {@@ -1387,6 +1604,10 @@}}},+ "subscription.instance-assignment.assign-license": "分配证书",+ "subscription.instance-assignment.n-license-remain": "剩余 {{n}} 个",+ "subscription.usage.instance-count.runoutof": "已用尽全部 {{total}} 个实例额度。",+ "subscription.usage.instance-count.title": "实例数量限制","two-factor": {"description": "双重认证为系统成员提供了一个额外的安全层。在登录时,用户需要输入由认证器应用程序生成的安全代码。","disable": {diff --git a/frontend/src/react/pages/settings/CreateInstancePage.tsx b/frontend/src/react/pages/settings/CreateInstancePage.tsxnew file mode 100644index 0000000000..d703428681--- /dev/null+++ b/frontend/src/react/pages/settings/CreateInstancePage.tsx@@ -0,0 +1,187 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ InfoPanel,+ InfoPanelContent,+ InstanceFormBody,+ InstanceFormButtons,+ InstanceFormProvider,+ useInstanceFormContext,+} from "@/react/components/instance";+import type { InfoSection } from "@/react/components/instance/info-content";+import { router } from "@/router";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";+import {+ pushNotification,+ useActuatorV1Store,+ useSubscriptionV1Store,+} from "@/store";++const MIN_DOCKED_MAIN_WIDTH = 700;+const DOCKED_INFO_RAIL_WIDTH = 500;+const DOCKED_INFO_RAIL_GAP = 16;+const MIN_DOCKED_LAYOUT_WIDTH =+ MIN_DOCKED_MAIN_WIDTH + DOCKED_INFO_RAIL_WIDTH + DOCKED_INFO_RAIL_GAP;++export function CreateInstancePage() {+ const { t } = useTranslation();+ const subscriptionStore = useSubscriptionV1Store();+ const actuatorStore = useActuatorV1Store();++ // Check instance limit on mount+ useEffect(() => {+ if (+ subscriptionStore.instanceCountLimit <=+ actuatorStore.activatedInstanceCount+ ) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("subscription.usage.instance-count.title"),+ description: t("subscription.usage.instance-count.runoutof", {+ total: subscriptionStore.instanceCountLimit,+ }),+ });+ router.push({ name: INSTANCE_ROUTE_DASHBOARD });+ }+ }, [subscriptionStore, actuatorStore, t]);++ const goBack = useCallback(() => {+ router.push({ name: INSTANCE_ROUTE_DASHBOARD });+ }, []);++ return (+ <div className="h-full overflow-hidden px-4 sm:px-6">+ <InstanceFormProvider onDismiss={goBack}>+ <CreateInstanceFormInner />+ </InstanceFormProvider>+ </div>+ );+}++function CreateInstanceFormInner() {+ const { t } = useTranslation();+ const ctx = useInstanceFormContext();+ const currentEngine = ctx.basicInfo.engine;++ const [activeInfoSection, setActiveInfoSection] = useState<+ InfoSection | undefined+ >();+ const layoutRef = useRef<HTMLDivElement>(null);+ const [layoutWidth, setLayoutWidth] = useState(0);++ useEffect(() => {+ const el = layoutRef.current;+ if (!el) return;+ const observer = new ResizeObserver((entries) => {+ for (const entry of entries) {+ setLayoutWidth(entry.contentRect.width);+ }+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const canUseDockedInfoLayout = layoutWidth >= MIN_DOCKED_LAYOUT_WIDTH;+ const showDockedInfoPanel = !!activeInfoSection && canUseDockedInfoLayout;+ const showOverlayInfoPanel = !!activeInfoSection && !canUseDockedInfoLayout;++ const layoutStyle = useMemo(() => {+ if (!canUseDockedInfoLayout || !showDockedInfoPanel) {+ return {+ gridTemplateColumns: "minmax(0, 1fr)",+ columnGap: "0rem",+ };+ }+ return {+ gridTemplateColumns: `minmax(${MIN_DOCKED_MAIN_WIDTH}px, 1fr) ${DOCKED_INFO_RAIL_WIDTH}px`,+ columnGap: `${DOCKED_INFO_RAIL_GAP}px`,+ };+ }, [canUseDockedInfoLayout, showDockedInfoPanel]);++ const infoPanelTitle = useMemo(() => {+ if (!activeInfoSection) return "";+ const titleMap: Record<InfoSection, string> = {+ host: t("instance.host-or-socket"),+ port: t("instance.port"),+ authentication: t("instance.connection-info"),+ ssl: t("data-source.ssl-connection"),+ ssh: t("data-source.ssh-connection"),+ database: t("common.database"),+ };+ return titleMap[activeInfoSection] ?? "";+ }, [activeInfoSection, t]);++ const handleDockedInfoPanelOutsideClick = useCallback(+ (event: React.MouseEvent) => {+ if (!showDockedInfoPanel) return;+ const target = event.target;+ if (!(target instanceof Element)) return;+ if (target.closest("[data-info-panel-docked='true']")) return;+ setActiveInfoSection(undefined);+ },+ [showDockedInfoPanel]+ );++ const handleOpenInfoPanel = useCallback((section: InfoSection) => {+ setActiveInfoSection(section);+ }, []);++ return (+ <div+ ref={layoutRef}+ className="grid h-full w-full min-h-0 min-w-0"+ style={layoutStyle}+ onClick={handleDockedInfoPanelOutsideClick}+ >+ <div className="min-w-0 min-h-0 flex-1 flex flex-col">+ {/* Header */}+ <div className="sticky top-0 z-10 bg-white border-b border-block-border py-4">+ <h1 className="text-lg font-medium">+ {t("quick-action.add-instance")}+ </h1>+ </div>++ {/* Body */}+ <div className="flex-1 min-h-0 overflow-auto py-4">+ <InstanceFormBody onOpenInfoPanel={handleOpenInfoPanel} />+ </div>++ {/* Sticky footer */}+ <div className="sticky bottom-0 z-10 bg-white">+ <InstanceFormButtons />+ </div>+ </div>++ {/* Docked info panel */}+ <InfoPanel+ visible={showDockedInfoPanel}+ mode="docked"+ title={infoPanelTitle}+ onClose={() => setActiveInfoSection(undefined)}+ >+ {activeInfoSection && (+ <InfoPanelContent+ engine={currentEngine}+ section={activeInfoSection}+ />+ )}+ </InfoPanel>++ {/* Overlay info panel */}+ <InfoPanel+ visible={showOverlayInfoPanel}+ mode="overlay"+ title={infoPanelTitle}+ onClose={() => setActiveInfoSection(undefined)}+ >+ {activeInfoSection && (+ <InfoPanelContent+ engine={currentEngine}+ section={activeInfoSection}+ />+ )}+ </InfoPanel>+ </div>+ );+}diff --git a/frontend/src/react/pages/settings/InstanceDetailPage.tsx b/frontend/src/react/pages/settings/InstanceDetailPage.tsxnew file mode 100644index 0000000000..f617a7c175--- /dev/null+++ b/frontend/src/react/pages/settings/InstanceDetailPage.tsx@@ -0,0 +1,211 @@+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ AdvancedSearch,+ getValueFromScopes,+ type ScopeOption,+ type SearchParams,+} from "@/react/components/AdvancedSearch";+import { DatabaseTable } from "@/react/components/database";+import {+ InstanceActionDropdown,+ InstanceFormBody,+ InstanceFormButtons,+ InstanceFormProvider,+ InstanceRoleTable,+ InstanceSyncButton,+} from "@/react/components/instance";+import { EngineIconPath } from "@/react/components/instance/constants";+import {+ Tabs,+ TabsList,+ TabsPanel,+ TabsTrigger,+} from "@/react/components/ui/tabs";+import { useVueState } from "@/react/hooks/useVueState";+import { useDatabaseV1Store, useInstanceV1Store } from "@/store";+import {+ environmentNamePrefix,+ instanceNamePrefix,+ projectNamePrefix,+} from "@/store/modules/v1/common";+import type { DatabaseFilter } from "@/store/modules/v1/database";+import { State } from "@/types/proto-es/v1/common_pb";+import { instanceV1Name, setDocumentTitle } from "@/utils";++const instanceHashList = ["overview", "databases", "users"] as const;+type InstanceHash = (typeof instanceHashList)[number];+const isInstanceHash = (x: unknown): x is InstanceHash =>+ instanceHashList.includes(x as InstanceHash);++export function InstanceDetailPage({ instanceId }: { instanceId: string }) {+ const { t } = useTranslation();+ const instanceStore = useInstanceV1Store();+ const databaseStore = useDatabaseV1Store();+ const instanceName = `${instanceNamePrefix}${instanceId}`;+ const instance = useVueState(() =>+ instanceStore.getInstanceByName(instanceName)+ );++ const [selectedTab, setSelectedTab] = useState<InstanceHash>("overview");+ const [searchParams, setSearchParams] = useState<SearchParams>({+ query: "",+ scopes: [{ id: "instance", value: instanceId, readonly: true }],+ });+ // Sync tab with URL hash+ useEffect(() => {+ const hash = window.location.hash.replace(/^#?/, "");+ if (isInstanceHash(hash)) {+ setSelectedTab(hash);+ }+ }, []);++ useEffect(() => {+ const query = new URLSearchParams(window.location.search);+ query.delete("qs");+ const url = `${window.location.pathname}?${query.toString()}#${selectedTab}`;+ window.history.replaceState(null, "", url);+ }, [selectedTab]);++ // Set document title+ useEffect(() => {+ if (instance.title) {+ setDocumentTitle(instance.title);+ }+ }, [instance.title]);++ const syncSchema = useCallback(+ async (enableFullSync: boolean) => {+ await instanceStore.syncInstance(instance.name, enableFullSync);+ databaseStore.removeCacheByInstance(instance.name);+ },+ [instance.name, instanceStore, databaseStore]+ );++ // Database filter+ const envVal = getValueFromScopes(searchParams, "environment");+ const selectedEnvironment = envVal+ ? `${environmentNamePrefix}${envVal}`+ : undefined;+ const projectVal = getValueFromScopes(searchParams, "project");+ const selectedProject = projectVal+ ? `${projectNamePrefix}${projectVal}`+ : undefined;+ const selectedLabels = searchParams.scopes+ .filter((s) => s.id === "label")+ .map((s) => s.value);++ const filter: DatabaseFilter = useMemo(+ () => ({+ environment: selectedEnvironment,+ project: selectedProject,+ query: searchParams.query,+ labels: selectedLabels.length > 0 ? selectedLabels : undefined,+ }),+ [selectedEnvironment, selectedProject, searchParams.query, selectedLabels]+ );++ const scopeOptions: ScopeOption[] = useMemo(+ () => [+ {+ id: "environment",+ title: t("common.environment"),+ description: t("common.environment"),+ },+ {+ id: "project",+ title: t("common.project"),+ description: t("common.project"),+ },+ {+ id: "label",+ title: t("common.labels"),+ description: t("common.labels"),+ allowMultiple: true,+ },+ ],+ [t]+ );++ const handleTabChange = useCallback((tab: string | number | null) => {+ if (typeof tab === "string" && isInstanceHash(tab)) {+ setSelectedTab(tab);+ }+ }, []);++ const engineIconSrc = EngineIconPath[instance.engine];++ return (+ <div className="pt-4 flex flex-col gap-y-2 px-6">+ {/* Archive banner */}+ {instance.state === State.DELETED && (+ <div className="bg-gray-700 text-white text-center py-2 rounded-md text-sm font-medium">+ {t("common.archived")}+ </div>+ )}++ {/* No environment warning */}+ {!instance.environment && (+ <div className="w-full mb-4 rounded-md bg-yellow-50 border border-yellow-200 p-3 text-sm text-yellow-800">+ {t("instance.no-environment")}+ </div>+ )}++ {/* Header */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-x-2">+ {engineIconSrc && (+ <img src={engineIconSrc} alt="" className="h-6 w-6" />+ )}+ <span className="text-lg font-medium">+ {instanceV1Name(instance)}+ </span>+ </div>+ <div className="flex items-center gap-x-2">+ {instance.state === State.ACTIVE && (+ <InstanceSyncButton+ instanceName={instance.name}+ instanceTitle={instance.title}+ onSyncSchema={syncSchema}+ />+ )}+ <InstanceActionDropdown instance={instance} />+ </div>+ </div>++ {/* Tabs */}+ <Tabs value={selectedTab} onValueChange={handleTabChange}>+ <TabsList>+ <TabsTrigger value="overview">{t("common.overview")}</TabsTrigger>+ <TabsTrigger value="databases">{t("common.databases")}</TabsTrigger>+ <TabsTrigger value="users">{t("instance.users")}</TabsTrigger>+ </TabsList>++ <TabsPanel value="overview">+ <InstanceFormProvider instance={instance}>+ <div className="-mt-2">+ <InstanceFormBody />+ <InstanceFormButtons className="sticky bottom-0 z-10" />+ </div>+ </InstanceFormProvider>+ </TabsPanel>++ <TabsPanel value="databases">+ <div className="flex flex-col gap-y-2">+ <AdvancedSearch+ params={searchParams}+ onParamsChange={setSearchParams}+ placeholder={t("database.filter-database")}+ scopeOptions={scopeOptions}+ />+ <DatabaseTable filter={filter} parent={instance.name} mode="ALL" />+ </div>+ </TabsPanel>++ <TabsPanel value="users">+ <InstanceRoleTable instanceRoleList={instance.roles ?? []} />+ </TabsPanel>+ </Tabs>+ </div>+ );+}diff --git a/frontend/src/router/dashboard/instance.ts b/frontend/src/router/dashboard/instance.tsindex 0fcc3401c1..ca3f97d29f 100644--- a/frontend/src/router/dashboard/instance.ts+++ b/frontend/src/router/dashboard/instance.ts@@ -1,4 +1,4 @@-import type { RouteRecordRaw } from "vue-router";+import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";import InstanceLayout from "@/layouts/InstanceLayout.vue";import { t } from "@/plugins/i18n";import { INSTANCE_ROUTE_DASHBOARD } from "./workspaceRoutes";@@ -17,10 +17,12 @@ const instanceRoutes: RouteRecordRaw[] = [getQuickActionList: () => [],},components: {- content: () => import("@/views/CreateInstancePage.vue"),+ content: () => import("@/react/ReactPageMount.vue"),leftSidebar: () => import("@/react/ReactSidebarMount.vue"),},- props: { content: true },+ props: {+ content: () => ({ page: "CreateInstancePage" }),+ },},{path: "instances/:instanceId",@@ -39,8 +41,11 @@ const instanceRoutes: RouteRecordRaw[] = [meta: {requiredPermissionList: () => ["bb.instances.get"],},- component: () => import("@/views/InstanceDetail.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "InstanceDetailPage",+ instanceId: route.params.instanceId,+ }),},{path: "databases/:databaseName",diff --git a/frontend/src/views/CreateInstancePage.vue b/frontend/src/views/CreateInstancePage.vuedeleted file mode 100644index 8d5ee7e44c..0000000000--- a/frontend/src/views/CreateInstancePage.vue+++ /dev/null@@ -1,197 +0,0 @@-<template>- <div class="h-full overflow-hidden px-4 sm:px-6">- <div- ref="createInstanceLayoutRef"- class="grid h-full w-full min-h-0 min-w-0"- :style="createInstanceLayoutStyle"- @click.capture="handleDockedInfoPanelOutsideClick"- >- <div class="min-w-0 min-h-0 flex-1 flex flex-col">- <InstanceForm @dismiss="goBack">- <!-- Header -->- <div- class="sticky top-0 z-10 bg-white border-b border-block-border py-4"- >- <h1 class="text-lg font-medium">- {{ $t("quick-action.add-instance") }}- </h1>- </div>-- <!-- Body -->- <div class="flex-1 min-h-0 overflow-auto py-4">- <InstanceFormBody />- </div>-- <!-- Sticky footer -->- <div class="sticky bottom-0 z-10 bg-white">- <InstanceFormButtons />- </div>- </InstanceForm>- </div>-- <InfoPanel- :visible="showDockedInfoPanel"- mode="docked"- :title="infoPanelTitle"- @before-leave="handleDockedInfoPanelBeforeLeave"- @after-leave="handleDockedInfoPanelAfterLeave"- @close="activeInfoSection = undefined"- >- <InfoPanelContent- v-if="activeInfoSection"- :engine="currentEngine"- :section="activeInfoSection"- />- </InfoPanel>- </div>-- <InfoPanel- :visible="showOverlayInfoPanel"- mode="overlay"- :title="infoPanelTitle"- @close="activeInfoSection = undefined"- >- <InfoPanelContent- v-if="activeInfoSection"- :engine="currentEngine"- :section="activeInfoSection"- />- </InfoPanel>- </div>-</template>--<script lang="ts" setup>-import { useElementSize } from "@vueuse/core";-import { computed, onMounted, provide, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import {- InstanceForm,- Form as InstanceFormBody,- Buttons as InstanceFormButtons,-} from "@/components/InstanceForm/";-import InfoPanel from "@/components/InstanceForm/InfoPanel.vue";-import InfoPanelContent from "@/components/InstanceForm/InfoPanelContent.vue";-import type { InfoSection } from "@/components/InstanceForm/info-content";-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";-import {- pushNotification,- useActuatorV1Store,- useSubscriptionV1Store,-} from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";--const { t } = useI18n();-const router = useRouter();-const subscriptionStore = useSubscriptionV1Store();-const actuatorStore = useActuatorV1Store();--const MIN_DOCKED_MAIN_WIDTH = 700;-const DOCKED_INFO_RAIL_WIDTH = 500;-const DOCKED_INFO_RAIL_GAP = 16;-const MIN_DOCKED_LAYOUT_WIDTH =- MIN_DOCKED_MAIN_WIDTH + DOCKED_INFO_RAIL_WIDTH + DOCKED_INFO_RAIL_GAP;--const activeInfoSection = ref<InfoSection | undefined>();-const currentEngine = ref<Engine>(Engine.MYSQL);-const isDockedInfoPanelLeaving = ref(false);-const createInstanceLayoutRef = ref<HTMLElement>();-const { width: createInstanceLayoutWidth } = useElementSize(- createInstanceLayoutRef-);-const canUseDockedInfoLayout = computed(- () => createInstanceLayoutWidth.value >= MIN_DOCKED_LAYOUT_WIDTH-);-const showDockedInfoPanel = computed(- () => !!activeInfoSection.value && canUseDockedInfoLayout.value-);-const showOverlayInfoPanel = computed(- () => !!activeInfoSection.value && !canUseDockedInfoLayout.value-);-const keepDockedLayout = computed(- () => showDockedInfoPanel.value || isDockedInfoPanelLeaving.value-);-const createInstanceLayoutStyle = computed(() => {- if (!canUseDockedInfoLayout.value || !keepDockedLayout.value) {- return {- gridTemplateColumns: "minmax(0, 1fr)",- columnGap: "0rem",- };- }-- return {- gridTemplateColumns: `minmax(${MIN_DOCKED_MAIN_WIDTH}px, 1fr) ${DOCKED_INFO_RAIL_WIDTH}px`,- columnGap: `${DOCKED_INFO_RAIL_GAP}px`,- };-});--const handleDockedInfoPanelBeforeLeave = () => {- isDockedInfoPanelLeaving.value = true;-};--const handleDockedInfoPanelAfterLeave = () => {- isDockedInfoPanelLeaving.value = false;-};--const handleDockedInfoPanelOutsideClick = (event: MouseEvent) => {- if (!showDockedInfoPanel.value) {- return;- }-- const target = event.target;- if (!(target instanceof Element)) {- return;- }-- if (target.closest("[data-info-panel-docked='true']")) {- return;- }-- activeInfoSection.value = undefined;-};--const infoPanelTitle = computed(() => {- if (!activeInfoSection.value) return "";- const titleMap: Record<InfoSection, string> = {- host: t("instance.host-or-socket"),- port: t("instance.port"),- authentication: t("instance.connection-info"),- ssl: t("data-source.ssl-connection"),- ssh: t("data-source.ssh-connection"),- database: t("common.database"),- };- return titleMap[activeInfoSection.value] ?? "";-});--provide("infoPanel", {- open: (section: InfoSection) => {- activeInfoSection.value = section;- },- close: () => {- activeInfoSection.value = undefined;- },- setEngine: (engine: Engine) => {- currentEngine.value = engine;- },-});--const goBack = () => {- router.push({ name: INSTANCE_ROUTE_DASHBOARD });-};--onMounted(() => {- if (- subscriptionStore.instanceCountLimit <= actuatorStore.activatedInstanceCount- ) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("subscription.usage.instance-count.title"),- description: t("subscription.usage.instance-count.runoutof", {- total: subscriptionStore.instanceCountLimit,- }),- });- goBack();- }-});-</script>diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vuedeleted file mode 100644index 9f77a40185..0000000000--- a/frontend/src/views/InstanceDetail.vue+++ /dev/null@@ -1,228 +0,0 @@-<template>- <div class="pt-4 flex flex-col gap-y-2 px-6" v-bind="$attrs">- <ArchiveBanner v-if="instance.state === State.DELETED" />- <BBAttention- v-if="!instance.environment"- class="w-full mb-4"- :type="'warning'"- >- {{ $t("instance.no-environment") }}- </BBAttention>-- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-2">- <EngineIcon :engine="instance.engine" custom-class="h-6!" />- <span class="text-lg font-medium">{{ instanceV1Name(instance) }}</span>- </div>- <div class="flex items-center gap-x-2">- <InstanceSyncButton- v-if="instance.state === State.ACTIVE"- :instance-name="instance.name"- :instance-title="instance.title"- @sync-schema="syncSchema"- />- <InstanceActionDropdown :instance="instance" />- </div>- </div>-- <NTabs :value="state.selectedTab" @update:value="onTabChange">- <NTabPane name="overview" :tab="$t('common.overview')">- <InstanceForm ref="instanceFormRef" class="-mt-2" :instance="instance">- <InstanceFormBody />- <InstanceFormButtons class="sticky bottom-0 z-10" />- </InstanceForm>- </NTabPane>- <NTabPane name="databases" :tab="$t('common.databases')">- <div class="flex flex-col gap-y-2">- <AdvancedSearch- v-model:params="state.params"- :autofocus="false"- :placeholder="$t('database.filter-database')"- :scope-options="scopeOptions"- />- <PagedDatabaseTable- ref="pagedDatabaseTableRef"- mode="INSTANCE"- :footer-class="'pb-4'"- :show-selection="false"- :filter="filter"- :parent="instance.name"- />- </div>- </NTabPane>- <NTabPane name="users" :tab="$t('instance.users')">- <InstanceRoleTable :instance-role-list="instanceRoleList" />- </NTabPane>- </NTabs>- </div>--</template>--<script lang="tsx" setup>-import { cloneDeep } from "lodash-es";-import { NTabPane, NTabs } from "naive-ui";-import { computed, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute, useRouter } from "vue-router";-import { BBAttention } from "@/bbkit";-import AdvancedSearch from "@/components/AdvancedSearch";-import { useCommonSearchScopeOptions } from "@/components/AdvancedSearch/useCommonSearchScopeOptions";-import ArchiveBanner from "@/components/ArchiveBanner.vue";-import { EngineIcon } from "@/components/Icon";-import InstanceActionDropdown from "@/components/Instance/InstanceActionDropdown.vue";-import InstanceSyncButton from "@/components/Instance/InstanceSyncButton.vue";-import {- InstanceForm,- Form as InstanceFormBody,- Buttons as InstanceFormButtons,-} from "@/components/InstanceForm/";-import { InstanceRoleTable } from "@/components/v2";-import { PagedDatabaseTable } from "@/components/v2/Model/DatabaseV1Table";-import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";-import { useDatabaseV1Store, useInstanceV1Store } from "@/store";-import {- environmentNamePrefix,- instanceNamePrefix,- projectNamePrefix,-} from "@/store/modules/v1/common";-import { State } from "@/types/proto-es/v1/common_pb";-import type { SearchParams, SearchScope } from "@/utils";-import {- CommonFilterScopeIdList,- getValueFromSearchParams,- getValuesFromSearchParams,- instanceV1Name,- setDocumentTitle,-} from "@/utils";--const instanceHashList = ["overview", "databases", "users"] as const;-export type InstanceHash = (typeof instanceHashList)[number];-const isInstanceHash = (x: unknown): x is InstanceHash =>- instanceHashList.includes(x as InstanceHash);--interface LocalState {- syncingSchema: boolean;- params: SearchParams;- selectedTab: InstanceHash;-}--const props = defineProps<{- instanceId: string;-}>();--defineOptions({- inheritAttrs: false,-});--const { t } = useI18n();-const router = useRouter();-const instanceV1Store = useInstanceV1Store();-const databaseStore = useDatabaseV1Store();-const pagedDatabaseTableRef = ref<InstanceType<typeof PagedDatabaseTable>>();-const instanceFormRef = ref<InstanceType<typeof InstanceForm>>();--const onTabChange = (tab: InstanceHash) => {- if (instanceFormRef.value?.isEditing) {- if (!window.confirm(t("common.leave-without-saving"))) {- return;- }- }- state.selectedTab = tab;-};--useRouteChangeGuard(computed(() => instanceFormRef.value?.isEditing ?? false));--const readonlyScopes = computed((): SearchScope[] => [- { id: "instance", value: props.instanceId, readonly: true },-]);--const state = reactive<LocalState>({- syncingSchema: false,- params: {- query: "",- scopes: [...readonlyScopes.value],- },- selectedTab: "overview",-});--const route = useRoute();--const scopeOptions = useCommonSearchScopeOptions([- ...CommonFilterScopeIdList,- "project",- "label",-]);--watch(- () => route.hash,- (hash) => {- const targetHash = hash.replace(/^#?/g, "") as InstanceHash;- if (isInstanceHash(targetHash)) {- state.selectedTab = targetHash;- }- },- { immediate: true }-);--watch(- () => state.selectedTab,- (tab) => {- const query = cloneDeep(route.query);- delete query["qs"];- router.replace({- query,- hash: `#${tab}`,- });- },- { immediate: true }-);--const instance = computed(() => {- return instanceV1Store.getInstanceByName(- `${instanceNamePrefix}${props.instanceId}`- );-});--const selectedEnvironment = computed(() => {- return getValueFromSearchParams(- state.params,- "environment",- environmentNamePrefix- );-});--const selectedProject = computed(() => {- return getValueFromSearchParams(state.params, "project", projectNamePrefix);-});--const selectedLabels = computed(() => {- return getValuesFromSearchParams(state.params, "label");-});--const filter = computed(() => ({- environment: selectedEnvironment.value,- project: selectedProject.value,- query: state.params.query,- labels: selectedLabels.value,-}));--const instanceRoleList = computed(() => {- return instance.value.roles;-});--const syncSchema = async (enableFullSync: boolean) => {- await instanceV1Store.syncInstance(instance.value.name, enableFullSync);- // Remove the database list cache for the instance.- databaseStore.removeCacheByInstance(instance.value.name);- // Note: Notification is now handled by InstanceSyncButton component- // which shows an honest "syncing" message and checks for errors after 30 seconds-};--watch(- () => instance.value.title,- (title) => {- setDocumentTitle(title);- },- { immediate: true }-);-</script>