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: code split (#12214)
Liu Ji6f44c9cd9d06
diff --git a/frontend/src/components/InstanceForm/Buttons.vue b/frontend/src/components/InstanceForm/Buttons.vuenew file mode 100644index 0000000000..90d9bf7415--- /dev/null+++ b/frontend/src/components/InstanceForm/Buttons.vue@@ -0,0 +1,494 @@+<template>+ <template v-if="isCreating">+ <div class="w-full flex justify-between items-center" v-bind="$attrs">+ <div class="w-full flex justify-end items-center gap-x-3">+ <NButton+ :disabled="state.isRequesting || state.isTestingConnection"+ @click.prevent="cancel"+ >+ {{ $t("common.cancel") }}+ </NButton>+ <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>+ <NButton+ :disabled="+ !allowUpdate || state.isRequesting || state.isTestingConnection+ "+ :loading="state.isRequesting"+ type="primary"+ @click.prevent="doUpdate"+ >+ {{ $t("common.confirm-and-update") }}+ </NButton>+ </div>+ </template>+</template>++<script setup lang="ts">+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 {+ useInstanceV1Store,+ useSubscriptionV1Store,+ useGracefulRequest,+ useDatabaseV1Store,+ pushNotification,+} from "@/store";+import { Engine } from "@/types/proto/v1/common";+import {+ DataSource,+ DataSourceType,+ Instance,+} from "@/types/proto/v1/instance_service";+import { isValidSpannerHost, defer } from "@/utils";+import ScanIntervalInput from "./ScanIntervalInput.vue";+import {+ calcDataSourceUpdateMask,+ extractBasicInfo,+ extractDataSourceEditState,+ type EditDataSource,+} from "./common";+import { useInstanceFormContext } from "./context";++const context = useInstanceFormContext();+const {+ $d,+ events,+ state,+ instance,+ isCreating,+ allowEdit,+ allowCreate,+ basicInfo,+ adminDataSource,+ readonlyDataSourceList,+ dataSourceEditState,+ hasReadonlyReplicaFeature,+ missingFeature,+ testConnection,+ checkDataSource,+ extractDataSourceFromEdit,+} = context;++const router = useRouter();+const { t } = useI18n();+const instanceV1Store = useInstanceV1Store();+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 valueChanged = computed(() => {+ const original = getOriginalEditState();+ const editing = {+ basicInfo: basicInfo.value,+ dataSources: dataSourceEditState.value.dataSources,+ };+ return !isEqual(editing, original);+});++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 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 {+ const confirmed = await confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (confirmed) {+ doCreate();+ }+ }+};++const hasExternalSecretFeature = computed(() =>+ subscriptionStore.hasFeature("bb.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, 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);+};++// 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;+ }+ const instanceCreate: Instance = {+ ...basicInfo.value,+ engineVersion: "",+ dataSources: [],+ };+ const adminDataSourceCreate = extractDataSourceFromEdit(+ instanceCreate,+ adminDataSource.value+ );+ instanceCreate.dataSources = [adminDataSourceCreate];++ if (!checkExternalSecretFeature(instanceCreate.dataSources)) {+ missingFeature.value = "bb.feature.external-secret-manager";+ return;+ }++ state.value.isRequesting = true;+ try {+ await useGracefulRequest(async () => {+ const createdInstance =+ await instanceV1Store.createInstance(instanceCreate);+ useDatabaseV1Store().searchDatabases({+ filter: `instance = "${createdInstance.name}"`,+ });+ router.push(`/${createdInstance.name}`);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(+ "instance.successfully-created-instance-createdinstance-name",+ [createdInstance.title]+ ),+ });+ });+ } finally {+ state.value.isRequesting = false;+ events.emit("dismiss");+ }+};++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;+ }++ // Backend will sync the schema when connection info changed, so we need to fetch the synced schema here.+ instanceV1Store.fetchInstanceRoleListByName(instance.name);+};++const doUpdate = async () => {+ const inst = instance.value;+ if (!inst) {+ return;+ }+ if (!checkRODataSourceFeature(inst)) {+ missingFeature.value = "bb.feature.read-replica-connection";+ return;+ }++ if (!checkExternalSecretFeature([adminDataSource.value])) {+ missingFeature.value = "bb.feature.external-secret-manager";+ return;+ }++ if (+ !checkExternalSecretFeature([+ adminDataSource.value,+ ...readonlyDataSourceList.value,+ ])+ ) {+ missingFeature.value = "bb.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<any>)[] = [];++ const maybeQueueUpdateInstanceBasicInfo = () => {+ const instancePatch = Instance.fromPartial({+ ...instance,+ ...basicInfo.value,+ });+ 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 (+ instancePatch.options?.syncInterval?.seconds?.toNumber() !==+ inst.options?.syncInterval?.seconds?.toNumber()+ ) {+ updateMask.push("options.sync_interval");+ }+ if (+ instancePatch.options?.maximumConnections !==+ inst.options?.maximumConnections+ ) {+ updateMask.push("options.maximum_connections");+ }+ if (updateMask.length === 0) {+ return;+ }+ pendingRequestRunners.push(() =>+ instanceV1Store.updateInstance(instancePatch, updateMask)+ );+ };+ /**+ * @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) {+ const continueAnyway = await confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (!continueAnyway) {+ return true;+ }+ }++ pendingRequestRunners.push(() =>+ instanceV1Store.updateDataSource(inst, editing, updateMask)+ );+ };+ const maybeQueueUpdateAdminDataSource = async () => {+ const original = inst.dataSources.find(+ (ds) => ds.type === DataSourceType.ADMIN+ );+ const editing = extractDataSourceFromEdit(inst, 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, editing);+ if (editing.pendingCreate) {+ const testResult = await testConnection(editing, /* silent */ true);+ if (!testResult.success) {+ const continueAnyway = await confirmContinueWithConnectionFailure(+ testResult.message+ );+ if (!continueAnyway) {+ return true;+ }+ }++ pendingRequestRunners.push(() =>+ instanceV1Store.createDataSource(inst, 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,+ ]),+ });+ } finally {+ state.value.isRequesting = false;+ }+};++const cancel = () => {+ events.emit("dismiss");+};+</script>diff --git a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vueindex 19111bd4ca..c689818036 100644--- a/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue+++ b/frontend/src/components/InstanceForm/DataSourceSection/DataSourceForm.vue@@ -744,7 +744,6 @@ import {import { onlyAllowNumber } from "@/utils";import type { EditDataSource } from "../common";import { useInstanceFormContext } from "../context";-import { useInstanceSpecs } from "../specs";import GcpCredentialInput from "./GcpCredentialInput.vue";import SshConnectionForm from "./SshConnectionForm.vue";import SslCertificateForm from "./SslCertificateForm.vue";@@ -759,6 +758,7 @@ const props = defineProps<{const {instance,+ specs,isCreating,allowEdit,basicInfo,@@ -775,7 +775,7 @@ const {showAuthenticationDatabase,hasReadonlyReplicaHost,hasReadonlyReplicaPort,-} = useInstanceSpecs();+} = specs;const state = reactive<LocalState>({passwordType: DataSourceExternalSecret_SecretType.SAECRET_TYPE_UNSPECIFIED,diff --git a/frontend/src/components/InstanceForm/Form.vue b/frontend/src/components/InstanceForm/Form.vuenew file mode 100644index 0000000000..e55c4fc316--- /dev/null+++ b/frontend/src/components/InstanceForm/Form.vue@@ -0,0 +1,665 @@+<template>+ <div class="space-y-6">+ <div class="divide-y divide-block-border w-[850px]">+ <InstanceEngineRadioGrid+ v-if="isCreating"+ :engine="basicInfo.engine"+ :engine-list="EngineList"+ class="w-full mb-6 grid-cols-4 gap-2"+ @update:engine="changeInstanceEngine"+ >+ <template #suffix="{ engine }: { engine: Engine }">+ <BBBetaBadge+ v-if="isEngineBeta(engine)"+ class="absolute -top-1.5 -right-1 rounded text-xs !bg-gray-500 px-1 !py-0 z-10"+ />+ </template>+ </InstanceEngineRadioGrid>++ <!-- Instance Name -->+ <div class="pt-4 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") }}+ <span class="text-red-600 ml-0.5">*</span>+ <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"+ :disabled="!allowEdit"+ />+ </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="{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }"+ class="accent-link"+ >+ {{+ $t("subscription.instance-assignment.n-license-remain", {+ n: availableLicenseCountText,+ })+ }}</router-link+ >)+ </label>+ <div class="h-[34px] 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"+ :validate="validateResourceId"+ />+ </div>++ <div class="sm:col-span-2 sm:col-start-1">+ <label for="environment" class="textlabel">+ {{ $t("common.environment") }}+ </label>+ <span class="text-red-600 ml-0.5">*</span>+ <EnvironmentSelect+ class="mt-1 w-full"+ required="true"+ :environment="+ environment.uid === String(UNKNOWN_ID)+ ? undefined+ : environment.uid+ "+ :disabled="!allowEdit"+ @update:environment="handleSelectEnvironmentUID"+ />+ </div>++ <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-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") }}+ <span class="text-red-600 mr-2">*</span>+ <LearnMoreLink+ url="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier"+ class="text-sm"+ />+ </template>+ <div+ v-else-if="+ adminDataSource.authenticationType ===+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM+ "+ >+ <span>+ {{ $t("instance.sentence.google-cloud-sql.instance-name") }}+ <span class="text-red-600 mr-2">*</span>+ </span>+ <div class="textinfolabel mb-1">+ {{+ $t("instance.sentence.google-cloud-sql.instance-name-tips")+ }}+ </div>+ </div>+ <template v-else>+ {{ $t("instance.host-or-socket") }}+ <span+ v-if="basicInfo.engine !== Engine.DYNAMODB"+ class="text-red-600 mr-2"+ >*</span+ >+ </template>+ </label>+ <NInput+ v-model:value="adminDataSource.host"+ required+ :placeholder="+ basicInfo.engine === Engine.SNOWFLAKE+ ? $t('instance.your-snowflake-account-locator')+ : $t('instance.sentence.host.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 &&+ 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"+ >+ <span class="textlabel">{{ type }}</span>+ </NRadio>+ </NRadioGroup>+ </div>++ <div+ v-if="basicInfo.engine === Engine.MONGODB && !adminDataSource.srv"+ 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="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 flex flex-row items-center"+ >+ {{ $t("instance.host-or-socket") }}+ </label>+ <NInput+ v-model:value="+ adminDataSource.additionalAddresses[index].host+ "+ required+ :placeholder="$t('instance.sentence.host.snowflake')"+ class="mt-1 w-full"+ :disabled="!allowEdit"+ />+ </div>+ <div class="sm:col-span-3">+ <label+ v-if="index === 0"+ for="additionalAddressesPort"+ class="textlabel 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-[34px] 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="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>++ <ScanIntervalInput+ v-if="!isCreating"+ ref="scanIntervalInputRef"+ :scan-interval="basicInfo.options?.syncInterval"+ :allow-edit="allowEdit"+ @update:scan-interval="changeScanInterval"+ />++ <MaximumConnectionsInput+ v-if="!isCreating"+ ref="maximumConnectionsInputRef"+ :maximum-connections="basicInfo.options?.maximumConnections ?? 0"+ :allow-edit="allowEdit"+ @update:maximum-connections="changeMaximumConnections"+ />++ <!--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 class>+ {{+ basicInfo.engine === Engine.SNOWFLAKE+ ? $t("instance.snowflake-web-console")+ : $t("instance.external-link")+ }}+ </span>+ <button+ class="ml-1 btn-icon"+ :disabled="instanceLink.trim().length === 0"+ @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>+ </div>++ <!-- Connection Info -->+ <template v-if="basicInfo.engine !== Engine.DYNAMODB">+ <p class="mt-6 pt-4 w-full text-lg leading-6 font-medium text-gray-900">+ {{ $t("instance.connection-info") }}+ </p>++ <DataSourceSection />+ </template>++ <BBAttention+ v-if="outboundIpList && actuatorStore.isSaaSMode"+ class="my-4 border-none"+ type="info"+ :title="$t('instance.sentence.outbound-ip-list')"+ :description="outboundIpList"+ />++ <div class="mt-6 pt-0 border-none">+ <div class="flex flex-row space-x-2">+ <NButton+ class="whitespace-nowrap flex items-center"+ :loading="state.isTestingConnection"+ :disabled="!allowCreate || state.isRequesting || !allowEdit"+ @click.prevent="testConnectionForCurrentEditingDS"+ >+ <span>{{ $t("instance.test-connection") }}</span>+ </NButton>+ </div>+ </div>+ </div>++ <InstanceArchiveRestoreButton+ v-if="!isCreating && instance"+ :instance="instance as ComposedInstance"+ />+ </div>+</template>++<script setup lang="ts">+import { TrashIcon } from "lucide-vue-next";+import {+ NButton,+ NInput,+ NSwitch,+ NRadioGroup,+ NRadio,+ NCheckbox,+} from "naive-ui";+import { Status } from "nice-grpc-common";+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { InstanceArchiveRestoreButton } from "@/components/Instance";+import {+ EnvironmentSelect,+ InstanceEngineRadioGrid,+ InstanceV1EngineIcon,+ MiniActionButton,+} from "@/components/v2";+import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";+import { SETTING_ROUTE_WORKSPACE_SUBSCRIPTION } from "@/router/dashboard/workspaceSetting";+import {+ useSettingV1Store,+ useActuatorV1Store,+ useEnvironmentV1Store,+ useInstanceV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { instanceNamePrefix } from "@/store/modules/v1/common";+import type { ResourceId, ValidatedMessage, ComposedInstance } from "@/types";+import { UNKNOWN_ID } from "@/types";+import type { Duration } from "@/types/proto/google/protobuf/duration";+import { Engine } from "@/types/proto/v1/common";+import {+ InstanceOptions,+ DataSource_AuthenticationType,+} from "@/types/proto/v1/instance_service";+import { PlanType } from "@/types/proto/v1/subscription_service";+import { isDev, extractInstanceResourceName, onlyAllowNumber } from "@/utils";+import { getErrorCode } from "@/utils/grpcweb";+import BigQueryHostInput from "./BigQueryHostInput.vue";+import DataSourceSection from "./DataSourceSection/DataSourceSection.vue";+import ScanIntervalInput from "./ScanIntervalInput.vue";+import SpannerHostInput from "./SpannerHostInput.vue";+import {+ MongoDBConnectionStringSchemaList,+ SnowflakeExtraLinkPlaceHolder,+ EngineList,+} from "./constants";+import { useInstanceFormContext } from "./context";++const context = useInstanceFormContext();+const {+ state,+ specs,+ instance,+ environment,+ isCreating,+ allowEdit,+ allowCreate,+ resourceIdField,+ basicInfo,+ adminDataSource,+ editingDataSource,+ testConnection,+} = context;+const { isEngineBeta, defaultPort, instanceLink, allowEditPort } = specs;++const { t } = useI18n();+const instanceV1Store = useInstanceV1Store();+const settingV1Store = useSettingV1Store();+const actuatorStore = useActuatorV1Store();+const subscriptionStore = useSubscriptionV1Store();+const scanIntervalInputRef = ref<InstanceType<typeof ScanIntervalInput>>();++const availableLicenseCount = computed(() => {+ return Math.max(+ 0,+ subscriptionStore.instanceLicenseCount -+ instanceV1Store.activateInstanceCount+ );+});++const availableLicenseCountText = computed((): string => {+ if (subscriptionStore.instanceLicenseCount === Number.MAX_VALUE) {+ return t("subscription.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 outboundIpList = computed(() => {+ if (!settingV1Store.workspaceProfileSetting) {+ return "";+ }+ return settingV1Store.workspaceProfileSetting.outboundIpList.join(",");+});++// 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();+ if (+ engine === Engine.SNOWFLAKE ||+ engine === Engine.SPANNER ||+ engine === Engine.BIGQUERY ||+ engine === Engine.DYNAMODB+ ) {+ if (+ adminDataSource.value.host === "127.0.0.1" ||+ adminDataSource.value.host === "host.docker.internal"+ ) {+ adminDataSource.value.host = "";+ }+ } else {+ if (!adminDataSource.value.host) {+ adminDataSource.value.host = isDev()+ ? "127.0.0.1"+ : "host.docker.internal";+ }+ }+ basicInfo.value.engine = engine;+};++const changeScanInterval = (duration: Duration | undefined) => {+ if (!basicInfo.value.options) {+ basicInfo.value.options = InstanceOptions.fromPartial({});+ }+ basicInfo.value.options.syncInterval = duration;+};+const changeMaximumConnections = (maximumConnections: number) => {+ if (!basicInfo.value.options) {+ basicInfo.value.options = InstanceOptions.fromPartial({});+ }+ basicInfo.value.options.maximumConnections = maximumConnections;+};++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({+ host: "",+ port: "",+ });+ if (adminDataSource.value.additionalAddresses.length !== 0) {+ adminDataSource.value.directConnection = false;+ }+};++const validateResourceId = async (+ resourceId: ResourceId+): Promise<ValidatedMessage[]> => {+ if (!resourceId) {+ return [];+ }++ try {+ const instance = await instanceV1Store.getOrFetchInstanceByName(+ instanceNamePrefix + resourceId,+ true /* silent */+ );+ if (instance) {+ return [+ {+ type: "error",+ message: t("resource-id.validation.duplicated", {+ resource: t("resource.instance"),+ }),+ },+ ];+ }+ } catch (error) {+ if (getErrorCode(error) !== Status.NOT_FOUND) {+ throw error;+ }+ }+ return [];+};++const changeInstanceActivation = async (on: boolean) => {+ basicInfo.value.activation = on;+ if (instance.value) {+ const instancePatch = {+ ...instance.value,+ activation: on,+ };+ await instanceV1Store.updateInstance(instancePatch, ["activation"]);+ }+};++const handleSelectEnvironmentUID = (uid: string | undefined) => {+ if (!uid) return;+ const environment = useEnvironmentV1Store().getEnvironmentByUID(uid);+ basicInfo.value.environment = environment.name;+};++const testConnectionForCurrentEditingDS = () => {+ const editingDS = editingDataSource.value;+ if (!editingDS) return;+ testConnection(editingDS, /* !silent */ false);+};+</script>++<style lang="postcss" scoped>+.instance-engine-button :deep(.n-button__content) {+ @apply w-full justify-start;+}+</style>diff --git a/frontend/src/components/InstanceForm/InstanceForm.vue b/frontend/src/components/InstanceForm/InstanceForm.vueindex 480ef4a145..4bb8805286 100644--- a/frontend/src/components/InstanceForm/InstanceForm.vue+++ b/frontend/src/components/InstanceForm/InstanceForm.vue@@ -1,479 +1,5 @@<template>- <component- :is="drawer ? DrawerContent : 'div'"- v-bind="{- ...$attrs,- ...bindings,- }"- >- <div class="space-y-6">- <div class="divide-y divide-block-border w-[850px]">- <InstanceEngineRadioGrid- v-if="isCreating"- :engine="basicInfo.engine"- :engine-list="EngineList"- class="w-full mb-6 grid-cols-4 gap-2"- @update:engine="changeInstanceEngine"- >- <template #suffix="{ engine }: { engine: Engine }">- <BBBetaBadge- v-if="isEngineBeta(engine)"- class="absolute -top-1.5 -right-1 rounded text-xs !bg-gray-500 px-1 !py-0 z-10"- />- </template>- </InstanceEngineRadioGrid>-- <!-- Instance Name -->- <div class="pt-4 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") }}- <span class="text-red-600 ml-0.5">*</span>- <div v-if="props.instance" class="ml-2 flex items-center">- <InstanceV1EngineIcon- :instance="props.instance"- :tooltip="false"- />- <span class="ml-1">{{ props.instance.engineVersion }}</span>- </div>- </label>- <NInput- v-model:value="basicInfo.title"- required- class="mt-1 w-full"- :disabled="!allowEdit"- />- </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="{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }"- class="accent-link"- >- {{- $t("subscription.instance-assignment.n-license-remain", {- n: availableLicenseCountText,- })- }}</router-link- >)- </label>- <div class="h-[34px] 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"- :validate="validateResourceId"- />- </div>-- <div class="sm:col-span-2 sm:col-start-1">- <label for="environment" class="textlabel">- {{ $t("common.environment") }}- </label>- <span class="text-red-600 ml-0.5">*</span>- <EnvironmentSelect- class="mt-1 w-full"- required="true"- :environment="- environment.uid === String(UNKNOWN_ID)- ? undefined- : environment.uid- "- :disabled="!allowEdit"- @update:environment="handleSelectEnvironmentUID"- />- </div>-- <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-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") }}- <span class="text-red-600 mr-2">*</span>- <LearnMoreLink- url="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier"- class="text-sm"- />- </template>- <div- v-else-if="- adminDataSource.authenticationType ===- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM- "- >- <span>- {{ $t("instance.sentence.google-cloud-sql.instance-name") }}- <span class="text-red-600 mr-2">*</span>- </span>- <div class="textinfolabel mb-1">- {{- $t(- "instance.sentence.google-cloud-sql.instance-name-tips"- )- }}- </div>- </div>- <template v-else>- {{ $t("instance.host-or-socket") }}- <span- v-if="basicInfo.engine !== Engine.DYNAMODB"- class="text-red-600 mr-2"- >*</span- >- </template>- </label>- <NInput- v-model:value="adminDataSource.host"- required- :placeholder="- basicInfo.engine === Engine.SNOWFLAKE- ? $t('instance.your-snowflake-account-locator')- : $t('instance.sentence.host.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 &&- 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"- >- <span class="textlabel">{{ type }}</span>- </NRadio>- </NRadioGroup>- </div>-- <div- v-if="basicInfo.engine === Engine.MONGODB && !adminDataSource.srv"- 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="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 flex flex-row items-center"- >- {{ $t("instance.host-or-socket") }}- </label>- <NInput- v-model:value="- adminDataSource.additionalAddresses[index].host- "- required- :placeholder="$t('instance.sentence.host.snowflake')"- class="mt-1 w-full"- :disabled="!allowEdit"- />- </div>- <div class="sm:col-span-3">- <label- v-if="index === 0"- for="additionalAddressesPort"- class="textlabel 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-[34px] 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="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>-- <ScanIntervalInput- v-if="!isCreating"- ref="scanIntervalInputRef"- :scan-interval="basicInfo.options?.syncInterval"- :allow-edit="allowEdit"- @update:scan-interval="changeScanInterval"- />-- <MaximumConnectionsInput- v-if="!isCreating"- ref="maximumConnectionsInputRef"- :maximum-connections="basicInfo.options?.maximumConnections ?? 0"- :allow-edit="allowEdit"- @update:maximum-connections="changeMaximumConnections"- />-- <!--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 class>- {{- basicInfo.engine === Engine.SNOWFLAKE- ? $t("instance.snowflake-web-console")- : $t("instance.external-link")- }}- </span>- <button- class="ml-1 btn-icon"- :disabled="instanceLink.trim().length === 0"- @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>- </div>-- <!-- Connection Info -->- <template v-if="basicInfo.engine !== Engine.DYNAMODB">- <p- class="mt-6 pt-4 w-full text-lg leading-6 font-medium text-gray-900"- >- {{ $t("instance.connection-info") }}- </p>-- <DataSourceSection />- </template>-- <BBAttention- v-if="outboundIpList && actuatorStore.isSaaSMode"- class="my-4 border-none"- type="info"- :title="$t('instance.sentence.outbound-ip-list')"- :description="outboundIpList"- />-- <div class="mt-6 pt-0 border-none">- <div class="flex flex-row space-x-2">- <NButton- class="whitespace-nowrap flex items-center"- :loading="state.isTestingConnection"- :disabled="!allowCreate || state.isRequesting || !allowEdit"- @click.prevent="testConnectionForCurrentEditingDS"- >- <span>{{ $t("instance.test-connection") }}</span>- </NButton>- </div>- </div>- </div>-- <!-- Action Button Group -->- <template v-if="!drawer">- <InstanceArchiveRestoreButton- v-if="!isCreating && instance"- :instance="instance as ComposedInstance"- />-- <div- v-if="valueChanged && allowEdit"- class="w-full mt-4 py-4 border-t border-block-border flex justify-between bg-white sticky -bottom-4 z-10"- >- <NButton- :disabled="state.isTestingConnection"- @click.prevent="resetChanges"- >- <span> {{ $t("common.cancel") }}</span>- </NButton>- <NButton- :disabled="- !allowUpdate || state.isRequesting || state.isTestingConnection- "- :loading="state.isRequesting"- type="primary"- @click.prevent="doUpdate"- >- {{ $t("common.confirm-and-update") }}- </NButton>- </div>- </template>- </div>-- <template v-if="drawer" #footer>- <div class="w-full flex justify-between items-center">- <div class="w-full flex justify-end items-center gap-x-3">- <NButton- :disabled="state.isRequesting || state.isTestingConnection"- @click.prevent="cancel"- >- {{ $t("common.cancel") }}- </NButton>- <NButton- :disabled="- !allowCreate || state.isRequesting || state.isTestingConnection- "- :loading="state.isRequesting"- type="primary"- @click.prevent="tryCreate"- >- {{ $t("common.create") }}- </NButton>- </div>- </div>- </template>- </component>+ <slot /><FeatureModalv-if="missingFeature"@@ -485,183 +11,29 @@</template><script lang="ts" setup>-import { cloneDeep, isEqual, omit } from "lodash-es";-import { TrashIcon } from "lucide-vue-next";-import {- NButton,- NInput,- NSwitch,- NRadioGroup,- NRadio,- NCheckbox,- useDialog,-} from "naive-ui";-import { Status } from "nice-grpc-common";-import { computed, reactive, ref, watch, onMounted, toRef } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { InstanceArchiveRestoreButton } from "@/components/Instance";-import {- DrawerContent,- EnvironmentSelect,- InstanceEngineRadioGrid,- InstanceV1EngineIcon,- MiniActionButton,-} from "@/components/v2";-import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";-import { instanceServiceClient } from "@/grpcweb";-import { SETTING_ROUTE_WORKSPACE_SUBSCRIPTION } from "@/router/dashboard/workspaceSetting";-import {- pushNotification,- useSettingV1Store,- useActuatorV1Store,- useEnvironmentV1Store,- useInstanceV1Store,- useSubscriptionV1Store,- useGracefulRequest,- useCurrentUserV1,- useDatabaseV1Store,-} from "@/store";-import { instanceNamePrefix } from "@/store/modules/v1/common";-import type { ResourceId, ValidatedMessage, ComposedInstance } from "@/types";-import { UNKNOWN_ID, unknownEnvironment } from "@/types";-import type { Duration } from "@/types/proto/google/protobuf/duration";+import { watch, onMounted, toRef } from "vue";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";+import { useSettingV1Store } from "@/store";import { Engine } from "@/types/proto/v1/common";-import { Instance, type DataSource } from "@/types/proto/v1/instance_service";-import {- DataSourceType,- InstanceOptions,- DataSourceExternalSecret_SecretType,- DataSourceExternalSecret_AuthType,- DataSource_AuthenticationType,-} from "@/types/proto/v1/instance_service";-import { PlanType } from "@/types/proto/v1/subscription_service";-import {- isDev,- isValidSpannerHost,- extractInstanceResourceName,- calcUpdateMask,- onlyAllowNumber,- hasWorkspacePermissionV2,- defer,-} from "@/utils";-import { extractGrpcErrorMessage, getErrorCode } from "@/utils/grpcweb";-import BigQueryHostInput from "./BigQueryHostInput.vue";-import DataSourceSection from "./DataSourceSection/DataSourceSection.vue";-import ScanIntervalInput from "./ScanIntervalInput.vue";-import SpannerHostInput from "./SpannerHostInput.vue";-import type { EditDataSource } from "./common";-import { extractBasicInfo, extractDataSourceEditState } from "./common";-import {- MongoDBConnectionStringSchemaList,- SnowflakeExtraLinkPlaceHolder,- defaultPortForEngine,- EngineList,-} from "./constants";+import { Instance } from "@/types/proto/v1/instance_service";+import { isDev } from "@/utils";+import { defaultPortForEngine } from "./constants";import { provideInstanceFormContext } from "./context";-import { useInstanceSpecs } from "./specs";const props = defineProps<{instance?: Instance;- drawer?: boolean;}>();-const emit = defineEmits(["dismiss"]);-const $d = useDialog();--const bindings = computed(() => {- if (props.drawer) {- return {- title: t("quick-action.add-instance"),- };- }- return {};-});--const cancel = () => {- emit("dismiss");-};--interface LocalState {- editingDataSourceId: string | undefined;- isTestingConnection: boolean;- isRequesting: boolean;-}+const emit = defineEmits<{+ (event: "dismiss"): void;+}>();-const { t } = useI18n();-const router = useRouter();-const currentUser = useCurrentUserV1();-const instanceV1Store = useInstanceV1Store();const settingV1Store = useSettingV1Store();-const actuatorStore = useActuatorV1Store();-const subscriptionStore = useSubscriptionV1Store();-const scanIntervalInputRef = ref<InstanceType<typeof ScanIntervalInput>>();--const state = reactive<LocalState>({- editingDataSourceId: props.instance?.dataSources.find(- (ds) => ds.type === DataSourceType.ADMIN- )?.id,- isTestingConnection: false,- isRequesting: false,-});const instance = toRef(props, "instance");const context = provideInstanceFormContext({ instance });-const {- isCreating,- allowEdit,- basicInfo,- dataSourceEditState,- adminDataSource,- editingDataSource,- readonlyDataSourceList,- hasReadonlyReplicaFeature,- missingFeature,-} = context;-const {- showDatabase,- showSSL,- showSSH,- isEngineBeta,- defaultPort,- instanceLink,- allowEditPort,-} = useInstanceSpecs(context);--const availableLicenseCount = computed(() => {- return Math.max(- 0,- subscriptionStore.instanceLicenseCount -- instanceV1Store.activateInstanceCount- );-});--const availableLicenseCountText = computed((): string => {- if (subscriptionStore.instanceLicenseCount === Number.MAX_VALUE) {- return t("subscription.unlimited");- }- return `${availableLicenseCount.value}`;-});--const environment = computed(() => {- return (- useEnvironmentV1Store().getEnvironmentByName(basicInfo.value.environment) ??- unknownEnvironment()- );-});--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 resourceIdField = ref<InstanceType<typeof ResourceIdField>>();-+const { events, isCreating, basicInfo, adminDataSource, missingFeature } =+ context;onMounted(async () => {if (isCreating.value) {adminDataSource.value.host = isDev() ? "127.0.0.1" : "host.docker.internal";@@ -695,849 +67,7 @@ watch(});-const outboundIpList = computed(() => {- if (!settingV1Store.workspaceProfileSetting) {- return "";- }- return settingV1Store.workspaceProfileSetting.outboundIpList.join(",");-});--const currentMongoDBConnectionSchema = computed(() => {- return adminDataSource.value.srv === false- ? MongoDBConnectionStringSchemaList[0]- : MongoDBConnectionStringSchemaList[1];-});-const allowCreate = computed(() => {- if (!hasWorkspacePermissionV2(currentUser.value, "bb.instances.create")) {- return false;- }- if (environment.value.uid === String(UNKNOWN_ID)) {- return false;- }- if (basicInfo.value.engine === Engine.SPANNER) {- return (- basicInfo.value.title.trim() &&- isValidSpannerHost(adminDataSource.value.host) &&- adminDataSource.value.updatedPassword- );- }-- // Check Host- if (basicInfo.value.engine !== Engine.DYNAMODB) {- if (adminDataSource.value.host === "") {- return false;- }- }-- return (- basicInfo.value.title.trim() &&- resourceIdField.value?.resourceId &&- resourceIdField.value?.isValidated &&- checkDataSource([adminDataSource.value])- );-});--const resetChanges = () => {- const original = getOriginalEditState();- basicInfo.value = cloneDeep(original.basicInfo);- dataSourceEditState.value.dataSources = cloneDeep(original.dataSources);-};--const valueChanged = computed(() => {- const original = getOriginalEditState();- const editing = {- basicInfo: basicInfo.value,- dataSources: dataSourceEditState.value.dataSources,- };- return !isEqual(editing, original);-});--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 checkDataSource([- adminDataSource.value,- ...readonlyDataSourceList.value,- ]);+useEmitteryEventListener(events, "dismiss", () => {+ emit("dismiss");});--const handleSelectEnvironmentUID = (uid: string | undefined) => {- if (!uid) return;- const environment = useEnvironmentV1Store().getEnvironmentByUID(uid);- basicInfo.value.environment = environment.name;-};--// 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();- if (- engine === Engine.SNOWFLAKE ||- engine === Engine.SPANNER ||- engine === Engine.BIGQUERY ||- engine === Engine.DYNAMODB- ) {- if (- adminDataSource.value.host === "127.0.0.1" ||- adminDataSource.value.host === "host.docker.internal"- ) {- adminDataSource.value.host = "";- }- } else {- if (!adminDataSource.value.host) {- adminDataSource.value.host = isDev()- ? "127.0.0.1"- : "host.docker.internal";- }- }- basicInfo.value.engine = engine;-};--const changeScanInterval = (duration: Duration | undefined) => {- if (!basicInfo.value.options) {- basicInfo.value.options = InstanceOptions.fromPartial({});- }- basicInfo.value.options.syncInterval = duration;-};-const changeMaximumConnections = (maximumConnections: number) => {- if (!basicInfo.value.options) {- basicInfo.value.options = InstanceOptions.fromPartial({});- }- basicInfo.value.options.maximumConnections = maximumConnections;-};--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({- host: "",- port: "",- });- if (adminDataSource.value.additionalAddresses.length !== 0) {- adminDataSource.value.directConnection = false;- }-};--const validateResourceId = async (- resourceId: ResourceId-): Promise<ValidatedMessage[]> => {- if (!resourceId) {- return [];- }-- try {- const instance = await instanceV1Store.getOrFetchInstanceByName(- instanceNamePrefix + resourceId,- true /* silent */- );- if (instance) {- return [- {- type: "error",- message: t("resource-id.validation.duplicated", {- resource: t("resource.instance"),- }),- },- ];- }- } catch (error) {- if (getErrorCode(error) !== Status.NOT_FOUND) {- throw error;- }- }- return [];-};--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;- }-- // Backend will sync the schema when connection info changed, so we need to fetch the synced schema here.- instanceV1Store.fetchInstanceRoleListByName(instance.name);-};--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(/* silent */ true, editingDS);- if (testResult.success) {- doCreate();- } else {- const confirmed = await confirmContinueWithConnectionFailure(- testResult.message- );- if (confirmed) {- doCreate();- }- }-};--const hasExternalSecretFeature = computed(() =>- subscriptionStore.hasFeature("bb.feature.external-secret-manager")-);--// 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;- }- const instanceCreate: Instance = {- ...basicInfo.value,- engineVersion: "",- dataSources: [],- };- const adminDataSourceCreate = extractDataSourceFromEdit(- instanceCreate,- adminDataSource.value- );- instanceCreate.dataSources = [adminDataSourceCreate];-- if (!checkExternalSecretFeature(instanceCreate.dataSources)) {- missingFeature.value = "bb.feature.external-secret-manager";- return;- }-- state.isRequesting = true;- try {- await useGracefulRequest(async () => {- const createdInstance =- await instanceV1Store.createInstance(instanceCreate);- useDatabaseV1Store().searchDatabases({- filter: `instance = "${createdInstance.name}"`,- });- router.push(`/${createdInstance.name}`);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t(- "instance.successfully-created-instance-createdinstance-name",- [createdInstance.title]- ),- });- });- } finally {- state.isRequesting = false;- emit("dismiss");- }-};--const doUpdate = async () => {- const { instance } = props;- if (!instance) {- return;- }- if (!checkRODataSourceFeature(instance)) {- missingFeature.value = "bb.feature.read-replica-connection";- return;- }-- if (!checkExternalSecretFeature([adminDataSource.value])) {- missingFeature.value = "bb.feature.external-secret-manager";- return;- }-- if (- !checkExternalSecretFeature([- adminDataSource.value,- ...readonlyDataSourceList.value,- ])- ) {- missingFeature.value = "bb.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<any>)[] = [];-- const maybeQueueUpdateInstanceBasicInfo = () => {- const instancePatch = {- ...instance,- ...basicInfo.value,- };- const updateMask: string[] = [];- if (instancePatch.title !== instance.title) {- updateMask.push("title");- }- if (instancePatch.externalLink !== instance.externalLink) {- updateMask.push("external_link");- }- if (instancePatch.activation !== instance.activation) {- updateMask.push("activation");- }- if (instancePatch.environment !== instance.environment) {- updateMask.push("environment");- }- if (- instancePatch.options?.syncInterval?.seconds?.toNumber() !==- instance.options?.syncInterval?.seconds?.toNumber()- ) {- updateMask.push("options.sync_interval");- }- if (- instancePatch.options?.maximumConnections !==- instance.options?.maximumConnections- ) {- updateMask.push("options.maximum_connections");- }- if (updateMask.length === 0) {- return;- }- pendingRequestRunners.push(() =>- instanceV1Store.updateInstance(instancePatch, updateMask)- );- };- /**- * @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(/* silent */ true, editState);- if (!testResult.success) {- const continueAnyway = await confirmContinueWithConnectionFailure(- testResult.message- );- if (!continueAnyway) {- return true;- }- }-- pendingRequestRunners.push(() =>- instanceV1Store.updateDataSource(instance, editing, updateMask)- );- };- const maybeQueueUpdateAdminDataSource = async () => {- const original = instance.dataSources.find(- (ds) => ds.type === DataSourceType.ADMIN- );- const editing = extractDataSourceFromEdit(instance, 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(instance, editing);- if (editing.pendingCreate) {- const testResult = await testConnection(/* silent */ true, editing);- if (!testResult.success) {- const continueAnyway = await confirmContinueWithConnectionFailure(- testResult.message- );- if (!continueAnyway) {- return true;- }- }-- pendingRequestRunners.push(() =>- instanceV1Store.createDataSource(instance, patch)- );- } else {- const original = instance.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.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(instance.name);- updateEditState(updatedInstance);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-updated-instance-instance-name", [- updatedInstance.title,- ]),- });- } finally {- state.isRequesting = false;- }-};--const testConnection = async (- silent = false,- editingDS: EditDataSource-): 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.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.isTestingConnection = false;- return { success: false, message: error };- };- state.isTestingConnection = true;- if (isCreating.value) {- // When creating new instance, use- // adminDataSource + CreateInstanceRequest.validateOnly = true- const instance: Instance = {- ...basicInfo.value,- engineVersion: "",- dataSources: [],- };- const dataSourceCreate = extractDataSourceFromEdit(instance, editingDS);- instance.dataSources = [dataSourceCreate];- try {- await instanceServiceClient.createInstance(- {- instance,- instanceId: extractInstanceResourceName(instance.name),- validateOnly: true,- },- {- silent: true,- }- );- return ok();- } catch (err) {- return fail(dataSourceCreate.host, err);- }- } else {- // Editing existed instance.- const instance = props.instance!;- const ds = extractDataSourceFromEdit(instance, editingDS);- if (editingDS.pendingCreate) {- // When read-only data source is about to be created, use- // editingDataSource + AddDataSourceRequest.validateOnly = true- try {- await instanceServiceClient.addDataSource(- {- instance: instance.name,- dataSource: ds,- validateOnly: true,- },- {- silent: 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.dataSources.find(- (ds) => ds.id === editingDS.id- );- if (!original) {- throw new Error("should never reach this line");- }- const updateMask = calcDataSourceUpdateMask(ds, original, editingDS);- await instanceServiceClient.updateDataSource(- {- instance: instance.name,- dataSource: ds,- updateMask,- validateOnly: true,- },- {- silent: true,- }- );- return ok();- } catch (err) {- return fail(ds.host, err);- }- }- }-};--const testConnectionForCurrentEditingDS = () => {- const editingDS = editingDataSource.value;- if (!editingDS) return;- testConnection(/* !silent */ false, editingDS);-};--// getOriginalEditState returns the origin instance data including-// basic information, admin data source and read-only data source.-const getOriginalEditState = () => {- return {- basicInfo: extractBasicInfo(props.instance),- dataSources: extractDataSourceEditState(props.instance).dataSources,- };-};--const calcDataSourceUpdateMask = (- editing: DataSource,- original: DataSource,- editState: EditDataSource-) => {- const updateMask = new Set(- calcUpdateMask(editing, original, true /* toSnakeCase */)- );- const {- useEmptyPassword,- updateSsh,- updateSsl,- updateAuthenticationPrivateKey,- } = editState;- if (useEmptyPassword) {- // We need to implicitly set "password" need to be updated- // if the "use empty password" option if checked- editing.password = "";- updateMask.add("password");- }- if (updateSsl) {- updateMask.add("ssl_ca");- updateMask.add("ssl_key");- updateMask.add("ssl_cert");- }- if (updateSsh) {- updateMask.add("ssh_host");- updateMask.add("ssh_port");- updateMask.add("ssh_user");- updateMask.add("ssh_password");- updateMask.add("ssh_private_key");- }- if (updateAuthenticationPrivateKey) {- updateMask.add("authentication_private_key");- }-- return Array.from(updateMask);-};--const extractDataSourceFromEdit = (- instance: Instance,- edit: EditDataSource-): DataSource => {- const ds = cloneDeep(- omit(- edit,- "pendingCreate",- "updatedPassword",- "useEmptyPassword",- "updateSsl",- "updateSsh",- "updateAuthenticationPrivateKey"- )- );- if (edit.updatedPassword) {- ds.password = edit.updatedPassword;- }- if (edit.useEmptyPassword) {- ds.password = "";- }-- // Clean up unused fields for certain engine types.- if (!showDatabase.value) {- ds.database = "";- }- if (instance.engine !== Engine.ORACLE) {- ds.sid = "";- ds.serviceName = "";- }- if (instance.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 checkExternalSecretFeature = (dataSources: DataSource[]) => {- if (hasExternalSecretFeature.value) {- return true;- }-- return dataSources.every((ds) => {- return !ds.externalSecret && !/^{{.+}}$/.test(ds.password);- });-};--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;- }- }-- if (ds.saslConfig?.krbConfig) {- if (- !ds.saslConfig.krbConfig.primary ||- !ds.saslConfig.krbConfig.realm ||- !ds.saslConfig.krbConfig.kdcHost ||- !ds.saslConfig.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) {- return false;- }- if (- !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.token;- case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:- return (- !!ds.externalSecret.appRole?.roleId &&- !!ds.externalSecret.appRole.secretId- );- }-- return true;- });-};--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, 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 changeInstanceActivation = async (on: boolean) => {- basicInfo.value.activation = on;- if (props.instance) {- const instancePatch = {- ...props.instance,- activation: on,- };- await instanceV1Store.updateInstance(instancePatch, ["activation"]);- }-};</script>--<style lang="postcss" scoped>-.instance-engine-button :deep(.n-button__content) {- @apply w-full justify-start;-}-</style>diff --git a/frontend/src/components/InstanceForm/common.ts b/frontend/src/components/InstanceForm/common.tsindex a7ff3139b5..234aa50c06 100644--- a/frontend/src/components/InstanceForm/common.ts+++ b/frontend/src/components/InstanceForm/common.ts@@ -14,6 +14,7 @@ import {InstanceOptions,} from "@/types/proto/v1/instance_service";import { PlanType } from "@/types/proto/v1/subscription_service";+import { calcUpdateMask } from "@/utils";export type BasicInfo = Omit<Instance, "dataSources" | "engineVersion">;@@ -87,3 +88,42 @@ export const wrapEditDataSource = (ds: DataSource | undefined) => {useEmptyPassword: false,};};++export const calcDataSourceUpdateMask = (+ editing: DataSource,+ original: DataSource,+ editState: EditDataSource+) => {+ const updateMask = new Set(+ calcUpdateMask(editing, original, true /* toSnakeCase */)+ );+ const {+ useEmptyPassword,+ updateSsh,+ updateSsl,+ updateAuthenticationPrivateKey,+ } = editState;+ if (useEmptyPassword) {+ // We need to implicitly set "password" need to be updated+ // if the "use empty password" option if checked+ editing.password = "";+ updateMask.add("password");+ }+ if (updateSsl) {+ updateMask.add("ssl_ca");+ updateMask.add("ssl_key");+ updateMask.add("ssl_cert");+ }+ if (updateSsh) {+ updateMask.add("ssh_host");+ updateMask.add("ssh_port");+ updateMask.add("ssh_user");+ updateMask.add("ssh_password");+ updateMask.add("ssh_private_key");+ }+ if (updateAuthenticationPrivateKey) {+ updateMask.add("authentication_private_key");+ }++ return Array.from(updateMask);+};diff --git a/frontend/src/components/InstanceForm/context.ts b/frontend/src/components/InstanceForm/context.tsindex ee1334f35d..6a0c53e4b0 100644--- a/frontend/src/components/InstanceForm/context.ts+++ b/frontend/src/components/InstanceForm/context.ts@@ -1,40 +1,68 @@-import type { ComputedRef, InjectionKey, Ref } from "vue";+import Emittery from "emittery";+import { cloneDeep, omit } from "lodash-es";+import { useDialog } from "naive-ui";+import type { InjectionKey, Ref } from "vue";import { provide, inject, computed, ref } from "vue";-import { useCurrentUserV1, useSubscriptionV1Store } from "@/store";-import type { FeatureType } from "@/types";-import { State } from "@/types/proto/v1/common";-import type { Instance } from "@/types/proto/v1/instance_service";-import { DataSourceType } from "@/types/proto/v1/instance_service";-import { hasWorkspacePermissionV2 } from "@/utils";-import type { BasicInfo, DataSourceEditState, EditDataSource } from "./common";-import { extractBasicInfo, extractDataSourceEditState } from "./common";--export type InstanceFormContext = {- instance: Ref<Instance | undefined>;- isCreating: Ref<boolean>;- allowEdit: Ref<boolean>;- basicInfo: Ref<BasicInfo>;- dataSourceEditState: Ref<DataSourceEditState>;- hasReadonlyReplicaFeature: ComputedRef<boolean>;- missingFeature: Ref<FeatureType | undefined>;-- // derived states- adminDataSource: ComputedRef<EditDataSource>;- editingDataSource: ComputedRef<EditDataSource | undefined>;- readonlyDataSourceList: ComputedRef<EditDataSource[]>;- hasReadOnlyDataSource: ComputedRef<boolean>;- resetDataSource: () => void;+import { useI18n } from "vue-i18n";+import { instanceServiceClient } from "@/grpcweb";+import {+ pushNotification,+ useCurrentUserV1,+ useEnvironmentV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { UNKNOWN_ID, unknownEnvironment, type FeatureType } from "@/types";+import { Engine, State } from "@/types/proto/v1/common";+import type { DataSource, Instance } from "@/types/proto/v1/instance_service";+import {+ DataSourceExternalSecret_AuthType,+ DataSourceExternalSecret_SecretType,+ DataSourceType,+ DataSource_AuthenticationType,+} from "@/types/proto/v1/instance_service";+import {+ extractInstanceResourceName,+ hasWorkspacePermissionV2,+ isValidSpannerHost,+} from "@/utils";+import { extractGrpcErrorMessage } from "@/utils/grpcweb";+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: Pick<InstanceFormContext, "instance">-) => {+export const provideInstanceFormContext = (baseContext: {+ instance: Ref<Instance | undefined>;+}) => {+ const $d = useDialog();+ const { t } = useI18n();const me = useCurrentUserV1();+ const events = new Emittery<{+ dismiss: 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;@@ -78,10 +106,300 @@ export const provideInstanceFormContext = (};const missingFeature = ref<FeatureType | undefined>(undefined);- const context: InstanceFormContext = {+ const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();++ const environment = computed(() => {+ return (+ useEnvironmentV1Store().getEnvironmentByName(+ basicInfo.value.environment+ ) ?? unknownEnvironment()+ );+ });++ 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;+ }+ }++ if (ds.saslConfig?.krbConfig) {+ if (+ !ds.saslConfig.krbConfig.primary ||+ !ds.saslConfig.krbConfig.realm ||+ !ds.saslConfig.krbConfig.kdcHost ||+ !ds.saslConfig.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) {+ return false;+ }+ if (+ !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.token;+ case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:+ return (+ !!ds.externalSecret.appRole?.roleId &&+ !!ds.externalSecret.appRole.secretId+ );+ }++ return true;+ });+ };++ const allowCreate = computed(() => {+ if (!hasWorkspacePermissionV2(me.value, "bb.instances.create")) {+ return false;+ }+ if (environment.value.uid === String(UNKNOWN_ID)) {+ return false;+ }+ if (basicInfo.value.engine === Engine.SPANNER) {+ return (+ basicInfo.value.title.trim() &&+ isValidSpannerHost(adminDataSource.value.host) &&+ adminDataSource.value.updatedPassword+ );+ }++ // Check Host+ if (basicInfo.value.engine !== Engine.DYNAMODB) {+ if (adminDataSource.value.host === "") {+ return false;+ }+ }++ return (+ basicInfo.value.title.trim() &&+ resourceIdField.value?.resourceId &&+ resourceIdField.value?.isValidated &&+ checkDataSource([adminDataSource.value])+ );+ });++ const specs = useInstanceSpecs(basicInfo, adminDataSource, editingDataSource);++ const extractDataSourceFromEdit = (+ instance: Instance,+ edit: EditDataSource+ ): DataSource => {+ const { showDatabase, showSSH, showSSL } = specs;+ const ds = cloneDeep(+ omit(+ edit,+ "pendingCreate",+ "updatedPassword",+ "useEmptyPassword",+ "updateSsl",+ "updateSsh",+ "updateAuthenticationPrivateKey"+ )+ );+ if (edit.updatedPassword) {+ ds.password = edit.updatedPassword;+ }+ if (edit.useEmptyPassword) {+ ds.password = "";+ }++ // Clean up unused fields for certain engine types.+ if (!showDatabase.value) {+ ds.database = "";+ }+ if (instance.engine !== Engine.ORACLE) {+ ds.sid = "";+ ds.serviceName = "";+ }+ if (instance.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 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 = {+ ...basicInfo.value,+ engineVersion: "",+ dataSources: [],+ };+ const dataSourceCreate = extractDataSourceFromEdit(instance, editingDS);+ instance.dataSources = [dataSourceCreate];+ try {+ await instanceServiceClient.createInstance(+ {+ instance,+ instanceId: extractInstanceResourceName(instance.name),+ validateOnly: true,+ },+ {+ silent: true,+ }+ );+ return ok();+ } catch (err) {+ return fail(dataSourceCreate.host, err);+ }+ } else {+ // Editing existed instance.+ const ds = extractDataSourceFromEdit(instance.value!, editingDS);+ if (editingDS.pendingCreate) {+ // When read-only data source is about to be created, use+ // editingDataSource + AddDataSourceRequest.validateOnly = true+ try {+ await instanceServiceClient.addDataSource(+ {+ instance: instance.value!.name,+ dataSource: ds,+ validateOnly: true,+ },+ {+ silent: 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 instanceServiceClient.updateDataSource(+ {+ instance: instance.value!.name,+ dataSource: ds,+ updateMask,+ validateOnly: true,+ },+ {+ silent: true,+ }+ );+ return ok();+ } catch (err) {+ return fail(ds.host, err);+ }+ }+ }+ };++ const context = {...baseContext,+ $d,+ events,+ state,+ specs,isCreating,allowEdit,+ allowCreate,+ resourceIdField,+ environment,basicInfo,dataSourceEditState,adminDataSource,@@ -90,7 +408,10 @@ export const provideInstanceFormContext = (hasReadOnlyDataSource,hasReadonlyReplicaFeature,missingFeature,+ checkDataSource,resetDataSource,+ extractDataSourceFromEdit,+ testConnection,};provide(KEY, context);@@ -100,3 +421,5 @@ export const provideInstanceFormContext = (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 fc89c1b974..ff3d73a499 100644--- a/frontend/src/components/InstanceForm/index.ts+++ b/frontend/src/components/InstanceForm/index.ts@@ -1,3 +1,7 @@+import Buttons from "./Buttons.vue";+import Form from "./Form.vue";import InstanceForm from "./InstanceForm.vue";export default InstanceForm;++export { InstanceForm, Form, Buttons };diff --git a/frontend/src/components/InstanceForm/specs.ts b/frontend/src/components/InstanceForm/specs.tsindex e5ae956722..deb50ef1b1 100644--- a/frontend/src/components/InstanceForm/specs.ts+++ b/frontend/src/components/InstanceForm/specs.ts@@ -1,24 +1,20 @@-import { computed } from "vue";+import { computed, type Ref } from "vue";import { Engine } from "@/types/proto/v1/common";import { DataSourceType } from "@/types/proto/v1/instance_service";import { instanceV1HasSSH, instanceV1HasSSL } from "@/utils";+import type { BasicInfo, EditDataSource } from "./common";import { defaultPortForEngine } from "./constants";-import type { InstanceFormContext } from "./context";-import { useInstanceFormContext } from "./context";export const useInstanceSpecs = (- context: InstanceFormContext | undefined = undefined+ basicInfo: Ref<BasicInfo>,+ adminDataSource: Ref<EditDataSource>,+ editingDataSource: Ref<EditDataSource | undefined>) => {- if (!context) {- context = useInstanceFormContext();- }- const { basicInfo, adminDataSource, editingDataSource } = context;-const showDatabase = computed((): boolean => {return ((basicInfo.value.engine === Engine.POSTGRES ||basicInfo.value.engine === Engine.REDSHIFT) &&- context?.editingDataSource.value?.type === DataSourceType.ADMIN+ editingDataSource.value?.type === DataSourceType.ADMIN);});const showSSL = computed((): boolean => {@@ -78,3 +74,5 @@ export const useInstanceSpecs = (hasReadonlyReplicaPort,};};++export type InstanceSpecs = ReturnType<typeof useInstanceSpecs>;diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vueindex ab3d61283d..28dec78b32 100644--- a/frontend/src/components/QuickActionPanel.vue+++ b/frontend/src/components/QuickActionPanel.vue@@ -32,7 +32,15 @@v-if="state.quickActionType === 'quickaction.bb.instance.create'":drawer="true"@dismiss="state.quickActionType = undefined"- />+ >+ <DrawerContent :title="$t('quick-action.add-instance')">+ <InstanceFormBody />+ <template #footer>+ <InstanceFormButtons />+ </template>+ </DrawerContent>+ <InstanceFormBody />+ </InstanceForm><CreateDatabasePrepPanelv-if="state.quickActionType === 'quickaction.bb.database.create'":project-id="project?.uid"@@ -110,7 +118,11 @@ import { useI18n } from "vue-i18n";import { useRoute, useRouter } from "vue-router";import AlterSchemaPrepForm from "@/components/AlterSchemaPrepForm/";import { CreateDatabasePrepPanel } from "@/components/CreateDatabasePrepForm";-import InstanceForm from "@/components/InstanceForm/";+import {+ InstanceForm,+ Form as InstanceFormBody,+ Buttons as InstanceFormButtons,+} from "@/components/InstanceForm/";import RequestExportPanel from "@/components/Issue/panel/RequestExportPanel/index.vue";import RequestQueryPanel from "@/components/Issue/panel/RequestQueryPanel/index.vue";import ProjectCreatePanel from "@/components/Project/ProjectCreatePanel.vue";diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vueindex 3b1a04b8c6..e32c332eb1 100644--- a/frontend/src/views/InstanceDetail.vue+++ b/frontend/src/views/InstanceDetail.vue@@ -32,7 +32,10 @@<NTabs><NTabPane name="OVERVIEW" :tab="$t('common.overview')">- <InstanceForm class="-mt-2" :instance="instance" />+ <InstanceForm class="-mt-2" :instance="instance">+ <InstanceFormBody />+ <InstanceFormButtons class="sticky bottom-0 z-10" />+ </InstanceForm></NTabPane><NTabPane name="DATABASES" :tab="$t('common.databases')"><div class="space-y-2">@@ -75,7 +78,11 @@ import { useRouter } from "vue-router";import ArchiveBanner from "@/components/ArchiveBanner.vue";import { CreateDatabasePrepPanel } from "@/components/CreateDatabasePrepForm";import { EngineIcon } from "@/components/Icon";-import InstanceForm from "@/components/InstanceForm/";+import {+ InstanceForm,+ Form as InstanceFormBody,+ Buttons as InstanceFormButtons,+} from "@/components/InstanceForm/";import { InstanceRoleTable, Drawer } from "@/components/v2";import DatabaseV1Table from "@/components/v2/Model/DatabaseV1Table";import {@@ -96,6 +103,7 @@ import {hasWorkspaceLevelProjectPermissionInAnyProject,databaseV1Url,} from "@/utils";+import { useBodyLayoutContext } from "@/layouts/common";interface LocalState {showCreateDatabaseModal: boolean;@@ -107,6 +115,9 @@ const props = defineProps<{instanceId: string;}>();+const { overrideMainContainerClass } = useBodyLayoutContext();+overrideMainContainerClass("!pb-0");+const instanceV1Store = useInstanceV1Store();const databaseStore = useDatabaseV1Store();const { t } = useI18n();