Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(frontend): migrate database backup to v1 (#6407)

Liu Jib3b2ae283926
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 4c67826e1b..548de1ec91 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -1370,7 +1370,7 @@ func convertToBackup(backup *store.BackupMessage, instanceID string, databaseNam
backupType = v1pb.Backup_PITR
}
return &v1pb.Backup{
- Name: fmt.Sprintf("%s%s/%s%s/%s", instanceNamePrefix, instanceID, databaseIDPrefix, databaseName, backup.Name),
+ Name: fmt.Sprintf("%s%s/%s%s/%s%s", instanceNamePrefix, instanceID, databaseIDPrefix, databaseName, backupPrefix, backup.Name),
CreateTime: createTime,
UpdateTime: updateTime,
State: backupState,
diff --git a/frontend/src/components/BackupTable.vue b/frontend/src/components/BackupTable.vue
deleted file mode 100644
index 147221cc90..0000000000
--- a/frontend/src/components/BackupTable.vue
+++ /dev/null
@@ -1,347 +0,0 @@
-<template>
- <BBTable
- :column-list="columnList"
- :section-data-source="backupSectionList"
- :show-header="true"
- :row-clickable="false"
- :left-bordered="true"
- :right-bordered="true"
- >
- <template #header>
- <BBTableHeaderCell
- :left-padding="4"
- class="w-4"
- :title="columnList[0].title"
- />
- <BBTableHeaderCell class="w-16" :title="columnList[1].title" />
- <BBTableHeaderCell class="w-48" :title="columnList[2].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[3].title" />
- <BBTableHeaderCell
- v-if="allowEdit"
- class="w-4"
- :title="columnList[4].title"
- />
- </template>
- <template #body="{ rowData: backup }">
- <BBTableCell :left-padding="4">
- <span
- class="flex items-center justify-center rounded-full select-none"
- :class="statusIconClass(backup)"
- >
- <template v-if="backup.status == 'PENDING_CREATE'">
- <span
- class="h-2 w-2 bg-info hover:bg-info-hover rounded-full"
- style="
- animation: pulse 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
- "
- >
- </span>
- </template>
- <template v-else-if="backup.status == 'DONE'">
- <heroicons-outline:check class="w-4 h-4" />
- </template>
- <template v-else-if="backup.status == 'FAILED'">
- <span
- class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"
- aria-hidden="true"
- >!</span
- >
- </template>
- </span>
- </BBTableCell>
- <BBTableCell>
- {{ backup.name }}
- </BBTableCell>
- <BBTableCell class="tooltip-wrapper">
- <span v-if="backup.comment.length > 100" class="tooltip">{{
- backup.comment
- }}</span>
- {{
- backup.comment.length > 100
- ? backup.comment.substring(0, 100) + "..."
- : backup.comment
- }}
- </BBTableCell>
- <BBTableCell class="tooltip-wrapper">
- <span class="tooltip whitespace-nowrap">
- {{ dayjs(backup.createdTs * 1000).format("YYYY-MM-DD HH:mm") }}
- </span>
- {{ humanizeTs(backup.createdTs) }}
- </BBTableCell>
- <BBTableCell v-if="allowEdit">
- <button
- :disabled="!allowRestore(backup)"
- class="normal-link disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:no-underline"
- @click.stop="showRestoreDialog(backup)"
- >
- {{ $t("database.restore") }}
- </button>
- </BBTableCell>
- </template>
- </BBTable>
- <BBModal
- v-if="state.restoreBackupContext"
- :title="$t('database.restore-database')"
- @close="state.restoreBackupContext = undefined"
- >
- <div class="space-y-4 w-[35rem]">
- <RestoreTargetForm
- v-if="allowRestoreInPlace"
- :target="state.restoreBackupContext.target"
- @change="state.restoreBackupContext!.target = $event"
- />
-
- <CreateDatabasePrepForm
- v-if="state.restoreBackupContext.target === 'NEW'"
- :project-id="database.projectEntity.uid"
- :environment-id="database.instanceEntity.environmentEntity.uid"
- :instance-id="database.instanceEntity.uid"
- :backup="state.restoreBackupContext.backup"
- @dismiss="state.restoreBackupContext = undefined"
- />
- </div>
-
- <div
- v-if="state.restoreBackupContext.target === 'IN-PLACE'"
- class="w-full pt-6 mt-4 flex justify-end gap-x-3 border-t border-block-border"
- >
- <button
- type="button"
- class="btn-normal py-2 px-4"
- @click="state.restoreBackupContext = undefined"
- >
- {{ $t("common.cancel") }}
- </button>
-
- <button
- type="button"
- class="btn-primary py-2 px-4"
- @click="doRestoreInPlace"
- >
- {{ $t("common.confirm") }}
- </button>
- </div>
-
- <div
- v-if="state.creatingRestoreIssue"
- class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"
- >
- <BBSpin />
- </div>
- </BBModal>
-
- <FeatureModal
- v-if="state.showFeatureModal"
- feature="bb.feature.pitr"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { computed, PropType, reactive } from "vue";
-import { useRouter } from "vue-router";
-import { useI18n } from "vue-i18n";
-import { BBTableColumn, BBTableSectionDataSource } from "../bbkit/types";
-import {
- Backup,
- ComposedDatabase,
- IssueCreate,
- PITRContext,
- SYSTEM_BOT_ID,
-} from "../types";
-import { issueSlug } from "../utils";
-import { featureToRef, useIssueStore } from "@/store";
-import CreateDatabasePrepForm from "../components/CreateDatabasePrepForm.vue";
-import {
- default as RestoreTargetForm,
- RestoreTarget,
-} from "../components/DatabaseBackup/RestoreTargetForm.vue";
-import { Engine } from "@/types/proto/v1/common";
-
-type RestoreBackupContext = {
- target: RestoreTarget;
- backup: Backup;
-};
-
-interface LocalState {
- restoreBackupContext?: RestoreBackupContext;
- loadingMigrationHistory: boolean;
- creatingRestoreIssue: boolean;
- showFeatureModal: boolean;
-}
-
-const props = defineProps({
- database: {
- required: true,
- type: Object as PropType<ComposedDatabase>,
- },
- backupList: {
- required: true,
- type: Object as PropType<Backup[]>,
- },
- allowEdit: {
- required: true,
- type: Boolean,
- },
-});
-
-const router = useRouter();
-const { t } = useI18n();
-
-const state = reactive<LocalState>({
- restoreBackupContext: undefined,
- loadingMigrationHistory: false,
- creatingRestoreIssue: false,
- showFeatureModal: false,
-});
-
-const allowRestoreInPlace = computed((): boolean => {
- return props.database.instanceEntity.engine === Engine.POSTGRES;
-});
-
-const hasPITRFeature = featureToRef("bb.feature.pitr");
-
-const EDIT_COLUMN_LIST: BBTableColumn[] = [
- {
- title: t("common.status"),
- },
- {
- title: t("common.name"),
- },
- {
- title: t("common.comment"),
- },
- {
- title: t("common.time"),
- },
- {
- title: "",
- },
-];
-
-const NON_EDIT_COLUMN_LIST: BBTableColumn[] = [
- {
- title: t("common.status"),
- },
- {
- title: t("common.name"),
- },
- {
- title: t("common.comment"),
- },
- {
- title: t("common.time"),
- },
-];
-
-const backupSectionList = computed(() => {
- const manualList: Backup[] = [];
- const automaticList: Backup[] = [];
- const pitrList: Backup[] = [];
- const sectionList: BBTableSectionDataSource<Backup>[] = [
- {
- title: t("common.manual"),
- list: manualList,
- },
- {
- title: t("common.automatic"),
- list: automaticList,
- },
- {
- title: t("common.pitr"),
- list: pitrList,
- },
- ];
-
- for (const backup of props.backupList) {
- if (backup.type == "MANUAL") {
- manualList.push(backup);
- } else if (backup.type == "AUTOMATIC") {
- automaticList.push(backup);
- } else if (backup.type === "PITR") {
- pitrList.push(backup);
- }
- }
-
- return sectionList;
-});
-
-const statusIconClass = (backup: Backup) => {
- const iconClass = "w-5 h-5";
- switch (backup.status) {
- case "PENDING_CREATE":
- return (
- iconClass +
- " bg-white border-2 border-info text-info hover:text-info-hover hover:border-info-hover"
- );
- case "DONE":
- return iconClass + " bg-success hover:bg-success-hover text-white";
- case "FAILED":
- return (
- iconClass + " bg-error text-white hover:text-white hover:bg-error-hover"
- );
- }
-};
-
-const columnList = computed(() => {
- return props.allowEdit ? EDIT_COLUMN_LIST : NON_EDIT_COLUMN_LIST;
-});
-
-const allowRestore = (backup: Backup) => {
- return backup.status === "DONE";
-};
-
-const showRestoreDialog = (backup: Backup) => {
- state.restoreBackupContext = {
- target: "NEW",
- backup,
- };
-};
-
-const doRestoreInPlace = async () => {
- const { restoreBackupContext } = state;
- if (!restoreBackupContext) {
- return;
- }
-
- if (!hasPITRFeature.value) {
- state.showFeatureModal = true;
- return;
- }
-
- state.creatingRestoreIssue = true;
-
- try {
- const { backup } = restoreBackupContext;
- const { database } = props;
- const issueNameParts: string[] = [
- `Restore database [${database.name}]`,
- `to backup snapshot [${restoreBackupContext.backup.name}]`,
- ];
-
- const issueStore = useIssueStore();
- const createContext: PITRContext = {
- databaseId: Number(database.uid),
- backupId: backup.id,
- };
- const issueCreate: IssueCreate = {
- name: issueNameParts.join(" "),
- type: "bb.issue.database.restore.pitr",
- description: "",
- assigneeId: SYSTEM_BOT_ID,
- projectId: Number(database.projectEntity.uid),
- payload: {},
- createContext,
- };
-
- await issueStore.validateIssue(issueCreate);
-
- const issue = await issueStore.createIssue(issueCreate);
-
- const slug = issueSlug(issue.name, issue.id);
- router.push(`/issue/${slug}`);
- } catch {
- state.creatingRestoreIssue = false;
- }
-};
-</script>
diff --git a/frontend/src/components/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm.vue
index 8a69a19f64..accbe4ed7f 100644
--- a/frontend/src/components/CreateDatabasePrepForm.vue
+++ b/frontend/src/components/CreateDatabasePrepForm.vue
@@ -250,7 +250,6 @@ import InstanceRoleSelect from "./InstanceRoleSelect.vue";
import {
IssueCreate,
SYSTEM_BOT_ID,
- Backup,
defaultCharsetOfEngineV1,
defaultCollationOfEngineV1,
CreateDatabaseContext,
@@ -262,6 +261,7 @@ import {
import { TenantMode } from "@/types/proto/v1/project_service";
import { INTERNAL_RDS_INSTANCE_USER_LIST } from "@/types/InstanceUser";
import {
+ extractDatabaseResourceName,
extractEnvironmentResourceName,
hasWorkspacePermissionV1,
instanceV1HasCollationAndCharacterSet,
@@ -271,6 +271,7 @@ import {
import {
hasFeature,
useCurrentUserV1,
+ useDatabaseV1Store,
useEnvironmentV1Store,
useInstanceV1Store,
useIssueStore,
@@ -280,6 +281,7 @@ import { UserRole } from "@/types/proto/v1/auth_service";
import { Engine } from "@/types/proto/v1/common";
import { InstanceV1EngineIcon } from "./v2";
import { InstanceRole } from "@/types/proto/v1/instance_role_service";
+import { Backup } from "@/types/proto/v1/database_service";
interface LocalState {
projectId?: string;
@@ -534,9 +536,15 @@ const create = async () => {
if (props.backup) {
// If props.backup is specified, we create a PITR issue
// with createDatabaseContext
+ const { instance, database } = extractDatabaseResourceName(
+ props.backup.name
+ );
+ const db = await useDatabaseV1Store().getOrFetchDatabaseByName(
+ `instances/${instance}/databases/${database}`
+ );
const createContext: PITRContext = {
- databaseId: props.backup.databaseId,
- backupId: props.backup.id,
+ databaseId: Number(db.uid),
+ backupId: Number(props.backup.uid),
createDatabaseContext,
};
newIssue = {
diff --git a/frontend/src/components/DatabaseBackup/BackupTable.vue b/frontend/src/components/DatabaseBackup/BackupTable.vue
new file mode 100644
index 0000000000..d594b7e94a
--- /dev/null
+++ b/frontend/src/components/DatabaseBackup/BackupTable.vue
@@ -0,0 +1,340 @@
+<template>
+ <div>
+ <div
+ v-for="section in backupSectionList"
+ :key="section.title"
+ class="border-x border-b first:border-t"
+ >
+ <div class="py-2 px-2">{{ section.title }}</div>
+
+ <BBGrid
+ :column-list="columnList"
+ :data-source="section.list"
+ class="border-t"
+ :row-clickable="false"
+ :show-placeholder="true"
+ >
+ <template #item="{ item: backup }: BackupRow">
+ <div class="bb-grid-cell">
+ <span
+ class="flex items-center justify-center rounded-full select-none"
+ :class="statusIconClass(backup)"
+ >
+ <template
+ v-if="backup.state === Backup_BackupState.PENDING_CREATE"
+ >
+ <span
+ class="h-2 w-2 bg-info hover:bg-info-hover rounded-full"
+ style="
+ animation: pulse 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+ "
+ >
+ </span>
+ </template>
+ <template v-else-if="backup.state === Backup_BackupState.DONE">
+ <heroicons-outline:check class="w-4 h-4" />
+ </template>
+ <template v-else-if="backup.state === Backup_BackupState.FAILED">
+ <span
+ class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"
+ aria-hidden="true"
+ >!</span
+ >
+ </template>
+ </span>
+ </div>
+ <div class="bb-grid-cell">
+ {{ extractBackupResourceName(backup.name) }}
+ </div>
+ <div class="bb-grid-cell">
+ <EllipsisText>
+ {{ backup.comment }}
+ </EllipsisText>
+ </div>
+ <div class="bb-grid-cell">
+ <HumanizeDate :date="backup.createTime" />
+ </div>
+ <div v-if="allowEdit" class="bb-grid-cell">
+ <NButton
+ :disabled="!allowRestore(backup)"
+ @click.stop="showRestoreDialog(backup)"
+ >
+ {{ $t("database.restore") }}
+ </NButton>
+ </div>
+ </template>
+ </BBGrid>
+ </div>
+
+ <BBModal
+ v-if="state.restoreBackupContext"
+ :title="$t('database.restore-database')"
+ @close="state.restoreBackupContext = undefined"
+ >
+ <div v-if="allowRestoreInPlace" class="space-y-4 w-[35rem]">
+ <RestoreTargetForm
+ :target="state.restoreBackupContext.target"
+ @change="state.restoreBackupContext!.target = $event"
+ />
+ </div>
+
+ <CreateDatabasePrepForm
+ v-if="state.restoreBackupContext.target === 'NEW'"
+ :project-id="database.projectEntity.uid"
+ :environment-id="database.instanceEntity.environmentEntity.uid"
+ :instance-id="database.instanceEntity.uid"
+ :backup="state.restoreBackupContext.backup"
+ @dismiss="state.restoreBackupContext = undefined"
+ />
+
+ <div
+ v-if="state.restoreBackupContext.target === 'IN-PLACE'"
+ class="w-full pt-6 mt-4 flex justify-end gap-x-3 border-t border-block-border"
+ >
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ @click="state.restoreBackupContext = undefined"
+ >
+ {{ $t("common.cancel") }}
+ </button>
+
+ <button
+ type="button"
+ class="btn-primary py-2 px-4"
+ @click="doRestoreInPlace"
+ >
+ {{ $t("common.confirm") }}
+ </button>
+ </div>
+
+ <div
+ v-if="state.creatingRestoreIssue"
+ class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </BBModal>
+
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.pitr"
+ @cancel="state.showFeatureModal = false"
+ />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, PropType, reactive } from "vue";
+import { useRouter } from "vue-router";
+import { useI18n } from "vue-i18n";
+import { NButton } from "naive-ui";
+
+import { BBGrid, BBGridColumn, BBGridRow } from "@/bbkit";
+import {
+ ComposedDatabase,
+ IssueCreate,
+ PITRContext,
+ SYSTEM_BOT_ID,
+} from "@/types";
+import { issueSlug, extractBackupResourceName } from "@/utils";
+import { featureToRef, useIssueStore } from "@/store";
+import CreateDatabasePrepForm from "@/components/CreateDatabasePrepForm.vue";
+import HumanizeDate from "@/components/misc/HumanizeDate.vue";
+import EllipsisText from "@/components/EllipsisText.vue";
+import {
+ default as RestoreTargetForm,
+ RestoreTarget,
+} from "@/components/DatabaseBackup/RestoreTargetForm.vue";
+import { Engine } from "@/types/proto/v1/common";
+import {
+ Backup,
+ Backup_BackupState,
+ Backup_BackupType,
+} from "@/types/proto/v1/database_service";
+
+export type BackupRow = BBGridRow<Backup>;
+
+type RestoreBackupContext = {
+ target: RestoreTarget;
+ backup: Backup;
+};
+
+type Section = {
+ title: string;
+ list: Backup[];
+};
+
+interface LocalState {
+ restoreBackupContext?: RestoreBackupContext;
+ loadingMigrationHistory: boolean;
+ creatingRestoreIssue: boolean;
+ showFeatureModal: boolean;
+}
+
+const props = defineProps({
+ database: {
+ required: true,
+ type: Object as PropType<ComposedDatabase>,
+ },
+ backupList: {
+ required: true,
+ type: Object as PropType<Backup[]>,
+ },
+ allowEdit: {
+ required: true,
+ type: Boolean,
+ },
+});
+
+const router = useRouter();
+const { t } = useI18n();
+
+const state = reactive<LocalState>({
+ restoreBackupContext: undefined,
+ loadingMigrationHistory: false,
+ creatingRestoreIssue: false,
+ showFeatureModal: false,
+});
+
+const allowRestoreInPlace = computed((): boolean => {
+ return props.database.instanceEntity.engine === Engine.POSTGRES;
+});
+
+const hasPITRFeature = featureToRef("bb.feature.pitr");
+
+const columnList = computed(() => {
+ const columns: BBGridColumn[] = [
+ {
+ title: t("common.status"),
+ width: "auto",
+ },
+ {
+ title: t("common.name"),
+ width: "1fr",
+ },
+ {
+ title: t("common.comment"),
+ width: "2fr",
+ },
+ {
+ title: t("common.time"),
+ width: "auto",
+ },
+ ];
+ if (props.allowEdit) {
+ columns.push({
+ title: "",
+ width: "auto",
+ });
+ }
+ return columns;
+});
+
+const backupSectionList = computed(() => {
+ const manualList: Backup[] = [];
+ const automaticList: Backup[] = [];
+ const pitrList: Backup[] = [];
+ const sectionList: Section[] = [
+ {
+ title: t("common.manual"),
+ list: manualList,
+ },
+ {
+ title: t("common.automatic"),
+ list: automaticList,
+ },
+ {
+ title: t("common.pitr"),
+ list: pitrList,
+ },
+ ];
+
+ for (const backup of props.backupList) {
+ if (backup.backupType === Backup_BackupType.MANUAL) {
+ manualList.push(backup);
+ } else if (backup.backupType === Backup_BackupType.AUTOMATIC) {
+ automaticList.push(backup);
+ } else if (backup.backupType === Backup_BackupType.PITR) {
+ pitrList.push(backup);
+ }
+ }
+
+ return sectionList;
+});
+
+const statusIconClass = (backup: Backup) => {
+ const iconClass = "w-5 h-5";
+ switch (backup.state) {
+ case Backup_BackupState.PENDING_CREATE:
+ return (
+ iconClass +
+ " bg-white border-2 border-info text-info hover:text-info-hover hover:border-info-hover"
+ );
+ case Backup_BackupState.DONE:
+ return iconClass + " bg-success hover:bg-success-hover text-white";
+ case Backup_BackupState.FAILED:
+ return (
+ iconClass + " bg-error text-white hover:text-white hover:bg-error-hover"
+ );
+ }
+};
+
+const allowRestore = (backup: Backup) => {
+ return backup.state === Backup_BackupState.DONE;
+};
+
+const showRestoreDialog = (backup: Backup) => {
+ state.restoreBackupContext = {
+ target: "NEW",
+ backup,
+ };
+};
+
+const doRestoreInPlace = async () => {
+ const { restoreBackupContext } = state;
+ if (!restoreBackupContext) {
+ return;
+ }
+
+ if (!hasPITRFeature.value) {
+ state.showFeatureModal = true;
+ return;
+ }
+
+ state.creatingRestoreIssue = true;
+
+ try {
+ const { backup } = restoreBackupContext;
+ const { database } = props;
+ const issueNameParts: string[] = [
+ `Restore database [${database.name}]`,
+ `to backup snapshot [${restoreBackupContext.backup.name}]`,
+ ];
+
+ const issueStore = useIssueStore();
+ const createContext: PITRContext = {
+ databaseId: Number(database.uid),
+ backupId: Number(backup.uid),
+ };
+ const issueCreate: IssueCreate = {
+ name: issueNameParts.join(" "),
+ type: "bb.issue.database.restore.pitr",
+ description: "",
+ assigneeId: SYSTEM_BOT_ID,
+ projectId: Number(database.projectEntity.uid),
+ payload: {},
+ createContext,
+ };
+
+ await issueStore.validateIssue(issueCreate);
+
+ const issue = await issueStore.createIssue(issueCreate);
+
+ const slug = issueSlug(issue.name, issue.id);
+ router.push(`/issue/${slug}`);
+ } catch {
+ state.creatingRestoreIssue = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/DatabaseBackup/DatabaseBackupSettingForm.vue b/frontend/src/components/DatabaseBackup/DatabaseBackupSettingForm.vue
index e2137bef3e..2513e98150 100644
--- a/frontend/src/components/DatabaseBackup/DatabaseBackupSettingForm.vue
+++ b/frontend/src/components/DatabaseBackup/DatabaseBackupSettingForm.vue
@@ -173,7 +173,7 @@ import {
parseScheduleFromBackupSetting,
BackupSettingEdit,
} from "./utils";
-import { pushNotification, useBackupStore } from "@/store";
+import { pushNotification, useLegacyBackupStore } from "@/store";
import {
BackupPlanSchedule,
backupPlanScheduleToJSON,
@@ -217,7 +217,7 @@ const state = reactive<LocalState>({
loading: false,
});
-const backupStore = useBackupStore();
+const backupStore = useLegacyBackupStore();
const { t } = useI18n();
const allowDisableAutoBackup = computed(() => {
diff --git a/frontend/src/components/DatabaseBackup/index.ts b/frontend/src/components/DatabaseBackup/index.ts
index 797bb71072..7fa83ca5e8 100644
--- a/frontend/src/components/DatabaseBackup/index.ts
+++ b/frontend/src/components/DatabaseBackup/index.ts
@@ -1,5 +1,6 @@
+import BackupTable from "./BackupTable.vue";
import DatabaseBackupSettingForm from "./DatabaseBackupSettingForm.vue";
export * from "./utils";
-export { DatabaseBackupSettingForm };
+export { DatabaseBackupSettingForm, BackupTable };
diff --git a/frontend/src/components/DatabaseBackupPanel.vue b/frontend/src/components/DatabaseBackupPanel.vue
index 79396f9738..e608154142 100644
--- a/frontend/src/components/DatabaseBackupPanel.vue
+++ b/frontend/src/components/DatabaseBackupPanel.vue
@@ -171,26 +171,29 @@ import {
PropType,
onBeforeMount,
} from "vue";
-import { cloneDeep, isEqual } from "lodash-es";
+import { isEqual } from "lodash-es";
import { useI18n } from "vue-i18n";
import {
- Backup,
- BackupCreate,
BackupSetting,
- BackupSettingUpsert,
ComposedDatabase,
NORMAL_POLL_INTERVAL,
POLL_JITTER,
MINIMUM_POLL_INTERVAL,
UNKNOWN_ID,
+ BackupSettingUpsert,
} from "@/types";
-import BackupTable from "@/components/BackupTable.vue";
import DatabaseBackupCreateForm from "@/components/DatabaseBackupCreateForm.vue";
import PITRRestoreButton from "@/components/DatabaseDetail/PITRRestoreButton.vue";
-import { pushNotification, useBackupStore } from "@/store";
+import {
+ pushNotification,
+ useLegacyBackupStore,
+ useBackupV1Store,
+ useGracefulRequest,
+} from "@/store";
import {
DatabaseBackupSettingForm,
+ BackupTable,
levelOfSchedule,
localFromUTC,
parseScheduleFromBackupSetting,
@@ -204,6 +207,11 @@ import {
BackupPlanSchedule,
} from "@/types/proto/v1/org_policy_service";
import { instanceV1HasBackupRestore } from "@/utils";
+import {
+ Backup,
+ Backup_BackupState,
+ Backup_BackupType,
+} from "@/types/proto/v1/database_service";
interface LocalState {
showCreateBackupModal: boolean;
@@ -233,7 +241,8 @@ const props = defineProps({
},
});
-const backupStore = useBackupStore();
+const legacyBackupStore = useLegacyBackupStore();
+const backupStore = useBackupV1Store();
const policyV1Store = usePolicyV1Store();
const { t } = useI18n();
@@ -256,7 +265,9 @@ onUnmounted(() => {
});
const prepareBackupList = () => {
- backupStore.fetchBackupListByDatabaseId(Number(props.database.uid));
+ backupStore.fetchBackupList({
+ parent: props.database.name,
+ });
};
watchEffect(prepareBackupList);
@@ -287,17 +298,21 @@ const disableBackupButton = computed(() => {
// List PENDING_CREATE backups first, followed by backups in createdTs descending order.
const backupList = computed(() => {
- const list = cloneDeep(
- backupStore.backupListByDatabaseId(Number(props.database.uid))
- );
- return list.sort((a: Backup, b: Backup) => {
- if (a.status == "PENDING_CREATE" && b.status != "PENDING_CREATE") {
+ const list = [...backupStore.backupListByDatabase(props.database.name)];
+ return list.sort((a, b) => {
+ if (
+ a.state === Backup_BackupState.PENDING_CREATE &&
+ b.state !== Backup_BackupState.PENDING_CREATE
+ ) {
return -1;
- } else if (a.status != "PENDING_CREATE" && b.status == "PENDING_CREATE") {
+ } else if (
+ a.state !== Backup_BackupState.PENDING_CREATE &&
+ b.state === Backup_BackupState.PENDING_CREATE
+ ) {
return 1;
}
- return b.createdTs - a.createdTs;
+ return (b.createTime?.getTime() ?? 0) - (a.createTime?.getTime() ?? 0);
});
});
@@ -372,18 +387,22 @@ const urlChanged = computed(() => {
return !isEqual(state.autoBackupHookUrl, state.autoBackupUpdatedHookUrl);
});
-const createBackup = (backupName: string) => {
+const createBackup = async (backupName: string) => {
// Create backup
- const newBackup: BackupCreate = {
- databaseId: Number(props.database.uid),
- name: backupName,
- type: "MANUAL",
- };
- backupStore.createBackup({
- databaseId: Number(props.database.uid),
- newBackup: newBackup,
+
+ useGracefulRequest(async () => {
+ const parent = props.database.name;
+ const backupCreate = Backup.fromJSON({
+ name: `${parent}/backups/${backupName}`,
+ backupType: Backup_BackupType.MANUAL,
+ });
+ await backupStore.createBackup(
+ backupCreate,
+ parent,
+ true /* refreshList */
+ );
+ pollBackups(MINIMUM_POLL_INTERVAL);
});
- pollBackups(MINIMUM_POLL_INTERVAL);
};
// pollBackups invalidates the current timer and schedule a new timer in <<interval>> microseconds
@@ -393,15 +412,13 @@ const pollBackups = (interval: number) => {
}
state.pollBackupsTimer = setTimeout(() => {
backupStore
- .fetchBackupListByDatabaseId(Number(props.database.uid))
- .then((backups: Backup[]) => {
- let pending = false;
- for (const idx in backups) {
- if (backups[idx].status.includes("PENDING")) {
- pending = true;
- continue;
- }
- }
+ .fetchBackupList({
+ parent: props.database.name,
+ })
+ .then((backups) => {
+ const pending = backups.some(
+ (backup) => backup.state === Backup_BackupState.PENDING_CREATE
+ );
if (pending) {
pollBackups(Math.min(interval * 2, NORMAL_POLL_INTERVAL));
}
@@ -410,7 +427,7 @@ const pollBackups = (interval: number) => {
};
const prepareBackupSetting = () => {
- backupStore
+ legacyBackupStore
.fetchBackupSettingByDatabaseId(Number(props.database.uid))
.then((backupSetting: BackupSetting) => {
// UNKNOWN_ID means database does not have backup setting and we should NOT overwrite the default setting.
@@ -431,7 +448,7 @@ const updateBackupHookUrl = () => {
retentionPeriodTs: state.autoBackupRetentionPeriodTs,
hookUrl: state.autoBackupUpdatedHookUrl,
};
- backupStore
+ legacyBackupStore
.upsertBackupSetting({
newBackupSetting: newBackupSetting,
})
diff --git a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
index d722afa2c4..aa381b87ee 100644
--- a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
+++ b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
@@ -278,9 +278,11 @@ const earliest = computed((): number => {
if (!pitrAvailable.value) {
return Infinity;
}
- const timestamps = doneBackupList.value.map((backup) => backup.createdTs);
+ const timestamps = doneBackupList.value.map(
+ (backup) => backup.createTime?.getTime() ?? 0
+ );
const earliestAllowedRestoreTS = Math.min(...timestamps);
- return earliestAllowedRestoreTS * 1000;
+ return earliestAllowedRestoreTS;
});
// Returns error message (string) if error occurs.
diff --git a/frontend/src/components/misc/HumanizeDate.vue b/frontend/src/components/misc/HumanizeDate.vue
new file mode 100644
index 0000000000..0b1611f997
--- /dev/null
+++ b/frontend/src/components/misc/HumanizeDate.vue
@@ -0,0 +1,34 @@
+<template>
+ <NTooltip trigger="hover">
+ <template #trigger>
+ <span v-bind="$attrs">{{ humanized }}</span>
+ </template>
+
+ <span class="whitespace-nowrap">{{ detail }}</span>
+ </NTooltip>
+</template>
+
+<script lang="ts" setup>
+import { PropType, computed } from "vue";
+import dayjs from "dayjs";
+import { NTooltip } from "naive-ui";
+
+import { humanizeDate } from "@/utils";
+
+const props = defineProps({
+ date: {
+ type: Object as PropType<Date>,
+ default: undefined,
+ },
+ format: {
+ type: String,
+ default: "YYYY-MM-DD HH:mm:ss UTCZZ",
+ },
+});
+
+const humanized = computed(() => humanizeDate(props.date));
+
+const detail = computed(() =>
+ dayjs(props.date?.getTime() ?? 0).format(props.format)
+);
+</script>
diff --git a/frontend/src/plugins/pitr/index.ts b/frontend/src/plugins/pitr/index.ts
index 2e0ba34cf7..38f2e735f8 100644
--- a/frontend/src/plugins/pitr/index.ts
+++ b/frontend/src/plugins/pitr/index.ts
@@ -6,7 +6,7 @@ import {
PITRContext,
} from "@/types";
import {
- useBackupListByDatabaseId,
+ useBackupListByDatabaseName,
useChangeHistoryStore,
useCurrentUserV1,
useIssueStore,
@@ -16,6 +16,7 @@ import { extractUserUID, semverCompare } from "@/utils";
import { Instance } from "@/types/proto/v1/instance_service";
import { Engine } from "@/types/proto/v1/common";
import { head } from "lodash-es";
+import { Backup_BackupState } from "@/types/proto/v1/database_service";
export const MIN_PITR_SUPPORT_MYSQL_VERSION = "8.0.0";
@@ -32,11 +33,13 @@ export const usePITRLogic = (database: Ref<ComposedDatabase>) => {
const currentUserV1 = useCurrentUserV1();
const changeHistoryStore = useChangeHistoryStore();
- const backupList = useBackupListByDatabaseId(
- computed(() => Number(database.value.uid))
+ const backupList = useBackupListByDatabaseName(
+ computed(() => database.value.name)
);
const doneBackupList = computed(() =>
- backupList.value.filter((backup) => backup.status === "DONE")
+ backupList.value.filter(
+ (backup) => backup.state === Backup_BackupState.DONE
+ )
);
const pitrAvailable = computed((): { result: boolean; message: string } => {
diff --git a/frontend/src/store/modules/backup.ts b/frontend/src/store/modules/backup.ts
index d5e20c33ad..86887d456b 100644
--- a/frontend/src/store/modules/backup.ts
+++ b/frontend/src/store/modules/backup.ts
@@ -1,9 +1,7 @@
-import { computed, Ref, watchEffect } from "vue";
import { defineStore } from "pinia";
import axios from "axios";
import {
Backup,
- BackupCreate,
BackupSetting,
BackupSettingState,
BackupSettingUpsert,
@@ -12,7 +10,6 @@ import {
ResourceObject,
unknown,
} from "@/types";
-import { useAuthStore } from "./auth";
export function convertBackup(
backup: ResourceObject,
@@ -34,7 +31,7 @@ function convertBackupSetting(
};
}
-export const useBackupStore = defineStore("backup", {
+export const useLegacyBackupStore = defineStore("backup", {
state: (): BackupState & BackupSettingState => ({
backupList: new Map(),
backupSetting: new Map(),
@@ -44,10 +41,6 @@ export const useBackupStore = defineStore("backup", {
convert(backup: ResourceObject, includedList: ResourceObject[]): Backup {
return convertBackup(backup, includedList || []);
},
-
- backupListByDatabaseId(databaseId: DatabaseId): Backup[] {
- return this.backupList.get(databaseId) || [];
- },
backupSettingByDatabaseId(databaseId: DatabaseId): BackupSetting {
return (
this.backupSetting.get(databaseId) ||
@@ -55,38 +48,6 @@ export const useBackupStore = defineStore("backup", {
);
},
- setTableListByDatabaseId({
- databaseId,
- backupList,
- }: {
- databaseId: DatabaseId;
- backupList: Backup[];
- }) {
- this.backupList.set(databaseId, backupList);
- },
-
- setBackupByDatabaseIdAndBackupName({
- databaseId,
- backupName,
- backup,
- }: {
- databaseId: DatabaseId;
- backupName: string;
- backup: Backup;
- }) {
- const list = this.backupList.get(databaseId);
- if (list) {
- const i = list.findIndex((item: Backup) => item.name == backupName);
- if (i != -1) {
- list[i] = backup;
- } else {
- list.push(backup);
- }
- } else {
- this.backupList.set(databaseId, [backup]);
- }
- },
-
upsertBackupSettingByDatabaseId({
databaseId,
backupSetting,
@@ -96,41 +57,6 @@ export const useBackupStore = defineStore("backup", {
}) {
this.backupSetting.set(databaseId, backupSetting);
},
- async createBackup({
- databaseId,
- newBackup,
- }: {
- databaseId: DatabaseId;
- newBackup: BackupCreate;
- }) {
- const data = (
- await axios.post(`/api/database/${newBackup.databaseId}/backup`, {
- data: {
- type: "BackupCreate",
- attributes: newBackup,
- },
- })
- ).data;
- const createdBackup: Backup = convertBackup(data.data, data.included);
-
- this.setBackupByDatabaseIdAndBackupName({
- databaseId: databaseId,
- backupName: createdBackup.name,
- backup: createdBackup,
- });
-
- return createdBackup;
- },
-
- async fetchBackupListByDatabaseId(databaseId: DatabaseId) {
- const data = (await axios.get(`/api/database/${databaseId}/backup`)).data;
- const backupList = data.data.map((backup: ResourceObject) => {
- return convertBackup(backup, data.included);
- });
-
- this.setTableListByDatabaseId({ databaseId, backupList });
- return backupList;
- },
async fetchBackupSettingByDatabaseId(databaseId: DatabaseId) {
const data = (
@@ -188,16 +114,3 @@ export const useBackupStore = defineStore("backup", {
},
},
});
-
-export const useBackupListByDatabaseId = (databaseId: Ref<DatabaseId>) => {
- const store = useBackupStore();
- const authStore = useAuthStore();
- watchEffect(() => {
- if (!authStore.isLoggedIn()) {
- return;
- }
- store.fetchBackupListByDatabaseId(databaseId.value);
- });
-
- return computed(() => store.backupListByDatabaseId(databaseId.value));
-};
diff --git a/frontend/src/store/modules/v1/backup.ts b/frontend/src/store/modules/v1/backup.ts
new file mode 100644
index 0000000000..7fcd1673b0
--- /dev/null
+++ b/frontend/src/store/modules/v1/backup.ts
@@ -0,0 +1,64 @@
+import { defineStore } from "pinia";
+import { computed, reactive, unref, watch } from "vue";
+
+import { databaseServiceClient } from "@/grpcweb";
+import { Backup, ListBackupRequest } from "@/types/proto/v1/database_service";
+import { MaybeRef } from "@/types";
+import { useAuthStore } from "../auth";
+
+export const useBackupV1Store = defineStore("backup_v1", () => {
+ const backupListMapByDatabase = reactive(new Map<string, Backup[]>());
+
+ const upsertBackupListMap = (parent: string, backups: Backup[]) => {
+ backupListMapByDatabase.set(parent, backups);
+ };
+
+ const backupListByDatabase = (database: string) => {
+ return backupListMapByDatabase.get(database) ?? [];
+ };
+ const fetchBackupList = async (params: Partial<ListBackupRequest>) => {
+ const { parent } = params;
+ if (!parent) {
+ throw new Error('"parent" parameter is required');
+ }
+ const { backups } = await databaseServiceClient.listBackup(params);
+ upsertBackupListMap(parent, backups);
+ return backups;
+ };
+ const createBackup = async (
+ backup: Backup,
+ parent: string,
+ refreshList = true
+ ) => {
+ const created = await databaseServiceClient.createBackup({
+ parent,
+ backup,
+ });
+ if (refreshList) {
+ await fetchBackupList({ parent });
+ }
+ return created;
+ };
+
+ return { backupListByDatabase, fetchBackupList, createBackup };
+});
+
+export const useBackupListByDatabaseName = (name: MaybeRef<string>) => {
+ const store = useBackupV1Store();
+ const authStore = useAuthStore();
+ watch(
+ [() => authStore.isLoggedIn(), () => unref(name)],
+ ([isLoggedIn, name]) => {
+ if (!isLoggedIn) return;
+
+ store.fetchBackupList({
+ parent: name,
+ });
+ },
+ {
+ immediate: true,
+ }
+ );
+
+ return computed(() => store.backupListByDatabase(unref(name)));
+};
diff --git a/frontend/src/store/modules/v1/dataSource.ts b/frontend/src/store/modules/v1/dataSource.ts
deleted file mode 100644
index 65d2271a40..0000000000
--- a/frontend/src/store/modules/v1/dataSource.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { defineStore } from "pinia";
-
-export const useDataSourceV1Store = defineStore("dataSource_v1", () => {
- return {};
-});
diff --git a/frontend/src/store/modules/v1/database.ts b/frontend/src/store/modules/v1/database.ts
index ab25c965fb..6bc26c85d4 100644
--- a/frontend/src/store/modules/v1/database.ts
+++ b/frontend/src/store/modules/v1/database.ts
@@ -235,7 +235,7 @@ const batchComposeDatabase = async (databaseList: Database[]) => {
const distinctProjectList = uniq(databaseList.map((db) => db.project));
const distinctInstanceList = uniq(
databaseList
- .map((db) => extractDatabaseResourceName(db.name).instance)
+ .map((db) => `instances/${extractDatabaseResourceName(db.name).instance}`)
.filter((instance) => instance !== UNKNOWN_INSTANCE_NAME)
);
await Promise.all(
@@ -253,7 +253,7 @@ const batchComposeDatabase = async (databaseList: Database[]) => {
const extractedResourceNames = extractDatabaseResourceName(db.name);
composed.databaseName = extractedResourceNames.database;
- composed.instance = extractedResourceNames.instance;
+ composed.instance = `instances/${extractedResourceNames.instance}`;
const instanceEntity =
composed.instance === UNKNOWN_INSTANCE_NAME
? unknownInstance()
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index b504be99dc..bc336b6836 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -1,5 +1,6 @@
export * from "./environment";
export * from "./database";
+export * from "./backup";
export * from "./project";
export * from "./projectIamPolicy";
export * from "./projectWebhook";
@@ -7,7 +8,6 @@ export * from "./deploymentConfig";
export * from "./databaseSecret";
export * from "./sheet";
export * from "./policy";
-export * from "./dataSource";
export * from "./setting";
export * from "./instance";
export * from "./subscription";
diff --git a/frontend/src/utils/v1/backup.ts b/frontend/src/utils/v1/backup.ts
new file mode 100644
index 0000000000..c41d311779
--- /dev/null
+++ b/frontend/src/utils/v1/backup.ts
@@ -0,0 +1,5 @@
+export const extractBackupResourceName = (name: string) => {
+ const pattern = /(?:^|\/)backups\/([^/]+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
+};
diff --git a/frontend/src/utils/v1/changeHistory.ts b/frontend/src/utils/v1/changeHistory.ts
index ece6f12d64..458b0a9696 100644
--- a/frontend/src/utils/v1/changeHistory.ts
+++ b/frontend/src/utils/v1/changeHistory.ts
@@ -2,7 +2,6 @@ import slug from "slug";
import { UNKNOWN_ID } from "@/types";
import { ChangeHistory } from "@/types/proto/v1/database_service";
import { extractDatabaseResourceName } from "./database";
-import { extractInstanceResourceName } from "./instance";
export const extractChangeHistoryUID = (changeHistorySlug: string) => {
const parts = changeHistorySlug.split("-");
@@ -15,8 +14,7 @@ export const changeHistorySlug = (uid: string, version: string): string => {
export const changeHistoryLink = (changeHistory: ChangeHistory): string => {
const { name, uid, version } = changeHistory;
- const { database } = extractDatabaseResourceName(name);
- const instance = extractInstanceResourceName(name);
+ const { instance, database } = extractDatabaseResourceName(name);
const parent = `instances/${instance}/databases/${database}`;
return `/${parent}/changeHistories/${changeHistorySlug(uid, version)}`;
};
diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.ts
index acab44325f..5acd672781 100644
--- a/frontend/src/utils/v1/database.ts
+++ b/frontend/src/utils/v1/database.ts
@@ -1,11 +1,7 @@
import { orderBy } from "lodash-es";
import slug from "slug";
-import {
- ComposedDatabase,
- unknownEnvironment,
- UNKNOWN_INSTANCE_NAME,
-} from "@/types";
+import { ComposedDatabase, unknownEnvironment, UNKNOWN_ID } from "@/types";
import { EnvironmentTier } from "@/types/proto/v1/environment_service";
import { Policy, PolicyType } from "@/types/proto/v1/org_policy_service";
import { User } from "@/types/proto/v1/auth_service";
@@ -26,14 +22,14 @@ export const databaseV1Slug = (db: ComposedDatabase) => {
export const extractDatabaseResourceName = (
resource: string
): {
- instance: string /** Format: instances/{instance} */;
+ instance: string;
database: string;
} => {
const pattern =
- /(?:^|\/)(?<instance>instances\/[^/]+)\/databases\/(?<database>[^/]+)(?:$|\/)/;
+ /(?:^|\/)instances\/(?<instance>[^/]+)\/databases\/(?<database>[^/]+)(?:$|\/)/;
const matches = resource.match(pattern);
if (matches) {
- const { instance = UNKNOWN_INSTANCE_NAME, database = "" } =
+ const { instance = String(UNKNOWN_ID), database = "" } =
matches.groups ?? {};
return {
instance,
@@ -41,7 +37,7 @@ export const extractDatabaseResourceName = (
};
}
return {
- instance: UNKNOWN_INSTANCE_NAME,
+ instance: String(UNKNOWN_ID),
database: "",
};
};
diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.ts
index c1fb3d0849..80ba4a9194 100644
--- a/frontend/src/utils/v1/index.ts
+++ b/frontend/src/utils/v1/index.ts
@@ -2,6 +2,7 @@ export * from "./common";
export * from "./environment";
export * from "./instance";
export * from "./database";
+export * from "./backup";
export * from "./databaseLabel";
export * from "./project";
export * from "./projectWebhook";
diff --git a/frontend/src/views/EnvironmentDetail.vue b/frontend/src/views/EnvironmentDetail.vue
index f75176baac..db9d6e313f 100644
--- a/frontend/src/views/EnvironmentDetail.vue
+++ b/frontend/src/views/EnvironmentDetail.vue
@@ -53,7 +53,7 @@ import { computed, reactive, watchEffect } from "vue";
import ArchiveBanner from "../components/ArchiveBanner.vue";
import EnvironmentForm from "../components/EnvironmentForm.vue";
import { idFromSlug } from "../utils";
-import { hasFeature, pushNotification, useBackupStore } from "@/store";
+import { hasFeature, pushNotification, useLegacyBackupStore } from "@/store";
import { useI18n } from "vue-i18n";
import { cloneDeep } from "lodash-es";
import BBModal from "@/bbkit/BBModal.vue";
@@ -104,7 +104,7 @@ const emit = defineEmits(["archive"]);
const environmentV1Store = useEnvironmentV1Store();
const policyV1Store = usePolicyV1Store();
-const backupStore = useBackupStore();
+const backupStore = useLegacyBackupStore();
const { t } = useI18n();
const state = reactive<LocalState>({