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。

13.3 KB
Raw Blame
import { computed, ref } from "vue";
import * as api from "@/lib/backend/api";
import { currentLocale } from "@/i18n";
import { buildMarketplacePluginListings, pluginSourceChange, type MarketplacePluginListing } from "@/lib/plugins/pluginMarketplace";
import { mcpUpdateAvailability } from "@/lib/mcp/mcpUpdateStatus";
import { useSettingsStore } from "@/stores/settingsStore";
import { isUpdatePreviewMockEnabled, previewDriverUpdates, previewJdbcUpdate, previewMcpUpdate, previewPluginUpdates } from "@/lib/updates/updatePreviewMock";
import type { ComponentUpdateCategory } from "@/lib/updates/componentUpdateOrchestration";
import type { AgentDriverInfo, AgentUpdateBlocker, McpServerStatus } from "@/lib/backend/tauri";
import type { JdbcPluginStatus } from "@/types/database";
import { uuid } from "@/lib/common/utils";
import { isDriverInstallProgressForOperation, updatePerDriverProgress, type DriverInstallProgress } from "@/lib/connection/driverInstallProgressUi";

export type { ComponentUpdateCategory } from "@/lib/updates/componentUpdateOrchestration";

export type PluginUpdateBlock = { pluginName: string; reason: "connections"; connections: string } | { pluginName: string; reason: "operations" | "inProgress" };

export interface ComponentUpdateResult {
  drivers: number;
  jdbc: boolean;
  mcp: boolean;
  plugins: number;
  skippedDrivers: number;
  blockedDrivers: AgentUpdateBlocker[];
  failed: string[];
  blockedPlugins: PluginUpdateBlock[];
}

interface ComponentUpdateRefreshOptions {
  force?: boolean;
}

function emptyResult(): ComponentUpdateResult {
  return { drivers: 0, jdbc: false, mcp: false, plugins: 0, skippedDrivers: 0, blockedDrivers: [], failed: [], blockedPlugins: [] };
}

function pluginUpdateBlock(pluginName: string, message: string): PluginUpdateBlock | null {
  const connectionsPrefix = "Plugin update blocked by active connections: ";
  if (message.startsWith(connectionsPrefix)) {
    return { pluginName, reason: "connections", connections: message.slice(connectionsPrefix.length) };
  }
  if (message === "Plugin update blocked by active operations. Please wait for them to finish.") {
    return { pluginName, reason: "operations" };
  }
  if (message === "Plugin update is in progress. Please try again after it finishes.") {
    return { pluginName, reason: "inProgress" };
  }
  return null;
}

export function useComponentUpdates(options: { isDesktop: boolean }) {
  const settingsStore = useSettingsStore();
  const drivers = ref<AgentDriverInfo[]>([]);
  const jdbcPluginStatus = ref<JdbcPluginStatus | null>(null);
  const mcpStatus = ref<McpServerStatus | null>(null);
  const pluginListings = ref<MarketplacePluginListing[]>([]);
  const loading = ref(false);
  const updating = ref(false);
  const updatingCategory = ref<ComponentUpdateCategory | null>(null);
  const lastError = ref("");
  const driverBatchCompleted = ref(0);
  const driverBatchTotal = ref(0);
  const driverProgressMap = ref<Record<string, DriverInstallProgress>>({});

  const driverUpdates = computed(() => drivers.value.filter((driver) => driver.update_available));
  const pluginUpdates = computed(() => pluginListings.value.filter((listing) => listing.status === "update"));
  const driverUpdateCount = computed(() => driverUpdates.value.length);
  const jdbcUpdateAvailable = computed(() => jdbcPluginStatus.value?.update_available === true);
  const mcpUpdateAvailable = computed(() => (mcpStatus.value ? mcpUpdateAvailability(mcpStatus.value) === true : false));
  const pluginUpdateCount = computed(() => pluginUpdates.value.length);
  const totalUpdateCount = computed(() => driverUpdateCount.value + (jdbcUpdateAvailable.value ? 1 : 0) + (mcpUpdateAvailable.value ? 1 : 0) + pluginUpdateCount.value);

  let refreshPromise: Promise<boolean> | null = null;
  let refreshVersion = 0;
  let activeUpdatePromise: Promise<ComponentUpdateResult> | null = null;

  function startRefresh(): Promise<boolean> {
    if (!options.isDesktop) return Promise.resolve(false);
    const version = ++refreshVersion;
    refreshPromise = Promise.resolve().then(async () => {
      loading.value = true;
      lastError.value = "";
      try {
        if (isUpdatePreviewMockEnabled()) {
          if (version !== refreshVersion) return false;
          drivers.value = previewDriverUpdates();
          jdbcPluginStatus.value = previewJdbcUpdate();
          mcpStatus.value = previewMcpUpdate();
          pluginListings.value = previewPluginUpdates();
          return true;
        }
        const [agentResult, jdbcResult, mcpResult, installedPluginsResult, catalogsResult] = await Promise.allSettled([api.listInstalledAgents(), api.jdbcPluginStatus(), api.checkMcpServerStatus(), api.listPlugins(), api.fetchPluginMarketplaceCatalogs()]);
        if (version !== refreshVersion) return false;
        const errors: string[] = [];
        if (agentResult.status === "fulfilled") drivers.value = agentResult.value;
        else {
          drivers.value = [];
          errors.push(`drivers: ${agentResult.reason instanceof Error ? agentResult.reason.message : String(agentResult.reason)}`);
        }
        if (jdbcResult.status === "fulfilled") jdbcPluginStatus.value = jdbcResult.value;
        else {
          jdbcPluginStatus.value = null;
          errors.push(`JDBC: ${jdbcResult.reason instanceof Error ? jdbcResult.reason.message : String(jdbcResult.reason)}`);
        }
        if (mcpResult.status === "fulfilled") mcpStatus.value = mcpResult.value;
        else {
          mcpStatus.value = null;
          errors.push(`MCP: ${mcpResult.reason instanceof Error ? mcpResult.reason.message : String(mcpResult.reason)}`);
        }
        if (installedPluginsResult.status === "fulfilled" && catalogsResult.status === "fulfilled") {
          pluginListings.value = buildMarketplacePluginListings(catalogsResult.value, installedPluginsResult.value, currentLocale());
        } else {
          pluginListings.value = [];
          if (installedPluginsResult.status === "rejected") errors.push(`plugins: ${installedPluginsResult.reason instanceof Error ? installedPluginsResult.reason.message : String(installedPluginsResult.reason)}`);
          if (catalogsResult.status === "rejected") errors.push(`plugin catalog: ${catalogsResult.reason instanceof Error ? catalogsResult.reason.message : String(catalogsResult.reason)}`);
        }
        lastError.value = errors.join("; ");
        return errors.length === 0;
      } catch (error) {
        if (version !== refreshVersion) return false;
        lastError.value = error instanceof Error ? error.message : String(error);
        return false;
      } finally {
        if (version === refreshVersion) {
          loading.value = false;
          refreshPromise = null;
        }
      }
    });
    return refreshPromise;
  }

  function refresh(refreshOptions: ComponentUpdateRefreshOptions = {}) {
    if (!refreshOptions.force && refreshPromise) return refreshPromise;
    return startRefresh();
  }

  async function updateDrivers(result: ComponentUpdateResult) {
    const updatable = driverUpdates.value.map((driver) => driver.db_type);
    if (!updatable.length) return;
    if (isUpdatePreviewMockEnabled()) {
      result.drivers += updatable.length;
      return;
    }
    const blockers = await api.checkAgentUpdateBlockers(updatable);
    if (blockers.length) {
      result.skippedDrivers = blockers.length;
      result.blockedDrivers = blockers;
      return;
    }
    const operationId = uuid();
    driverBatchCompleted.value = 0;
    driverBatchTotal.value = updatable.length;
    driverProgressMap.value = {};

    let unlisten: (() => void) | null = null;
    try {
      if (typeof api.listenAgentInstallProgress === "function") {
        unlisten = await api.listenAgentInstallProgress((payload) => {
          const incoming = payload as DriverInstallProgress;
          if (!isDriverInstallProgressForOperation(incoming, operationId)) return;
          if (incoming.total_drivers) {
            driverBatchTotal.value = incoming.total_drivers;
          }
          if (incoming.step === "done" && incoming.db_type) {
            driverBatchCompleted.value++;
          }
          updatePerDriverProgress(driverProgressMap.value, incoming);
          driverProgressMap.value = { ...driverProgressMap.value };
        });
      }
      const upgraded = await api.upgradeAllAgents(operationId);
      result.drivers += upgraded.upgraded;
      if (upgraded.failed.length) result.failed.push(...upgraded.failed.map((item) => `${item.db_type}: ${item.error}`));
    } finally {
      unlisten?.();
      driverProgressMap.value = {};
      driverBatchCompleted.value = 0;
      driverBatchTotal.value = 0;
    }
  }

  async function updateJdbc(result: ComponentUpdateResult) {
    if (!jdbcUpdateAvailable.value) return;
    if (isUpdatePreviewMockEnabled()) {
      result.jdbc = true;
      return;
    }
    await api.installJdbcPlugin();
    result.jdbc = true;
  }

  async function updateMcp(result: ComponentUpdateResult) {
    if (!mcpUpdateAvailable.value) return;
    if (isUpdatePreviewMockEnabled()) {
      result.mcp = true;
      return;
    }
    await api.installMcpServer();
    result.mcp = true;
  }

  async function updatePlugins(result: ComponentUpdateResult) {
    // Listings whose recorded provenance differs from the offering repository/publisher/key need an
    // explicit confirmation, which the automatic path cannot give: keep them visible in the update
    // center (they still count) but let the user confirm them in the Plugin Center instead.
    const updatable = pluginUpdates.value.filter((item) => item.artifact && !pluginSourceChange(item));
    if (isUpdatePreviewMockEnabled()) {
      result.plugins += updatable.length;
      return;
    }
    for (const listing of updatable) {
      try {
        await api.installMarketplacePlugin({
          repositoryId: listing.repository.id,
          pluginId: listing.plugin.id,
          version: listing.plugin.latestVersion,
        });
        result.plugins += 1;
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        const block = pluginUpdateBlock(listing.name, message);
        if (block) result.blockedPlugins.push(block);
        result.failed.push(`${listing.name}: ${message}`);
      }
    }
  }

  function categoryLabel(category: ComponentUpdateCategory): string {
    return category === "jdbc" ? "JDBC" : category === "mcp" ? "MCP" : category;
  }

  async function runCategory(category: ComponentUpdateCategory, result: ComponentUpdateResult) {
    updatingCategory.value = category;
    try {
      if (category === "drivers") await updateDrivers(result);
      else if (category === "jdbc") await updateJdbc(result);
      else if (category === "mcp") await updateMcp(result);
      else await updatePlugins(result);
    } catch (error) {
      result.failed.push(`${categoryLabel(category)}: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  async function runUpdateOperation(categories: ComponentUpdateCategory[]): Promise<ComponentUpdateResult> {
    const result = emptyResult();
    if (!options.isDesktop) return result;
    if (activeUpdatePromise) return activeUpdatePromise;
    updating.value = true;
    // 作废更新窗口开始前发出的刷新:旧的 refreshPromise 带的是升级前快照,
    // 必须一并清掉,否则更新流程会复用它而拿不到安装后的权威状态。
    refreshVersion += 1;
    refreshPromise = null;
    const operation = (async () => {
      await refresh();
      const initialCheckError = lastError.value;
      if (initialCheckError) result.failed.push(initialCheckError);
      for (const category of categories) await runCategory(category, result);
      await refresh();
      if (lastError.value && lastError.value !== initialCheckError) result.failed.push(lastError.value);
      return result;
    })();
    activeUpdatePromise = operation;
    try {
      return await operation;
    } finally {
      if (activeUpdatePromise === operation) activeUpdatePromise = null;
      // 安装结束后同样作废在途刷新,确保权威状态不会被旧快照覆盖。
      refreshVersion += 1;
      refreshPromise = null;
      updating.value = false;
      updatingCategory.value = null;
    }
  }

  function installCategory(category: ComponentUpdateCategory): Promise<ComponentUpdateResult> {
    return runUpdateOperation([category]);
  }

  function installCategories(categories: ComponentUpdateCategory[]): Promise<ComponentUpdateResult> {
    return runUpdateOperation([...new Set(categories)]);
  }

  function autoUpdateEnabledComponents(): Promise<ComponentUpdateResult> {
    const categories: ComponentUpdateCategory[] = [];
    if (settingsStore.editorSettings.autoUpdateDrivers) categories.push("drivers");
    if (settingsStore.editorSettings.autoUpdateJdbc) categories.push("jdbc");
    if (settingsStore.editorSettings.autoUpdateMcp) categories.push("mcp");
    if (settingsStore.editorSettings.autoUpdatePlugins) categories.push("plugins");
    return runUpdateOperation(categories);
  }

  return {
    drivers,
    driverUpdates,
    jdbcPluginStatus,
    mcpStatus,
    pluginListings,
    pluginUpdates,
    loading,
    updating,
    updatingCategory,
    lastError,
    driverUpdateCount,
    driverBatchCompleted,
    driverBatchTotal,
    driverProgressMap,
    jdbcUpdateAvailable,
    mcpUpdateAvailable,
    pluginUpdateCount,
    totalUpdateCount,
    refresh,
    installCategory,
    installCategories,
    autoUpdateEnabledComponents,
  };
}