feat(nacos): show conflict config diff in copy preview

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-08 16:47:39 +08:00
1 parent 538aeed99c
commit cbd769d36b
5 files changed
+134 -11

No files matched your search

@@ -1,11 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from "vue"; import { computed, ref, watch } from "vue";
import { AlertTriangle, Archive, CheckCircle2, FileUp, Loader2 } from "@lucide/vue"; import { AlertTriangle, Archive, CheckCircle2, FileUp, GitCompareArrows, Loader2 } from "@lucide/vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import NacosConfigDiffDialog from "@/components/nacos/NacosConfigDiffDialog.vue";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import type { NacosBatchPreview, NacosBatchReport, NacosConfigDataIdMapping, NacosConfigKey, NacosConfigSelectionScope, NacosConflictPolicy, NacosNamespaceInfo } from "@/types/nacos"; import type { NacosBatchPreview, NacosBatchPreviewDiff, NacosBatchReport, NacosConfigDataIdMapping, NacosConfigKey, NacosConfigSelectionScope, NacosConflictPolicy, NacosNamespaceInfo } from "@/types/nacos";
import { nacosNamespaceIdentity } from "@/lib/nacos/nacosNamespaceVisibility"; import { nacosNamespaceIdentity } from "@/lib/nacos/nacosNamespaceVisibility";
export type NacosBatchDialogMode = "export" | "import" | "copy"; export type NacosBatchDialogMode = "export" | "import" | "copy";
@@ -58,6 +59,8 @@ const policy = ref<NacosConflictPolicy>("ABORT");
const targetNamespace = ref(""); const targetNamespace = ref("");
const targetGroup = ref(""); const targetGroup = ref("");
const targetDataIdDrafts = ref<NacosConfigDataIdMapping[]>([]); const targetDataIdDrafts = ref<NacosConfigDataIdMapping[]>([]);
const previewDiffOpen = ref(false);
const selectedPreviewDiff = ref<NacosBatchPreviewDiff | null>(null);
const titleKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Title`); const titleKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Title`);
const descriptionKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Description`); const descriptionKey = computed(() => `nacos.batch${props.mode[0].toUpperCase()}${props.mode.slice(1)}Description`);
@@ -117,6 +120,11 @@ function batchStatusClass(status: string) {
return "text-muted-foreground"; return "text-muted-foreground";
} }
function showPreviewDiff(diff: NacosBatchPreviewDiff) {
selectedPreviewDiff.value = diff;
previewDiffOpen.value = true;
}
function resetTargetNamespace() { function resetTargetNamespace() {
if (targetNamespaces.value.some((item) => JSON.stringify(item.namespace) === targetNamespace.value)) return; if (targetNamespaces.value.some((item) => JSON.stringify(item.namespace) === targetNamespace.value)) return;
targetNamespace.value = targetNamespaces.value[0] ? JSON.stringify(targetNamespaces.value[0].namespace) : ""; targetNamespace.value = targetNamespaces.value[0] ? JSON.stringify(targetNamespaces.value[0].namespace) : "";
@@ -171,6 +179,14 @@ watch(
watch(targetNamespaces, () => { watch(targetNamespaces, () => {
if (props.open) resetTargetNamespace(); if (props.open) resetTargetNamespace();
}); });
watch(
() => props.preview,
() => {
previewDiffOpen.value = false;
selectedPreviewDiff.value = null;
},
);
</script> </script>
<template> <template>
@@ -302,7 +318,12 @@ watch(targetNamespaces, () => {
<div class="truncate text-muted-foreground">{{ item.group }} · {{ item.namespace || "public" }}</div> <div class="truncate text-muted-foreground">{{ item.group }} · {{ item.namespace || "public" }}</div>
<div v-if="item.message" class="break-all text-destructive">{{ item.message }}</div> <div v-if="item.message" class="break-all text-destructive">{{ item.message }}</div>
</div> </div>
<Badge variant="outline" :class="batchStatusClass(item.status)">{{ batchStatusLabel(item.status) }}</Badge> <div class="flex shrink-0 items-center gap-1">
<Button v-if="item.diff" size="icon" variant="ghost" class="h-7 w-7" :title="t('nacos.configDiffTitle')" :aria-label="t('nacos.configDiffTitle')" @click="showPreviewDiff(item.diff)">
<GitCompareArrows class="h-4 w-4" />
</Button>
<Badge variant="outline" :class="batchStatusClass(item.status)">{{ batchStatusLabel(item.status) }}</Badge>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -358,4 +379,6 @@ watch(targetNamespaces, () => {
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
<NacosConfigDiffDialog v-model:open="previewDiffOpen" :before="selectedPreviewDiff?.beforeContent ?? ''" :after="selectedPreviewDiff?.afterContent ?? ''" :format="selectedPreviewDiff?.format" :show-confirm="false" />
</template> </template>
@@ -4,7 +4,20 @@ import { createApp, defineComponent, h, nextTick, type App } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n"; import i18n from "@/i18n";
import NacosConfigBatchDialog from "@/components/nacos/NacosConfigBatchDialog.vue"; import NacosConfigBatchDialog from "@/components/nacos/NacosConfigBatchDialog.vue";
import type { NacosBatchReport, NacosConfigKey } from "@/types/nacos"; import type { NacosBatchPreview, NacosBatchReport, NacosConfigKey } from "@/types/nacos";
vi.mock("@/components/nacos/NacosConfigDiffDialog.vue", () => ({
default: defineComponent({
props: {
open: Boolean,
before: String,
after: String,
format: String,
showConfirm: Boolean,
},
template: '<div v-if="open" data-testid="nacos-preview-diff" :data-before="before" :data-after="after" :data-format="format" :data-show-confirm="showConfirm" />',
}),
}));
const mountedApps: App[] = []; const mountedApps: App[] = [];
@@ -16,6 +29,7 @@ async function mountDialog(
], ],
report: NacosBatchReport | null = null, report: NacosBatchReport | null = null,
selectedKeys: NacosConfigKey[] = [{ namespace: "shared", group: "DEFAULT_GROUP", dataId: "app.yaml" }], selectedKeys: NacosConfigKey[] = [{ namespace: "shared", group: "DEFAULT_GROUP", dataId: "app.yaml" }],
preview: NacosBatchPreview | null = null,
) { ) {
const onTargetConnectionChange = vi.fn(); const onTargetConnectionChange = vi.fn();
const onPreview = vi.fn(); const onPreview = vi.fn();
@@ -39,7 +53,7 @@ async function mountDialog(
sourceConnectionId: "source", sourceConnectionId: "source",
currentNamespace: "shared", currentNamespace: "shared",
namespaces, namespaces,
preview: null, preview,
report, report,
onTargetConnectionChange, onTargetConnectionChange,
onPreview, onPreview,
@@ -232,4 +246,32 @@ describe("NacosConfigBatchDialog cross-connection sync", () => {
expect(document.body.textContent).toContain("Failed"); expect(document.body.textContent).toContain("Failed");
expect(document.body.textContent).toContain("target unavailable"); expect(document.body.textContent).toContain("target unavailable");
}); });
it("opens a read-only diff for a conflicting copy preview", async () => {
await mountDialog("remote", undefined, null, undefined, {
planHash: "preview-hash",
total: 1,
created: 0,
conflicts: 1,
invalid: 0,
items: [
{
namespace: "shared",
group: "DEFAULT_GROUP",
dataId: "app.yaml",
status: "conflict",
diff: { beforeContent: "port: 8080", afterContent: "port: 9090", format: "yaml" },
},
],
});
(document.body.querySelector('[aria-label="Config Content Compare"]') as HTMLButtonElement).click();
await nextTick();
const diff = document.body.querySelector("[data-testid=nacos-preview-diff]") as HTMLElement;
expect(diff.dataset.before).toBe("port: 8080");
expect(diff.dataset.after).toBe("port: 9090");
expect(diff.dataset.format).toBe("yaml");
expect(diff.dataset.showConfirm).toBe("false");
});
}); });
+7
View File
@@ -358,12 +358,19 @@ export interface NacosConfigSelector {
export type NacosConflictPolicy = "ABORT" | "SKIP" | "OVERWRITE"; export type NacosConflictPolicy = "ABORT" | "SKIP" | "OVERWRITE";
export interface NacosBatchPreviewDiff {
beforeContent: string;
afterContent: string;
format?: string;
}
export interface NacosBatchPreviewItem { export interface NacosBatchPreviewItem {
namespace: string; namespace: string;
group: string; group: string;
dataId: string; dataId: string;
status: string; status: string;
message?: string; message?: string;
diff?: NacosBatchPreviewDiff;
} }
export interface NacosBatchPreview { export interface NacosBatchPreview {
+46 -6
View File
@@ -11,8 +11,9 @@ use crate::nacos::port::NacosAdmin;
use crate::nacos::search::{begin_operation, finish_operation}; use crate::nacos::search::{begin_operation, finish_operation};
use crate::nacos::service::{ensure_connection_writable, get_admin}; use crate::nacos::service::{ensure_connection_writable, get_admin};
use crate::nacos::types::{ use crate::nacos::types::{
NacosBatchItemResult, NacosBatchPreview, NacosBatchPreviewItem, NacosBatchReport, NacosConfigItem, NacosConfigKey, NacosBatchItemResult, NacosBatchPreview, NacosBatchPreviewDiff, NacosBatchPreviewItem, NacosBatchReport,
NacosConfigSelectionScope, NacosConfigSelector, NacosConfigTransferRequest, NacosConfigUpsert, NacosConflictPolicy, NacosConfigItem, NacosConfigKey, NacosConfigSelectionScope, NacosConfigSelector, NacosConfigTransferRequest,
NacosConfigUpsert, NacosConflictPolicy,
}; };
const PAGE_SIZE: u32 = 500; const PAGE_SIZE: u32 = 500;
@@ -64,7 +65,7 @@ pub async fn preview_import(
archive_path: &Path, archive_path: &Path,
) -> Result<NacosBatchPreview, String> { ) -> Result<NacosBatchPreview, String> {
let configs = read_archive(archive_path, target_namespace).await?; let configs = read_archive(archive_path, target_namespace).await?;
preview_configs(admin, &configs).await preview_configs(admin, &configs, false).await
} }
pub async fn apply_import( pub async fn apply_import(
@@ -85,7 +86,7 @@ pub async fn preview_transfer(
request: &NacosConfigTransferRequest, request: &NacosConfigTransferRequest,
) -> Result<NacosBatchPreview, String> { ) -> Result<NacosBatchPreview, String> {
let configs = transfer_configs(source_admin, request).await?; let configs = transfer_configs(source_admin, request).await?;
preview_configs(target_admin, &configs).await preview_configs(target_admin, &configs, true).await
} }
pub async fn apply_transfer( pub async fn apply_transfer(
@@ -330,6 +331,7 @@ async fn resolve_selector(
async fn preview_configs( async fn preview_configs(
admin: Arc<dyn NacosAdmin>, admin: Arc<dyn NacosAdmin>,
configs: &[NacosConfigUpsert], configs: &[NacosConfigUpsert],
include_diff: bool,
) -> Result<NacosBatchPreview, String> { ) -> Result<NacosBatchPreview, String> {
let mut items = Vec::with_capacity(configs.len()); let mut items = Vec::with_capacity(configs.len());
let mut target_snapshots = Vec::with_capacity(configs.len()); let mut target_snapshots = Vec::with_capacity(configs.len());
@@ -344,6 +346,17 @@ async fn preview_configs(
created += 1; created += 1;
"create" "create"
}; };
let diff = if include_diff {
target.as_ref().and_then(|target| {
target.content.as_ref().map(|before_content| NacosBatchPreviewDiff {
before_content: before_content.clone(),
after_content: config.content.clone(),
format: config.config_type.clone(),
})
})
} else {
None
};
target_snapshots.push(target); target_snapshots.push(target);
items.push(NacosBatchPreviewItem { items.push(NacosBatchPreviewItem {
namespace: config.namespace.clone().unwrap_or_default(), namespace: config.namespace.clone().unwrap_or_default(),
@@ -351,6 +364,7 @@ async fn preview_configs(
data_id: config.data_id.clone(), data_id: config.data_id.clone(),
status: status.to_string(), status: status.to_string(),
message: None, message: None,
diff,
}); });
} }
Ok(NacosBatchPreview { Ok(NacosBatchPreview {
@@ -370,7 +384,7 @@ async fn apply_configs(
expected_plan_hash: &str, expected_plan_hash: &str,
policy: &NacosConflictPolicy, policy: &NacosConflictPolicy,
) -> Result<NacosBatchReport, String> { ) -> Result<NacosBatchReport, String> {
let preview = preview_configs(admin.clone(), &configs).await?; let preview = preview_configs(admin.clone(), &configs, false).await?;
if preview.plan_hash != expected_plan_hash { if preview.plan_hash != expected_plan_hash {
return Err( return Err(
"NACOS_ERROR[stalePreview]: Nacos import/copy preview is stale; preview again before applying".to_string() "NACOS_ERROR[stalePreview]: Nacos import/copy preview is stale; preview again before applying".to_string()
@@ -750,7 +764,7 @@ mod tests {
} }
async fn preview_hash(admin: Arc<MockAdmin>, configs: &[NacosConfigUpsert]) -> String { async fn preview_hash(admin: Arc<MockAdmin>, configs: &[NacosConfigUpsert]) -> String {
preview_configs(admin, configs).await.unwrap().plan_hash preview_configs(admin, configs, false).await.unwrap().plan_hash
} }
#[tokio::test] #[tokio::test]
@@ -1107,4 +1121,30 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!(published.content.as_deref(), Some("value")); assert_eq!(published.content.as_deref(), Some("value"));
} }
#[tokio::test]
async fn transfer_preview_includes_conflict_content_diff() {
let source_admin = source_admin_with_config();
let target_admin = Arc::new(MockAdmin::default());
target_admin.insert(NacosConfigItem {
data_id: "app".to_string(),
group: "SOURCE_GROUP".to_string(),
namespace: "target-ns".to_string(),
app_name: None,
desc: None,
tags: None,
config_type: Some("text".to_string()),
md5: Some("target-md5".to_string()),
encrypted_data_key: None,
content: Some("old value".to_string()),
});
let preview = preview_transfer(source_admin, target_admin, &transfer_request(None)).await.unwrap();
let diff = preview.items[0].diff.as_ref().expect("conflicting transfer should include a diff");
assert_eq!(preview.items[0].status, "conflict");
assert_eq!(diff.before_content, "old value");
assert_eq!(diff.after_content, "value");
assert_eq!(diff.format.as_deref(), Some("text"));
}
} }
+11
View File
@@ -766,6 +766,15 @@ pub enum NacosConflictPolicy {
Overwrite, Overwrite,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct NacosBatchPreviewDiff {
pub before_content: String,
pub after_content: String,
#[serde(default)]
pub format: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct NacosBatchPreviewItem { pub struct NacosBatchPreviewItem {
@@ -775,6 +784,8 @@ pub struct NacosBatchPreviewItem {
pub status: String, pub status: String,
#[serde(default)] #[serde(default)]
pub message: Option<String>, pub message: Option<String>,
#[serde(default)]
pub diff: Option<NacosBatchPreviewDiff>,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]