feat(xugu): add active transaction management

This commit is contained in:
Elias authored and GitHub committed 2026-10-01 02:05:50 +08:00
1 parent 4706ffe070
commit 0f7e2b6c6c
10 files changed
+566 -39

No files matched your search

@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { connectionSupportsProcessList, resolveProcessListDriver, resolveProcessListDriverForConnection } from "@/lib/database/processListDrivers";
import { assessProductionSql } from "@/lib/database/productionSafety";
import { buildXuguKillTransactionSql, mapXuguTransactionRows, XUGU_OWN_SESSION_SQL, XUGU_TRANSACTION_LIST_SQL, xuguTransactionKey } from "@/lib/database/xuguProcessList";
describe("Xugu active transaction management", () => {
it("uses the system-wide active-transaction join, not all idle sessions", () => {
expect(XUGU_TRANSACTION_LIST_SQL).toContain("FROM SYS_ALL_TRANS T");
expect(XUGU_TRANSACTION_LIST_SQL).toContain("JOIN SYS_ALL_SESSIONS S");
expect(XUGU_TRANSACTION_LIST_SQL).toContain("T.NODEID = S.NODEID AND T.TRANID = S.CURR_TID");
expect(XUGU_TRANSACTION_LIST_SQL).toContain("CAST(T.TRANID AS VARCHAR(32))");
expect(XUGU_OWN_SESSION_SQL).toContain("USERENV('SID')");
});
it("maps shuffled columns while preserving a BIGINT transaction id exactly", () => {
const rows = mapXuguTransactionRows({
columns: ["TRANSACTION_ID", "USER_NAME", "SESSION_ID", "NODE_ID", "CLIENT_IP", "START_TIME", "DB_NAME"],
rows: [["9007199254740993", "APP_TEST", 7, 2, "10.0.0.1", "2026-09-30 10:00:00", "SHOP_DEMO"]],
});
expect(rows).toEqual([{ id: 7, nodeId: 2, transactionId: "9007199254740993", user: "APP_TEST", db: "SHOP_DEMO", host: "10.0.0.1", startTime: "2026-09-30 10:00:00" }]);
expect(xuguTransactionKey(rows[0]!)).toBe("2:9007199254740993:7");
expect(buildXuguKillTransactionSql(rows[0]!)).toBe("CALL DBMS_DBA.KILL_TRANS(2, 9007199254740993)");
});
it("distinguishes equal session and transaction numbers on different nodes", () => {
const rows = mapXuguTransactionRows({
columns: ["NODE_ID", "TRANSACTION_ID", "SESSION_ID", "USER_NAME"],
rows: [
[1, "123", 5, "A"],
[2, "123", 5, "B"],
],
});
expect(rows).toHaveLength(2);
expect(rows.map(xuguTransactionKey)).toEqual(["1:123:5", "2:123:5"]);
});
it("drops unusable identities and rejects unsafe SQL inputs", () => {
expect(
mapXuguTransactionRows({
columns: ["NODE_ID", "TRANSACTION_ID", "SESSION_ID"],
rows: [
[1, "0", 2],
[0, "12", 2],
[1, "1; DROP TABLE X", 2],
[1, "9223372036854775808", 2],
[1, "12", "not-an-id"],
],
}),
).toEqual([]);
expect(() => buildXuguKillTransactionSql({ nodeId: 1, transactionId: "1); DROP TABLE X" })).toThrow("Invalid Xugu transaction target");
expect(() => buildXuguKillTransactionSql({ nodeId: Number.MAX_SAFE_INTEGER + 1, transactionId: "2" })).toThrow("Invalid Xugu transaction target");
});
it("registers Xugu without changing the other process-list drivers", () => {
const xugu = resolveProcessListDriver("xugu");
expect(xugu?.mode).toBe("transaction");
expect(xugu?.database).toBe("SYSTEM");
expect(xugu?.buildCancelQuerySql).toBeUndefined();
expect(xugu?.buildKillTransactionSql?.({ id: 7, nodeId: 2, transactionId: "9007199254740993" })).toBe("CALL DBMS_DBA.KILL_TRANS(2, 9007199254740993)");
expect(xugu?.buildTerminateSessionSql).toBeUndefined();
expect(xugu?.supportsBatchCancel).toBeUndefined();
expect(resolveProcessListDriverForConnection({ id: "x", db_type: "xugu", username: "SYSDBA", database: "SHOP_DEMO" } as any)).toBe(xugu);
for (const type of ["mysql", "postgres", "opengauss", "kingbase"] as const) {
expect(resolveProcessListDriver(type)?.mode).toBeUndefined();
expect(resolveProcessListDriver(type)?.database).toBeUndefined();
}
});
it("only exposes Xugu transaction management to SYSDBA connections", () => {
for (const username of ["SYSDBA", " sysdba "]) {
expect(connectionSupportsProcessList({ id: "x", db_type: "xugu", username, database: "SHOP_DEMO" } as any)).toBe(true);
}
for (const username of ["APP_TEST", "DBX_7102_DBA", "", undefined]) {
const connection = { id: "x", db_type: "xugu", username, database: "SYSTEM" } as any;
expect(resolveProcessListDriverForConnection(connection)).toBeNull();
expect(connectionSupportsProcessList(connection)).toBe(false);
}
});
it("classifies termination as a protected write for production connections", () => {
const sql = buildXuguKillTransactionSql({ nodeId: 1, transactionId: "42" });
expect(assessProductionSql(sql, { id: "x", db_type: "xugu", is_production: true } as any, "SYSTEM")).toMatchObject({ active: true, isMutation: true });
});
});
@@ -1,5 +1,6 @@
import type { ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { buildXuguKillTransactionSql, mapXuguTransactionRows, XUGU_OWN_SESSION_SQL, XUGU_TRANSACTION_LIST_SQL, xuguTransactionKey } from "./xuguProcessList";
import { buildCancelQuerySql as buildMysqlCancelQuerySql, buildTerminateSessionSql as buildMysqlTerminateSessionSql, mapProcessRows as mapMysqlProcessRows, PROCESS_LIST_SQL as MYSQL_PROCESS_LIST_SQL, supportsProcessList as supportsMysqlProcessList } from "./mysqlProcessList";
import {
buildKingbaseCancelQuerySql,
@@ -32,12 +33,12 @@ import {
} from "./postgresProcessList";
/**
* Engine-agnostic process-list model. Each supported engine contributes a driver
* describing how to list sessions, identify the caller's own session, render the
* columns, and kill a session. The panel component stays entirely generic.
* Engine-agnostic operations model. Each supported engine contributes a driver
* describing how to list sessions or transactions, identify the caller's own
* session, render columns, and perform its explicitly named action.
*/
/** A displayable session row. `id` is the value passed to the driver's kill SQL. */
/** A displayable row. `id` is the session/process id; transaction drivers use a separate composite target. */
export type ProcessRow = { id: number } & Record<string, string | number | null>;
export interface ProcessColumn {
@@ -54,9 +55,15 @@ export interface ProcessColumn {
}
export interface ProcessListDriver {
/** Xugu displays active transactions rather than a full session list. */
mode?: "transaction";
/** Execution database for a system-wide administrative view. */
database?: string;
/** Stable row key when a server-local session id is not globally unique. */
rowKey?(row: ProcessRow): string;
/** Whether the panel offers multi-selection and batch query cancellation. */
supportsBatchCancel?: boolean;
/** SQL that lists current sessions, one row each. */
/** SQL that lists sessions or, for transaction mode, active transactions. */
listSql: string;
/** Compatibility query used when the primary list SQL references newer columns. */
fallbackListSql?: string;
@@ -77,7 +84,9 @@ export interface ProcessListDriver {
/** Map a raw list result into typed rows. */
mapRows(result: QueryResult | null | undefined): ProcessRow[];
/** Build the validated statement that cancels the selected session's running query. */
buildCancelQuerySql(id: number): string;
buildCancelQuerySql?(id: number): string;
/** Xugu-only action: end the selected transaction without disconnecting its session. */
buildKillTransactionSql?(row: ProcessRow): string;
/** Build the compatibility statement used when the primary cancellation function is unavailable. */
buildFallbackCancelQuerySql?(id: number): string;
/** Restrict cancellation fallback attempts to known compatibility failures. */
@@ -188,16 +197,40 @@ const KINGBASE_DRIVER: ProcessListDriver = {
fallbackTerminateSessionResultError: kingbasePgTerminateSessionResultError,
};
const XUGU_COLUMNS: ProcessColumn[] = [
{ key: "nodeId", labelKey: "processList.transactionNode", mono: true, numeric: true },
{ key: "transactionId", labelKey: "processList.transactionId", mono: true },
{ key: "id", labelKey: "processList.transactionSession", mono: true, numeric: true },
{ key: "user", labelKey: "processList.colUser" },
{ key: "db", labelKey: "processList.colDb" },
{ key: "host", labelKey: "processList.colClient" },
{ key: "startTime", labelKey: "processList.transactionStart" },
];
const XUGU_DRIVER: ProcessListDriver = {
mode: "transaction",
database: "SYSTEM",
listSql: XUGU_TRANSACTION_LIST_SQL,
ownSessionSql: XUGU_OWN_SESSION_SQL,
columns: XUGU_COLUMNS,
defaultSortKey: "startTime",
maxRows: 5000,
mapRows: (result) => mapXuguTransactionRows(result) as unknown as ProcessRow[],
rowKey: (row) => xuguTransactionKey(row as unknown as ReturnType<typeof mapXuguTransactionRows>[number]),
buildKillTransactionSql: (row) => buildXuguKillTransactionSql(row as unknown as ReturnType<typeof mapXuguTransactionRows>[number]),
};
/** Resolve the process-list driver for a connection, or null if unsupported. */
export function resolveProcessListDriver(dbType: DatabaseType | undefined): ProcessListDriver | null {
if (supportsMysqlProcessList(dbType)) return MYSQL_DRIVER;
if (dbType === "postgres") return POSTGRES_DRIVER;
if (dbType === "opengauss") return OPENGAUSS_DRIVER;
if (dbType === "kingbase") return KINGBASE_DRIVER;
if (dbType === "xugu") return XUGU_DRIVER;
return null;
}
/** Whether any process-list viewer (MySQL or Postgres family) covers this engine. */
/** Whether the shared operations panel covers this engine. */
export function supportsProcessList(dbType: DatabaseType | undefined): boolean {
return resolveProcessListDriver(dbType) !== null;
}
@@ -221,6 +254,9 @@ export function resolveProcessListDriverForConnection(connection: ConnectionConf
}
const dbType = effectiveDatabaseTypeForConnection(connection);
if (dbType === "gaussdb" && connection.driver_profile?.toLowerCase() === "opengauss") return OPENGAUSS_DRIVER;
// Xugu's SYS_* transaction views and DBMS_DBA.KILL_TRANS are queried through
// SYSTEM. A DBA grant in a business database does not make that login SYSDBA.
if (dbType === "xugu" && connection.username?.trim().toUpperCase() !== "SYSDBA") return null;
return resolveProcessListDriver(dbType);
}
@@ -0,0 +1,86 @@
import type { QueryResult } from "@/types/database";
/**
* Xugu's DBA operation kills a transaction, not its owning session. Keep the
* BIGINT transaction id as text so JSON/JavaScript never rounds the target.
* The join deliberately matches the transaction to its current session on
* both node and transaction id; idle sessions are not part of this view.
*/
export const XUGU_TRANSACTION_LIST_SQL = `SELECT T.NODEID AS NODE_ID,
CAST(T.TRANID AS VARCHAR(32)) AS TRANSACTION_ID,
S.SESSION_ID AS SESSION_ID,
S.USER_NAME AS USER_NAME,
S.DB_NAME AS DB_NAME,
S.IP AS CLIENT_IP,
T.START_T AS START_TIME
FROM SYS_ALL_TRANS T
JOIN SYS_ALL_SESSIONS S
ON T.NODEID = S.NODEID AND T.TRANID = S.CURR_TID
ORDER BY T.START_T`;
/** The SYSTEM control connection is serialized by the Xugu agent. */
export const XUGU_OWN_SESSION_SQL = "SELECT NODEID, SESSION_ID FROM SYS_SESSIONS WHERE SESSION_ID = USERENV('SID')";
export interface XuguTransactionRow {
/** Session id for display only; it is not the transaction kill target. */
id: number;
nodeId: number;
transactionId: string;
user: string;
db: string | null;
host: string | null;
startTime: string | null;
}
const MAX_SIGNED_BIGINT = 9223372036854775807n;
function columnIndex(columns: string[], name: string): number {
return columns.findIndex((column) => column.toUpperCase() === name);
}
function textAt(result: QueryResult, row: unknown[], name: string): string | null {
const index = columnIndex(result.columns, name);
const value = index < 0 ? null : row[index];
return value === null || value === undefined ? null : String(value);
}
function safeInteger(value: string | null): number | null {
if (value === null || !/^(0|[1-9]\d*)$/.test(value)) return null;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
export function mapXuguTransactionRows(result: QueryResult | null | undefined): XuguTransactionRow[] {
if (!result?.rows) return [];
const mapped: XuguTransactionRow[] = [];
for (const raw of result.rows) {
const nodeId = safeInteger(textAt(result, raw, "NODE_ID"));
const sessionId = safeInteger(textAt(result, raw, "SESSION_ID"));
const transactionId = textAt(result, raw, "TRANSACTION_ID");
if (nodeId === null || nodeId <= 0 || sessionId === null || transactionId === null || !/^[1-9]\d*$/.test(transactionId)) continue;
const transaction = BigInt(transactionId);
if (transaction > MAX_SIGNED_BIGINT) continue;
mapped.push({
id: sessionId,
nodeId,
transactionId,
user: textAt(result, raw, "USER_NAME") ?? "",
db: textAt(result, raw, "DB_NAME"),
host: textAt(result, raw, "CLIENT_IP"),
startTime: textAt(result, raw, "START_TIME"),
});
}
return mapped;
}
export function xuguTransactionKey(row: XuguTransactionRow): string {
return `${row.nodeId}:${row.transactionId}:${row.id}`;
}
export function buildXuguKillTransactionSql(row: Pick<XuguTransactionRow, "nodeId" | "transactionId">): string {
const { nodeId, transactionId } = row;
if (!Number.isSafeInteger(nodeId) || nodeId <= 0 || !/^[1-9]\d*$/.test(transactionId)) throw new Error("Invalid Xugu transaction target");
const transaction = BigInt(transactionId);
if (transaction > MAX_SIGNED_BIGINT) throw new Error("Invalid Xugu transaction target");
return `CALL DBMS_DBA.KILL_TRANS(${nodeId}, ${transactionId})`;
}