Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

20.1 KB
Raw Blame
// @vitest-environment happy-dom

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createApp, nextTick, type App } from "vue";
import type { PeekedMessage, SubscriptionInfo } from "@/types/mq";

const backend = vi.hoisted(() => ({
  mqListSubscriptions: vi.fn(),
  mqEnrichSubscriptions: vi.fn(),
  mqCreateSubscription: vi.fn(),
  mqDeleteSubscription: vi.fn(),
  mqResetCursor: vi.fn(),
  mqSkipMessages: vi.fn(),
  mqClearBacklog: vi.fn(),
  mqPeekMessages: vi.fn(),
  mqExpireMessages: vi.fn(),
}));

vi.mock("vue-i18n", () => ({
  useI18n: () => ({ t: (key: string, params?: { count?: number }) => (key === "mqSubscriptions.consumerCount" ? `${params?.count}` : key) }),
}));

vi.mock("@/lib/backend/api", () => backend);

vi.mock("@/composables/useMqMutationGuard", () => ({
  useMqMutationGuard: () => ({ confirmMqWrite: vi.fn().mockResolvedValue(true) }),
}));

vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({
  default: {
    props: ["open", "title", "confirmLabel", "loading", "closeOnConfirm"],
    emits: ["update:open", "confirm"],
    template: `
      <div v-if="open" role="dialog" :aria-label="title">
        <slot name="options" />
        <button :disabled="loading" @click="$emit('update:open', false)">dangerDialog.cancel</button>
        <button :disabled="loading" @click="closeOnConfirm !== false && $emit('update:open', false); $emit('confirm')">{{ confirmLabel }}</button>
      </div>
    `,
  },
}));

vi.mock("@/components/mq/rocketmq/RocketMqConsumerGroupDialogs.vue", () => ({
  default: { template: "<div />" },
}));

import SubscriptionsPanel from "@/components/mq/SubscriptionsPanel.vue";

const TOPIC = {
  name: "persistent://public/default/events",
  shortName: "events",
  partitioned: false,
  persistent: true,
};

let app: App<Element> | null = null;
let root: HTMLDivElement | null = null;

async function flushUi() {
  await Promise.resolve();
  await Promise.resolve();
  await nextTick();
}

function buttonByText(container: ParentNode, text: string): HTMLButtonElement {
  const button = [...container.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.includes(text));
  if (!button) throw new Error(`Button not found: ${text}`);
  return button;
}

function buttonWithExactText(container: ParentNode, text: string): HTMLButtonElement {
  const button = [...container.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.trim() === text);
  if (!button) throw new Error(`Button not found: ${text}`);
  return button;
}

function deferred<T>() {
  let resolve!: (value: T) => void;
  let reject!: (reason: unknown) => void;
  const promise = new Promise<T>((resolvePromise, rejectPromise) => {
    resolve = resolvePromise;
    reject = rejectPromise;
  });
  return { promise, resolve, reject };
}

async function mountPanel(overrides: Record<string, unknown> = {}) {
  root = document.createElement("div");
  document.body.appendChild(root);
  app = createApp(SubscriptionsPanel, {
    connectionId: "mq-1",
    topic: TOPIC,
    tenant: "_kafka",
    namespace: "default",
    mqSystemKind: "kafka",
    supportsResetCursor: true,
    supportsClearBacklog: true,
    supportsPeekMessages: true,
    ...overrides,
  });
  app.mount(root);
  await flushUi();
  return root;
}

function subscription(name: string, consumerGroupType: string): SubscriptionInfo {
  return {
    name,
    subType: consumerGroupType,
    consumerGroupType,
    messageModel: "CLUSTERING",
    msgBacklog: 0,
    msgRateOut: 0,
    msgThroughputOut: 0,
    consumers: [],
  };
}

beforeEach(() => {
  Object.values(backend).forEach((mock) => mock.mockReset());
  const rows = [
    {
      name: "orders-consumer",
      subType: "shared",
      msgBacklog: 0,
      msgRateOut: 0,
      msgThroughputOut: 0,
      consumers: [],
    },
  ];
  backend.mqListSubscriptions.mockResolvedValue(rows);
  backend.mqEnrichSubscriptions.mockResolvedValue(rows);
});

afterEach(() => {
  app?.unmount();
  app = null;
  root?.remove();
  root = null;
});

describe("SubscriptionsPanel Kafka partial results", () => {
  it.each([undefined, 0, 1])("distinguishes unavailable members from a known count of %s", async (onlineMembers) => {
    backend.mqListSubscriptions.mockResolvedValue([
      {
        ...subscription("orders-service", "consumer-group"),
        onlineMembers,
        backlogUnavailable: onlineMembers == null,
        consumers: Array.from({ length: onlineMembers ?? 0 }, () => ({ consumerName: "consumer-orders" })),
      },
    ]);
    const panel = await mountPanel();
    const row = panel.querySelector(".subscriptions-table tbody tr")!;

    expect(row.querySelector('[data-testid="online-members"]')?.textContent?.trim()).toBe(onlineMembers == null ? "-" : `${onlineMembers}`);
    expect(row.querySelectorAll("td")[2].textContent?.trim()).toBe(onlineMembers == null ? "-" : "0");
  });
});

describe("SubscriptionsPanel message peek", () => {
  it("warns when a Kafka peek is incomplete and clears the warning after a complete refresh", async () => {
    backend.mqPeekMessages
      .mockResolvedValueOnce({
        messages: [
          {
            position: 1,
            messageId: "17",
            payloadBase64: "",
            payloadText: "partial message",
            properties: { partition: "0" },
            headers: {},
          },
        ],
        incomplete: true,
      })
      .mockResolvedValueOnce({ messages: [], incomplete: false });
    const panel = await mountPanel();

    buttonByText(panel, "mqSubscriptions.peek").click();
    await flushUi();

    expect(backend.mqPeekMessages).toHaveBeenCalledWith("mq-1", expect.objectContaining({ topic: "events" }), "orders-consumer", 5);
    expect(panel.querySelector('[data-testid="peek-incomplete"]')?.textContent).toContain("mqMessages.peekIncomplete");
    expect(panel.textContent).toContain("partial message");

    buttonByText(panel, "mqSubscriptions.refresh").click();
    await flushUi();

    expect(panel.querySelector('[data-testid="peek-incomplete"]')).toBeNull();
  });

  it("ignores a stale peek when another subscription is opened", async () => {
    const first = deferred<{ messages: PeekedMessage[]; incomplete: boolean }>();
    const second = deferred<{ messages: PeekedMessage[]; incomplete: boolean }>();
    backend.mqListSubscriptions.mockResolvedValue([
      {
        name: "orders-consumer",
        subType: "shared",
        msgBacklog: 0,
        msgRateOut: 0,
        msgThroughputOut: 0,
        consumers: [],
      },
      {
        name: "payments-consumer",
        subType: "shared",
        msgBacklog: 0,
        msgRateOut: 0,
        msgThroughputOut: 0,
        consumers: [],
      },
    ]);
    backend.mqPeekMessages.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
    const panel = await mountPanel();

    const peekButtons = [...panel.querySelectorAll<HTMLButtonElement>("button")].filter((button) => button.textContent?.includes("mqSubscriptions.peek"));
    expect(peekButtons).toHaveLength(2);
    peekButtons[0].click();
    await flushUi();
    peekButtons[1].click();
    await flushUi();

    second.resolve({
      messages: [{ position: 1, messageId: "new", payloadBase64: "", payloadText: "payments message", properties: {}, headers: {} }],
      incomplete: false,
    });
    await flushUi();
    first.resolve({
      messages: [{ position: 1, messageId: "old", payloadBase64: "", payloadText: "orders message", properties: {}, headers: {} }],
      incomplete: false,
    });
    await flushUi();

    expect(panel.textContent).toContain("payments message");
    expect(panel.textContent).not.toContain("orders message");
  });
});

describe("SubscriptionsPanel clear backlog", () => {
  async function openClearBacklog(panel: HTMLDivElement) {
    buttonWithExactText(panel, "mqSubscriptions.clearBacklog").click();
    await flushUi();
    const dialog = panel.querySelector('[role="dialog"][aria-label="mqSubscriptions.clearBacklog"]');
    expect(dialog).not.toBeNull();
    return dialog!;
  }

  it("keeps a failed clear backlog open with the error in the dialog, not the panel", async () => {
    backend.mqClearBacklog.mockRejectedValueOnce(new Error("Cannot clear an active consumer group"));
    const panel = await mountPanel();
    const dialog = await openClearBacklog(panel);

    buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").click();
    await vi.waitFor(() => expect(dialog.querySelector(".form-error")?.textContent).toContain("Cannot clear an active consumer group"));

    expect(backend.mqClearBacklog).toHaveBeenCalledExactlyOnceWith("mq-1", { tenant: "_kafka", namespace: "default", topic: "events", persistent: true, partitioned: false }, "orders-consumer");
    expect(dialog.isConnected).toBe(true);
    expect(buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").disabled).toBe(false);
    expect(panel.querySelector(".panel-error")).toBeNull();
    expect(panel.querySelector(".subscriptions-table")?.textContent).toContain("orders-consumer");
    expect(backend.mqListSubscriptions).toHaveBeenCalledTimes(1);
  });

  it("clears the previous error when the dialog is closed and reopened", async () => {
    backend.mqClearBacklog.mockRejectedValueOnce(new Error("Previous clear backlog failed"));
    const panel = await mountPanel();
    const dialog = await openClearBacklog(panel);
    buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").click();
    await vi.waitFor(() => expect(dialog.textContent).toContain("Previous clear backlog failed"));

    buttonWithExactText(dialog, "dangerDialog.cancel").click();
    await flushUi();
    expect(dialog.isConnected).toBe(false);

    const reopenedDialog = await openClearBacklog(panel);
    expect(reopenedDialog.querySelector(".form-error")).toBeNull();
    expect(panel.textContent).not.toContain("Previous clear backlog failed");
    expect(panel.querySelector(".panel-error")).toBeNull();
  });

  it.each(["success", "failure"])("clears the previous error while retrying and handles retry %s", async (outcome) => {
    const retry = deferred<void>();
    backend.mqClearBacklog.mockRejectedValueOnce(new Error("First attempt failed")).mockReturnValueOnce(retry.promise);
    const panel = await mountPanel();
    const dialog = await openClearBacklog(panel);
    buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").click();
    await vi.waitFor(() => expect(dialog.textContent).toContain("First attempt failed"));

    buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").click();
    await vi.waitFor(() => expect(backend.mqClearBacklog).toHaveBeenCalledTimes(2));
    expect(dialog.querySelector(".form-error")).toBeNull();
    expect(dialog.isConnected).toBe(true);
    expect(buttonWithExactText(dialog, "mqSubscriptions.clearBacklog").disabled).toBe(true);

    if (outcome === "success") {
      backend.mqListSubscriptions.mockResolvedValue([{ ...subscription("orders-consumer", "shared"), msgBacklog: 123 }]);
      retry.resolve();
      await vi.waitFor(() => {
        expect(dialog.isConnected).toBe(false);
        expect(backend.mqListSubscriptions).toHaveBeenCalledTimes(2);
        expect(panel.querySelector(".subscriptions-table")?.textContent).toContain("123");
      });
    } else {
      retry.reject(new Error("Retry failed"));
      await vi.waitFor(() => expect(dialog.querySelector(".form-error")?.textContent).toContain("Retry failed"));
      expect(dialog.isConnected).toBe(true);
      expect(dialog.textContent).not.toContain("First attempt failed");
      expect(backend.mqListSubscriptions).toHaveBeenCalledTimes(1);
    }
    expect(panel.querySelector(".panel-error")).toBeNull();
  });

  it("keeps subscription list loading failures in the panel", async () => {
    backend.mqListSubscriptions.mockRejectedValueOnce(new Error("Subscription list failed"));
    const panel = await mountPanel();

    await vi.waitFor(() => expect(panel.querySelector(".panel-error")?.textContent).toContain("Subscription list failed"));
    expect(panel.querySelector('[role="dialog"]')).toBeNull();
  });
});

describe("SubscriptionsPanel Kafka absolute offset reset", () => {
  async function openAbsoluteReset(panel: HTMLDivElement) {
    await vi.waitFor(() => {
      expect([...panel.querySelectorAll("button")].some((button) => button.textContent?.includes("mqSubscriptions.resetCursor"))).toBe(true);
    });
    buttonByText(panel, "mqSubscriptions.resetCursor").click();
    await flushUi();
    const absolute = panel.querySelector<HTMLInputElement>('input[value="partitionOffset"]');
    expect(absolute).toBeTruthy();
    absolute!.checked = true;
    absolute!.dispatchEvent(new Event("change", { bubbles: true }));
    await vi.waitFor(() => {
      expect(panel.querySelector('[data-testid="reset-partition"]')).toBeTruthy();
    });
  }

  it("shows Kafka-only partition fields and dispatches one exact absolute offset", async () => {
    backend.mqResetCursor.mockResolvedValue(undefined);
    const panel = await mountPanel();
    await openAbsoluteReset(panel);

    const partition = panel.querySelector<HTMLInputElement>('[data-testid="reset-partition"]');
    const offset = panel.querySelector<HTMLInputElement>('[data-testid="reset-offset"]');
    expect(partition).toBeTruthy();
    expect(offset).toBeTruthy();
    partition!.value = "1";
    partition!.dispatchEvent(new Event("input", { bubbles: true }));
    offset!.value = "42";
    offset!.dispatchEvent(new Event("input", { bubbles: true }));

    buttonWithExactText(panel, "mqSubscriptions.reset").click();
    await flushUi();

    expect(backend.mqResetCursor).toHaveBeenCalledWith("mq-1", expect.objectContaining({ topic: "events" }), "orders-consumer", { kind: "partitionOffset", partition: 1, offset: 42 });
  });

  it.each([false, true])("refreshes after a closed reset succeeds without closing a new dialog (reopen: %s)", async (reopen) => {
    const reset = deferred<void>();
    backend.mqResetCursor.mockReturnValueOnce(reset.promise);
    const panel = await mountPanel();
    await openAbsoluteReset(panel);
    buttonWithExactText(panel, "mqSubscriptions.reset").click();
    await vi.waitFor(() => expect(backend.mqResetCursor).toHaveBeenCalledTimes(1));

    buttonWithExactText(panel, "mqSubscriptions.cancel").click();
    await flushUi();
    if (reopen) await openAbsoluteReset(panel);
    backend.mqListSubscriptions.mockResolvedValue([{ ...subscription("orders-consumer", "NORMAL"), msgBacklog: 123 }]);
    reset.resolve();

    await vi.waitFor(() => {
      expect(backend.mqListSubscriptions).toHaveBeenCalledTimes(2);
      expect(panel.querySelector(".subscriptions-table")?.textContent).toContain("123");
    });
    expect(panel.querySelector('input[value="partitionOffset"]') !== null).toBe(reopen);
    expect(panel.querySelector(".form-error")).toBeNull();
  });

  it("does not refresh after a reset succeeds on an unmounted panel", async () => {
    const reset = deferred<void>();
    backend.mqResetCursor.mockReturnValueOnce(reset.promise);
    const panel = await mountPanel();
    await openAbsoluteReset(panel);
    buttonWithExactText(panel, "mqSubscriptions.reset").click();
    await vi.waitFor(() => expect(backend.mqResetCursor).toHaveBeenCalledTimes(1));
    app!.unmount();
    app = null;
    reset.resolve();
    await flushUi();
    expect(backend.mqListSubscriptions).toHaveBeenCalledTimes(1);
  });

  it.each([
    ["partition", "-1"],
    ["partition", "1.5"],
    ["offset", "-1"],
    ["offset", "42.5"],
    ["offset", "9007199254740992"],
  ])("rejects invalid %s value %s", async (field, value) => {
    const panel = await mountPanel();
    await openAbsoluteReset(panel);
    const input = panel.querySelector<HTMLInputElement>(`[data-testid="reset-${field}"]`)!;
    input.value = value;
    input.dispatchEvent(new Event("input", { bubbles: true }));
    buttonWithExactText(panel, "mqSubscriptions.reset").click();
    await vi.waitFor(() => {
      expect(panel.textContent).toContain("mqSubscriptions.nonNegativeIntegerRequired");
    });
    expect(backend.mqResetCursor).not.toHaveBeenCalled();
  });

  it("hides the absolute offset option outside Kafka", async () => {
    const pulsarPanel = await mountPanel({ mqSystemKind: "pulsar", tenant: "public" });
    await vi.waitFor(() => {
      expect([...pulsarPanel.querySelectorAll("button")].some((button) => button.textContent?.includes("mqSubscriptions.resetCursor"))).toBe(true);
    });
    buttonByText(pulsarPanel, "mqSubscriptions.resetCursor").click();
    await flushUi();
    expect(pulsarPanel.querySelector('input[value="partitionOffset"]')).toBeNull();
  });
});

describe("SubscriptionsPanel RocketMQ online members", () => {
  it("shows '-' when onlineMembers is unknown before enrich completes", async () => {
    const enrich = deferred<ReturnType<typeof subscription>[]>();
    const rows = [subscription("orders-group", "NORMAL")];
    backend.mqListSubscriptions.mockResolvedValue(rows);
    backend.mqEnrichSubscriptions.mockReturnValueOnce(enrich.promise);

    const panel = await mountPanel({
      topic: undefined,
      tenant: "_rocketmq",
      namespace: "default",
      mqSystemKind: "rocketmq",
      supportsPeekMessages: false,
    });

    // Fast list paints before enrich; unknown member count must not look like healthy zero.
    const membersCell = () => panel.querySelector('[data-testid="online-members"]')?.textContent?.trim();
    expect(membersCell()).toBe("-");

    enrich.resolve([{ ...rows[0], onlineMembers: 2, topics: ["orders"] }]);
    await flushUi();
    expect(membersCell()).toBe("2");
  });
});

describe("SubscriptionsPanel RocketMQ filter count", () => {
  it("updates the visible/total count when type filters or search change", async () => {
    const rows = [subscription("orders-group", "NORMAL"), subscription("payments-fifo", "FIFO"), subscription("CID_SYS_GROUP", "SYSTEM"), subscription("orders-retry", "NORMAL")];
    backend.mqListSubscriptions.mockResolvedValue(rows);
    backend.mqEnrichSubscriptions.mockResolvedValue(rows);

    const panel = await mountPanel({
      topic: undefined,
      tenant: "_rocketmq",
      namespace: "default",
      mqSystemKind: "rocketmq",
      supportsPeekMessages: false,
    });

    const count = () => panel.querySelector('[data-testid="subscription-count"]')?.textContent?.replace(/\s+/g, " ").trim();
    // Default: SYSTEM off → 3 type-filtered groups.
    expect(count()).toBe("3 / 3");

    const systemCheckbox = [...panel.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')].find((input) => input.closest("label")?.textContent?.toLowerCase().includes("system"));
    expect(systemCheckbox).toBeTruthy();
    expect(systemCheckbox!.checked).toBe(false);
    systemCheckbox!.click();
    await flushUi();
    expect(count()).toBe("4 / 4");

    const search = panel.querySelector<HTMLInputElement>("input.topic-search");
    expect(search).toBeTruthy();
    search!.focus();
    search!.value = "orders";
    search!.dispatchEvent(new Event("input", { bubbles: true }));
    await flushUi();
    expect(count()).toBe("2 / 4");
  });
});

describe("SubscriptionsPanel RocketMQ pagination", () => {
  it("keeps groups after the first page when enrichment is partial", async () => {
    const rows = Array.from({ length: 1000 }, (_, index) => subscription(`group-${String(index + 1).padStart(4, "0")}`, "NORMAL"));
    rows.push(subscription("z-target-group", "NORMAL"));
    backend.mqListSubscriptions.mockResolvedValue(rows);
    backend.mqEnrichSubscriptions.mockResolvedValue(rows.slice(0, 500).map((row) => ({ ...row, onlineMembers: 2, topics: ["events"] })));

    const panel = await mountPanel({
      topic: undefined,
      tenant: "_rocketmq",
      namespace: "default",
      mqSystemKind: "rocketmq",
      supportsPeekMessages: false,
    });

    await vi.waitFor(() => expect(panel.querySelectorAll("tbody tr")).toHaveLength(1001));
    expect(panel.querySelector('[data-testid="subscription-count"]')?.textContent?.replace(/\s+/g, " ").trim()).toBe("1001 / 1001");

    const search = panel.querySelector<HTMLInputElement>("input.topic-search");
    expect(search).toBeTruthy();
    search!.value = "z-target-group";
    search!.dispatchEvent(new Event("input", { bubbles: true }));
    await vi.waitFor(() => expect(panel.querySelectorAll("tbody tr")).toHaveLength(1));
    expect(panel.textContent).toContain("z-target-group");
  });
});