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。

feat(consul): add Consul full-stack workbench

二丫讲梵37f13018d3b3
diff --git a/.github/scripts/database-issue-catalog.mjs b/.github/scripts/database-issue-catalog.mjs
index 350d17d7ce..9f6ee6022e 100644
--- a/.github/scripts/database-issue-catalog.mjs
+++ b/.github/scripts/database-issue-catalog.mjs
@@ -69,6 +69,7 @@ const extraAliases = {
const supplementalDrivers = [
{ dbType: "turso", label: "Turso", aliases: ["libsql", "lib sql"] },
{ dbType: "nacos", label: "Nacos", aliases: ["r-nacos", "rnacos"] },
+ { dbType: "consul", label: "Consul", aliases: ["hashicorp consul"] },
{ dbType: "cloudberry", label: "Apache Cloudberry" },
{ dbType: "mariadb", label: "MariaDB" },
{ dbType: "tidb", label: "TiDB" },
diff --git a/.github/scripts/i18n-autofill.mjs b/.github/scripts/i18n-autofill.mjs
index ca6116f4f5..50c4d202a1 100644
--- a/.github/scripts/i18n-autofill.mjs
+++ b/.github/scripts/i18n-autofill.mjs
@@ -2,7 +2,7 @@
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
+import { dirname, join, resolve } from "node:path";
const LOCALES_DIR = "apps/desktop/src/i18n/locales";
const SOURCE_LOCALE = "zh-CN";
@@ -351,27 +351,98 @@ function applyEdits(text, edits) {
function flattenLeaves(root) {
const result = new Map();
- flattenNode(root, [], result);
+ flattenNode(root, [], result, root.externalObjects || new Map(), new Set());
return result;
}
-function flattenNode(node, path, result) {
+function flattenNode(node, path, result, externalObjects, activeExternalObjects) {
for (const property of node.properties) {
const nextPath = [...path, property.key];
if (property.value.type === "object") {
- flattenNode(property.value, nextPath, result);
+ flattenNode(property.value, nextPath, result, externalObjects, activeExternalObjects);
} else if (property.value.type === "string") {
result.set(nextPath.join("."), property.value.value);
+ } else if (property.value.type === "spread") {
+ const [binding, ...members] = property.value.expression.split(".");
+ let spreadObject = externalObjects.get(binding);
+ for (const member of members) {
+ spreadObject = spreadObject?.properties.find((candidate) => candidate.key === member && candidate.value.type === "object")?.value;
+ }
+ flattenExternalObject(property.value.expression, spreadObject, path, result, externalObjects, activeExternalObjects);
+ } else if (property.value.type === "external") {
+ flattenExternalObject(property.key, externalObjects.get(property.key), nextPath, result, externalObjects, activeExternalObjects);
}
}
}
+function flattenExternalObject(name, object, path, result, externalObjects, activeExternalObjects) {
+ if (!object || activeExternalObjects.has(name)) return;
+ activeExternalObjects.add(name);
+ flattenNode(object, path, result, externalObjects, activeExternalObjects);
+ activeExternalObjects.delete(name);
+}
+
function parseLocaleFile(text, file) {
const parser = new Parser(text, file);
const root = parser.parseLocaleRoot();
+ root.externalObjects = parseImportedObjects(text, file);
+ for (const [name, object] of parseDeclaredObjects(text, file)) {
+ root.externalObjects.set(name, object);
+ }
return { root };
}
+function parseDeclaredObjects(text, file) {
+ const result = new Map();
+ const declarations = /^\s*const\s+([A-Za-z_$][\w$]*)\s*=/gm;
+ const exportIndex = text.indexOf("export default");
+
+ for (const match of text.slice(0, exportIndex).matchAll(declarations)) {
+ const parser = new Parser(text, file);
+ parser.index = match.index + match[0].length;
+ parser.skipSpace();
+ if (parser.peek() === "{") result.set(match[1], parser.parseObject());
+ }
+
+ return result;
+}
+
+function parseImportedObjects(text, file, visited = new Set()) {
+ const result = new Map();
+ const actualFile = existsSync(file) ? file : file.slice(file.indexOf(":") + 1);
+ const resolvedFile = resolve(actualFile);
+ if (visited.has(resolvedFile)) return result;
+ visited.add(resolvedFile);
+ const importPattern = /import\s*\{([^}]+)\}\s*from\s*["'](\.\.?\/[^"']+)["'];?/g;
+
+ for (const match of text.matchAll(importPattern)) {
+ const modulePath = resolve(dirname(actualFile), `${match[2]}.ts`);
+ if (!existsSync(modulePath)) continue;
+ const moduleText = readFileSync(modulePath, "utf8");
+ for (const [name, object] of parseImportedObjects(moduleText, modulePath, visited)) {
+ if (!result.has(name)) result.set(name, object);
+ }
+ for (const specifier of match[1].split(",")) {
+ const [exportedName, localName = exportedName] = specifier.trim().split(/\s+as\s+/);
+ if (!exportedName) continue;
+ const object = parseExportedObject(moduleText, modulePath, exportedName);
+ if (object) result.set(localName, object);
+ }
+ }
+
+ return result;
+}
+
+function parseExportedObject(text, file, name) {
+ const match = new RegExp(`export\\s+const\\s+${name.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&")}\\s*=`).exec(text);
+ if (!match) return null;
+ const parser = new Parser(text, file);
+ parser.index = match.index + match[0].length;
+ parser.skipSpace();
+ if (parser.peek() !== "{") return null;
+ return parser.parseObject();
+}
+
class Parser {
constructor(text, file) {
this.text = text;
@@ -412,6 +483,26 @@ class Parser {
}
const start = this.index;
+ if (this.text.startsWith("...", this.index)) {
+ this.index += 3;
+ this.skipSpace();
+ const root = this.parseIdentifier();
+ if (!root) this.fail("Expected spread identifier");
+ let expression = root;
+ while (this.peek() === ".") {
+ this.index += 1;
+ const member = this.parseIdentifier();
+ if (!member) this.fail("Expected spread member");
+ expression += `.${member}`;
+ }
+ this.skipSpace();
+ const hasComma = this.peek() === ",";
+ if (hasComma) this.index += 1;
+ else if (this.peek() !== "}") this.fail("Expected comma after spread property");
+ properties.push({ key: `...${expression}`, start, end: this.index, hasComma, value: { type: "spread", expression } });
+ continue;
+ }
+
const key = this.parseKey();
this.skipSpace();
if (this.peek() === "," || this.peek() === "}") {
diff --git a/.github/scripts/label-issue-database.test.mjs b/.github/scripts/label-issue-database.test.mjs
index 782eccf7c1..4ff5a204b9 100644
--- a/.github/scripts/label-issue-database.test.mjs
+++ b/.github/scripts/label-issue-database.test.mjs
@@ -46,6 +46,7 @@ test("labels native and compatibility database products with their families", ()
["Turso", ["db/turso"]],
["Nacos 2.0.1", ["db/nacos"]],
["r-nacos", ["db/nacos"]],
+ ["HashiCorp Consul", ["db/consul"]],
["Apache Cloudberry", ["db/cloudberry", "db/postgres"]],
["TiDB v8.5", ["db/mysql", "db/tidb"]],
["OceanBase", ["db/oceanbase"]],
diff --git a/README.md b/README.md
index 394161b18d..239d646219 100644
--- a/README.md
+++ b/README.md
@@ -90,7 +90,7 @@
### 70+ Databases, One Tool
-MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Easysearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, UXDB, Dolt, and more. Agent-based profiles extend DBX to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, and custom JDBC connections. New native and agent-driven drivers also cover Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and more. Message queue admin is also available for Pulsar, Kafka, and RocketMQ. All in a single ~20 MB app. No bundled Chromium.
+MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Easysearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, UXDB, Dolt, and more. Agent-based profiles extend DBX to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, and custom JDBC connections. New native and agent-driven drivers also cover Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, Consul KV, IRIS, and more. Message queue admin is also available for Pulsar, Kafka, and RocketMQ. All in a single ~20 MB app. No bundled Chromium.
### Query Editor
@@ -483,7 +483,7 @@ DBX is 20 MB with no runtime dependencies for its native database features (no s
<details>
<summary><strong>What databases are supported?</strong></summary>
-MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Easysearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, UXDB, and more. Agent-based profiles extend support to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, IRIS, and custom JDBC connections. Message queue admin (Pulsar, Kafka, RocketMQ) is also supported.
+MySQL, PostgreSQL, SQLite, Cloudflare D1, Redis, MongoDB, DuckDB, ClickHouse, SQL Server, Oracle, Elasticsearch, Easysearch, Qdrant, Milvus, Weaviate, MariaDB, TiDB, OceanBase, openGauss, GaussDB, KWDB, KingBase, Vastbase, GoldenDB, Doris, SelectDB, StarRocks, Manticore Search, Redshift, DM, TDengine, XuguDB, CockroachDB, Access, HighGo, UXDB, and more. Agent-based profiles extend support to H2, Snowflake, Trino, PrestoSQL, Hive, DB2, Informix, Neo4j, Cassandra, BigQuery, Kylin, SunDB, JDBCX, Databricks, SAP HANA, Teradata, Vertica, Firebird, Exasol, YashanDB, GBase 8a/8s, Databend, RQLite, Turso, InfluxDB, QuestDB, IoTDB, etcd, ZooKeeper, Nacos, Consul KV, IRIS, and custom JDBC connections. Message queue admin (Pulsar, Kafka, RocketMQ) is also supported.
</details>
<details>
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3cd61555d1..0e73070d74 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -90,7 +90,7 @@
### 70+ 种数据库,一个工具搞定
-MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Easysearch、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo、UXDB、Dolt 等数据库都能直接连接。Agent 配置还可扩展到 H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX 和自定义 JDBC。新增的原生与 Agent 驱动还覆盖了 Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、IRIS 等。全部装进约 20 MB 的应用里,不内嵌 Chromium。
+MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Easysearch、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo、UXDB、Dolt 等数据库都能直接连接。Agent 配置还可扩展到 H2、Snowflake、Trino、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX 和自定义 JDBC。新增的原生与 Agent 驱动还覆盖了 Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、ZooKeeper、Nacos、Consul KV、IRIS 等。全部装进约 20 MB 的应用里,不内嵌 Chromium。
### 查询编辑器
@@ -486,7 +486,7 @@ DBX 仅 20 MB,无需运行时依赖(无需 Java、无需 Python)。AI 和
<details>
<summary><strong>支持哪些数据库?</strong></summary>
-MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Easysearch、Qdrant、Milvus、Weaviate、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo、UXDB 等。Agent 配置可扩展到 H2、Snowflake、Trino、PrestoSQL、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX、Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase 8a/8s、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、ZooKeeper、Nacos、IRIS 及自定义 JDBC 连接,并支持消息队列管理(Pulsar、Kafka、RocketMQ)。
+MySQL、PostgreSQL、SQLite、Cloudflare D1、Redis、MongoDB、DuckDB、ClickHouse、SQL Server、Oracle、Elasticsearch、Easysearch、Qdrant、Milvus、Weaviate、MariaDB、TiDB、OceanBase、openGauss、GaussDB、KWDB、KingBase、Vastbase、GoldenDB、Doris、SelectDB、StarRocks、Manticore Search、Redshift、DM、TDengine、虚谷 XuguDB、CockroachDB、Access、HighGo、UXDB 等。Agent 配置可扩展到 H2、Snowflake、Trino、PrestoSQL、Hive、DB2、Informix、Neo4j、Cassandra、BigQuery、Kylin、SunDB、JDBCX、Databricks、SAP HANA、Teradata、Vertica、Firebird、Exasol、崖山 YashanDB、GBase 8a/8s、Databend、RQLite、Turso、InfluxDB、QuestDB、IoTDB、etcd、ZooKeeper、Nacos、Consul KV、IRIS 及自定义 JDBC 连接,并支持消息队列管理(Pulsar、Kafka、RocketMQ)。
</details>
<details>
diff --git a/apps/desktop/public/icons/database/consul.svg b/apps/desktop/public/icons/database/consul.svg
new file mode 100644
index 0000000000..5220a1e9dd
--- /dev/null
+++ b/apps/desktop/public/icons/database/consul.svg
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="32px" height="32px" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <title>favicon</title>
+ <g id="favicon" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <path d="M19.5795647,2.46534761 C17.3769619,1.88281475 15.0654136,1.84664567 12.8456739,2.35998035 C10.6258805,2.8733161 8.56493925,3.92063891 6.8417186,5.41105013 C5.11848183,6.90146135 3.78503178,8.78992153 2.95709359,10.9125342 C2.12916239,13.0350931 1.83176938,15.327678 2.09073006,17.5912538 C2.34969127,19.8548296 3.15718174,22.0210097 4.44311046,23.9017717 C5.72903917,25.7825337 7.45453221,27.3210411 9.46986459,28.3837441 C11.485197,29.4464472 13.7294333,30.0012747 16.0077822,30 C19.5196661,30.0035846 22.9038559,28.6829685 25.4850822,26.3016369 L22.174651,22.8413249 C20.8533901,24.0326353 19.215016,24.8152386 17.4580265,25.0944251 C15.701037,25.3736654 13.9007486,25.1374017 12.2753211,24.4143747 C10.6498399,23.691294 9.2688417,22.5124467 8.2996664,21.0205689 C7.33049109,19.5287449 6.81465948,17.7878716 6.81465948,16.0088029 C6.81465948,14.2297879 7.33049109,12.4889146 8.2996664,10.9970368 C9.2688417,9.50515904 10.6498399,8.32631181 12.2753211,7.6032848 C13.9007486,6.88022555 15.701037,6.64399411 17.4580265,6.923186 C19.215016,7.2023779 20.8533901,7.98502415 22.174651,9.17633458 L25.4850822,5.70276969 C23.8093184,4.15917497 21.7821675,3.04788154 19.5795647,2.46534761 Z M27.0510408,20.7255348 C26.8287445,20.769747 26.6244984,20.8789074 26.4642495,21.0391563 C26.3039469,21.1994589 26.1947865,21.4036513 26.1505743,21.6260013 C26.1063622,21.8482976 26.1290323,22.0787595 26.2157913,22.2881628 C26.3025502,22.4976198 26.4494226,22.6766172 26.6379286,22.8025386 C26.8263808,22.9284599 27.0479788,22.9956645 27.2746264,22.9956645 C27.5786319,22.9956645 27.8701205,22.8749541 28.085057,22.6600175 C28.2999936,22.445081 28.4207577,22.1535387 28.4207577,21.8495869 C28.4207577,21.6228855 28.3534994,21.4013413 28.2275781,21.2128354 C28.1016567,21.0243831 27.9226593,20.877457 27.713256,20.7907517 C27.503799,20.7039928 27.2733908,20.6812689 27.0510408,20.7255348 Z M28.3691321,16.8066091 C28.1468358,16.850875 27.9425897,16.9599818 27.7823408,17.1202843 C27.6220382,17.2805869 27.5128778,17.4847794 27.4686656,17.7071294 C27.4244535,17.9294257 27.4471236,18.1598875 27.5338826,18.3692908 C27.6206415,18.5786941 27.7675139,18.7576915 27.9560199,18.8836666 C28.1444721,19.0095879 28.3660701,19.0767925 28.5927177,19.0767925 C28.8963472,19.0756107 29.1871911,18.9545242 29.401859,18.7398563 C29.616527,18.5251346 29.7376672,18.2342907 29.738849,17.930715 C29.738849,17.7040136 29.6716444,17.4824156 29.5456694,17.2939634 C29.419748,17.1055111 29.2407506,16.958585 29.0313473,16.8718261 C28.8218903,16.7851208 28.5914822,16.762397 28.3691321,16.8066091 Z M17.0809071,13.1984577 C16.5267243,12.9689629 15.9169405,12.9089031 15.328645,13.0259068 C14.7403496,13.1429105 14.199973,13.4317668 13.775848,13.8558918 C13.3516693,14.2800168 13.0628667,14.8204471 12.9458093,15.4086889 C12.8288056,15.9969843 12.8888654,16.6067681 13.1184139,17.1609509 C13.3479625,17.7151337 13.7366856,18.1887892 14.2354286,18.5220188 C14.734118,18.8552483 15.3204795,19.0331176 15.9203249,19.0331176 C16.7246314,19.0331176 17.496007,18.7135868 18.0648019,18.1448457 C18.633543,17.5761046 18.9530738,16.8047289 18.9530738,16.0003687 C18.9530738,15.400577 18.7752045,14.8142155 18.4419213,14.3154724 C18.1086917,13.8167294 17.6350362,13.4280063 17.0809071,13.1984577 Z M25.619384,16.7397806 C25.4099806,16.6530216 25.1795188,16.6303515 24.9572225,16.6745636 C24.7348725,16.7187758 24.5306801,16.8279362 24.3703775,16.9882388 C24.2101286,17.1484877 24.1009681,17.3527338 24.0567023,17.5750301 C24.0124901,17.7973802 24.035214,18.0277883 24.1219729,18.2372453 C24.2086782,18.4466486 24.3556043,18.625646 24.5440565,18.7515674 C24.7325625,18.8774887 24.9541067,18.944747 25.1808081,18.944747 C25.4847599,18.944747 25.7763021,18.8239829 25.9912387,18.6090463 C26.2061215,18.3941098 26.3268857,18.1026212 26.3268857,17.7986157 C26.3268857,17.5719681 26.2596811,17.3503701 26.1337597,17.1619179 C26.0078384,16.9734119 25.8287873,16.8265395 25.619384,16.7397806 Z M25.619384,13.1472082 C25.4099806,13.0604492 25.1795188,13.0377791 24.9572225,13.0819912 C24.7348725,13.1262034 24.5306801,13.2353639 24.3703775,13.3956665 C24.2101286,13.5559153 24.1009681,13.7601615 24.0567023,13.9824578 C24.0124901,14.2048078 24.035214,14.4352159 24.1219729,14.6446729 C24.2086782,14.8540763 24.3556043,15.0330737 24.5440565,15.158995 C24.7325625,15.2849163 24.9541067,15.3521747 25.1808081,15.3521747 C25.4847599,15.3521747 25.7763021,15.2314105 25.9912387,15.016474 C26.2061215,14.8015374 26.3268857,14.5099951 26.3268857,14.2060434 C26.3268857,13.9793957 26.2596811,13.7577978 26.1337597,13.5692918 C26.0078384,13.3808396 25.8287873,13.2339671 25.619384,13.1472082 Z M28.3691321,12.9496234 C28.1468358,12.9938893 27.9425897,13.1030498 27.7823408,13.2632986 C27.6220382,13.4236012 27.5128778,13.6277936 27.4686656,13.8501437 C27.4244535,14.07244 27.4471236,14.3029018 27.5338826,14.5123051 C27.6206415,14.7217622 27.7675139,14.9007058 27.9560199,15.0266809 C28.1444721,15.1526022 28.3660701,15.2198068 28.5927177,15.2198068 C28.8963472,15.2186787 29.1871911,15.0975385 29.401859,14.8828706 C29.616527,14.6681489 29.7376672,14.377305 29.738849,14.0737292 C29.738849,13.8470279 29.6716444,13.6254837 29.5456694,13.4369777 C29.419748,13.2485254 29.2407506,13.1015993 29.0313473,13.0148941 C28.8218903,12.9281351 28.5914822,12.9054113 28.3691321,12.9496234 Z M27.1173322,9.09253028 C26.8950359,9.13674242 26.6907898,9.2459029 26.5304872,9.4062055 C26.3702383,9.56650809 26.2610778,9.7707005 26.2168657,9.99299679 C26.1726535,10.2153468 26.1953237,10.4458086 26.2820826,10.655212 C26.3688416,10.8646153 26.515714,11.0436127 26.7041662,11.169534 C26.8926722,11.2955091 27.1142701,11.3627137 27.3409178,11.3627137 C27.6448695,11.3627137 27.9364118,11.2419495 28.1513484,11.027013 C28.3662849,10.8120764 28.4869954,10.5205879 28.4869954,10.2166361 C28.4869954,9.98993471 28.4197908,9.76833679 28.2938694,9.57988455 C28.1679481,9.39137858 27.9889507,9.24450616 27.7794936,9.15774722 C27.5700903,9.07098828 27.3396285,9.04831814 27.1173322,9.09253028 Z" id="Shape" fill="#E03875" fill-rule="nonzero"></path>
+ </g>
+</svg>
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index c5f2bff85f..16b229c6fe 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -1546,7 +1546,7 @@ async function openConnectionQuery(connectionId: string) {
}
return;
}
- if (initialTarget.kind === "etcd" || initialTarget.kind === "zookeeper") {
+ if (initialTarget.kind === "etcd" || initialTarget.kind === "zookeeper" || initialTarget.kind === "consul") {
try {
await connectionStore.ensureConnected(connectionId);
queryStore.createTab(connectionId, "", `${connection.name}:keys`, initialTarget.kind);
@@ -1968,6 +1968,8 @@ async function handleQuickOpenSelect(item: any) {
await connectionStore.loadEtcdRoot(item.connectionId);
} else if (config?.db_type === "zookeeper") {
await connectionStore.loadZooKeeperRoot(item.connectionId);
+ } else if (config?.db_type === "consul") {
+ await connectionStore.loadConsulRoot(item.connectionId);
} else if (config?.db_type === "mongodb") {
await connectionStore.loadMongoDatabases(item.connectionId);
} else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch") {
@@ -1993,6 +1995,8 @@ async function handleQuickOpenSelect(item: any) {
await connectionStore.loadEtcdRoot(item.connectionId);
} else if (config?.db_type === "zookeeper") {
await connectionStore.loadZooKeeperRoot(item.connectionId);
+ } else if (config?.db_type === "consul") {
+ await connectionStore.loadConsulRoot(item.connectionId);
} else if (config?.db_type === "mongodb") {
await connectionStore.loadMongoDatabases(item.connectionId);
} else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch") {
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 280196e4c6..a0543f45f2 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -53,6 +53,7 @@ import { prestoSqlBuiltinDriverPaths } from "@/lib/database/prestoSqlBuiltinDriv
import { JDBCX_DEFAULT_URL, JDBCX_DRIVER_PROFILE, JDBCX_JDBC_DRIVER_CLASS, ensureJdbcxRuntimeDrivers, isJdbcxRuntimeBundle, isJdbcxRuntimePath, jdbcxHighPrivilegeExtensionsEnabled, setJdbcxHighPrivilegeExtensionsEnabled } from "@/lib/database/jdbcxBuiltinDriver";
import { SQLITE_DATABASE_FILE_EXTENSIONS } from "@/lib/database/databaseFileDetection";
import { connectionAttemptOriginalErrorMessage, connectionAttemptTimeoutMessage, connectionAttemptTimeoutMs } from "@/lib/connection/connectionAttemptTimeout";
+import { consulAgentAddressesMatch } from "@/lib/consul/agentTarget";
import { appendConnectionErrorHints, isJdbcMissingRuntimeDependencyError } from "@/lib/connection/connectionErrorHints";
import { preventDialogDocumentSelectAll } from "@/lib/connection/dialogTextSelection";
import { postgresTlsModeForForm } from "@/lib/connection/postgresTlsMode";
@@ -809,6 +810,22 @@ const nacosTlsSkipVerify = ref(false);
const nacosMetricsMode = ref<NacosMetricsMode>("auto");
const nacosMetricsUrl = ref("");
const nacosPageSize = ref(20);
+type ConsulConsistency = "default" | "stale" | "consistent";
+const consulServerAddr = ref("http://127.0.0.1:8500");
+const consulDatacenter = ref("");
+const consulNamespace = ref("");
+const consulPartition = ref("");
+const consulConsistency = ref<ConsulConsistency>("default");
+const consulTlsSkipVerify = ref(false);
+const consulAgentTargetNode = ref("");
+const consulAgentTargetAddress = ref("");
+const consulMeshVisible = ref(false);
+const consulOperatorVisible = ref(false);
+const consulOperatorSnapshotRestoreEnabled = ref(false);
+const consulOperatorAutopilotWriteEnabled = ref(false);
+const consulOperatorRaftWriteEnabled = ref(false);
+const consulOperatorKeyringWriteEnabled = ref(false);
+const consulOperatorLicenseWriteEnabled = ref(false);
// --- MQTT-specific form fields ---
const mqttHost = ref("127.0.0.1");
@@ -1131,6 +1148,7 @@ const driverProfiles: Record<
rocketmq: { type: "mq", port: 9876, user: "", label: "Apache RocketMQ", icon: "rocketmq", host: "127.0.0.1" },
rabbitmq: { type: "mq", port: 5672, user: "", label: "RabbitMQ", icon: "rabbitmq", host: "127.0.0.1" },
nacos: { type: "nacos", port: 8848, user: "nacos", label: "Nacos", icon: "nacos", host: "127.0.0.1" },
+ consul: { type: "consul", port: 8500, user: "", label: "Consul", icon: "consul", host: "127.0.0.1" },
mqtt: { type: "mqtt", port: 1883, user: "", label: "MQTT", icon: "mqtt", host: "127.0.0.1" },
iris: { type: "iris", port: 1972, user: "_SYSTEM", label: "IRIS", icon: "iris" },
influxdb: { type: "influxdb", port: 8086, user: "", label: "InfluxDB", icon: "InfluxDB" },
@@ -1351,6 +1369,31 @@ function hydrateNacosFields(value: unknown) {
resetNacosFields(value as Partial<NacosAdminConfig>);
}
+function resetConsulFields(value?: Record<string, unknown>) {
+ consulServerAddr.value = String(value?.serverAddr || value?.server_addr || "http://127.0.0.1:8500");
+ consulDatacenter.value = String(value?.datacenter || value?.consulDatacenter || value?.consul_datacenter || "");
+ consulNamespace.value = String(value?.namespace || value?.consulNamespace || value?.consul_namespace || "");
+ consulPartition.value = String(value?.partition || value?.consulPartition || value?.consul_partition || "");
+ const consistency = String(value?.consistency || value?.consulConsistency || value?.consul_consistency || "default");
+ consulConsistency.value = (["default", "stale", "consistent"].includes(consistency) ? consistency : "default") as ConsulConsistency;
+ consulTlsSkipVerify.value = Boolean(value?.tlsSkipVerify || value?.tls_skip_verify || value?.consulTlsSkipVerify || value?.consul_tls_skip_verify);
+ const agentTarget = value?.agentTarget || value?.agent_target;
+ const target = agentTarget && typeof agentTarget === "object" ? (agentTarget as Record<string, unknown>) : undefined;
+ consulAgentTargetNode.value = String(target?.node || "");
+ consulAgentTargetAddress.value = String(target?.address || "");
+ consulMeshVisible.value = Boolean(value?.consulMeshVisible);
+ consulOperatorVisible.value = Boolean(value?.consulOperatorVisible);
+ consulOperatorSnapshotRestoreEnabled.value = Boolean(value?.consulOperatorSnapshotRestoreEnabled);
+ consulOperatorAutopilotWriteEnabled.value = Boolean(value?.consulOperatorAutopilotWriteEnabled);
+ consulOperatorRaftWriteEnabled.value = Boolean(value?.consulOperatorRaftWriteEnabled);
+ consulOperatorKeyringWriteEnabled.value = Boolean(value?.consulOperatorKeyringWriteEnabled);
+ consulOperatorLicenseWriteEnabled.value = Boolean(value?.consulOperatorLicenseWriteEnabled);
+}
+
+function hydrateConsulFields(value: unknown) {
+ resetConsulFields(value && typeof value === "object" ? (value as Record<string, unknown>) : undefined);
+}
+
function resetMqttFields(config?: Partial<MqttConnectionConfig>) {
mqttHost.value = config?.host?.trim() || "127.0.0.1";
mqttPort.value = config?.port || 1883;
@@ -1685,6 +1728,46 @@ function buildNacosAdminConfig(): NacosAdminConfig {
};
}
+function buildConsulExternalConfig(): Record<string, unknown> {
+ let parsed: URL;
+ try {
+ parsed = new URL(consulServerAddr.value.trim());
+ } catch {
+ throw new Error(t("connection.consulAddressInvalid"));
+ }
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(t("connection.consulAddressInvalid"));
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) throw new Error(t("connection.consulAddressInvalid"));
+ const targetNode = consulAgentTargetNode.value.trim();
+ const targetAddress = consulAgentTargetAddress.value.trim();
+ if (!!targetNode !== !!targetAddress) throw new Error(t("connection.consulAgentTargetIncomplete"));
+ if (targetAddress && !consulAgentAddressesMatch(targetAddress, parsed.hostname)) {
+ throw new Error(t("connection.consulAgentTargetAddressMismatch"));
+ }
+ return {
+ serverAddr: parsed.toString().replace(/\/$/, ""),
+ datacenter: consulDatacenter.value.trim() || undefined,
+ namespace: consulNamespace.value.trim() || undefined,
+ partition: consulPartition.value.trim() || undefined,
+ consistency: consulConsistency.value,
+ tlsSkipVerify: consulTlsSkipVerify.value || undefined,
+ agentTarget: targetNode ? { node: targetNode, address: targetAddress } : undefined,
+ consulMeshVisible: consulMeshVisible.value || undefined,
+ consulOperatorVisible: consulOperatorVisible.value || undefined,
+ consulOperatorSnapshotRestoreEnabled: consulOperatorSnapshotRestoreEnabled.value || undefined,
+ consulOperatorAutopilotWriteEnabled: consulOperatorAutopilotWriteEnabled.value || undefined,
+ consulOperatorRaftWriteEnabled: consulOperatorRaftWriteEnabled.value || undefined,
+ consulOperatorKeyringWriteEnabled: consulOperatorKeyringWriteEnabled.value || undefined,
+ consulOperatorLicenseWriteEnabled: consulOperatorLicenseWriteEnabled.value || undefined,
+ };
+}
+
+function applyConsulServerAddr(config: LegacyConnectionConfig, serverAddr: string) {
+ const parsed = new URL(serverAddr);
+ config.host = parsed.hostname;
+ config.port = Number(parsed.port) || (parsed.protocol === "https:" ? 443 : 8500);
+ config.ssl = parsed.protocol === "https:";
+}
+
function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
@@ -2262,6 +2345,14 @@ function applyProfile(val: string, preserveConnectionFields = false) {
form.value.connection_string = undefined;
form.value.url_params = "";
}
+ if (profile.type === "consul") {
+ resetConsulFields();
+ form.value.database = undefined;
+ form.value.connection_string = undefined;
+ form.value.username = "";
+ form.value.password = "";
+ form.value.url_params = "";
+ }
if (profile.type === "mqtt") {
resetMqttFields();
form.value.database = undefined;
@@ -2384,6 +2475,11 @@ watch(
} else {
resetNacosFields();
}
+ if (config.db_type === "consul") {
+ hydrateConsulFields(config.external_config);
+ } else {
+ resetConsulFields();
+ }
if (config.db_type === "mqtt") {
hydrateMqttFields(config.external_config);
} else {
@@ -2640,6 +2736,7 @@ const iconTypeMap: Record<string, string> = {
rocketmq: "rocketmq",
rabbitmq: "rabbitmq",
nacos: "nacos",
+ consul: "consul",
mqtt: "mqtt",
dm: "dm",
h2: "h2",
@@ -2745,6 +2842,7 @@ const dbOptions: DbOption[] = [
{ value: "rabbitmq", label: "RabbitMQ" },
{ value: "mqtt", label: "MQTT" },
{ value: "nacos", label: "Nacos" },
+ { value: "consul", label: "Consul" },
{ value: "influxdb", label: "InfluxDB" },
{ value: "victoriametrics", label: "VictoriaMetrics" },
{ value: "iris", label: "IRIS" },
@@ -2805,7 +2903,7 @@ const dbCategoryDefinitions: Array<{
{
key: "registry_config",
titleKey: "connection.databaseCategoryRegistryConfig",
- optionValues: ["etcd", "zookeeper", "nacos"],
+ optionValues: ["etcd", "zookeeper", "nacos", "consul"],
},
];
@@ -2921,6 +3019,7 @@ const tlsCapableDatabaseTypes = new Set<DatabaseType>([
"dameng",
"redis",
"etcd",
+ "consul",
"clickhouse",
"elasticsearch",
"easysearch",
@@ -3279,6 +3378,7 @@ const hasRequiredConnectionTarget = computed(() => {
if (form.value.db_type === "zookeeper") return !!(form.value.host || form.value.connection_string || connectionUrlInput.value.trim());
if (form.value.db_type === "mqtt") return !!mqttHost.value.trim() && mqttPort.value > 0;
if (form.value.db_type === "nacos") return !!nacosServerAddr.value.trim();
+ if (form.value.db_type === "consul") return !!consulServerAddr.value.trim();
if (isCloudflareD1Connection(form.value)) return hasCloudflareD1Credentials(form.value);
if (isH2FileMode.value) return !!(form.value.host.trim() || h2FilePathFromJdbcUrl(form.value.connection_string));
return !!(form.value.host || (mongoUseUrl.value && form.value.connection_string) || (form.value.db_type === "jdbc" && form.value.connection_string) || connectionUrlInput.value.trim());
@@ -3679,6 +3779,20 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo
config.database = undefined;
config.connection_string = undefined;
config.url_params = "";
+ } else if (config.db_type === "consul") {
+ const consulConfig = buildConsulExternalConfig();
+ config.external_config = consulConfig;
+ applyConsulServerAddr(config, String(consulConfig.serverAddr));
+ config.client_cert_path = config.client_cert_path?.trim() || "";
+ config.client_key_path = config.client_key_path?.trim() || "";
+ if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
+ throw new Error(t("connection.etcdClientCertPairRequired"));
+ }
+ config.username = "";
+ config.password = config.password.trim();
+ config.database = undefined;
+ config.connection_string = undefined;
+ config.url_params = "";
} else if (config.db_type === "mqtt") {
const mqttConfig = buildMqttExternalConfig();
config.external_config = mqttConfig;
@@ -3813,12 +3927,12 @@ function connectionConfigForSubmit(id: string, generatedName = ""): ConnectionCo
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
throw new Error(t("connection.etcdClientCertPairRequired"));
}
- } else {
+ } else if (form.value.db_type !== "consul") {
config.etcd_endpoints = undefined;
config.client_cert_path = undefined;
config.client_key_path = undefined;
}
- if (config.db_type !== "mysql" && config.db_type !== "clickhouse" && config.db_type !== "etcd" && config.db_type !== "starrocks" && config.db_type !== "mongodb" && config.db_type !== "victoriametrics") {
+ if (config.db_type !== "mysql" && config.db_type !== "clickhouse" && config.db_type !== "etcd" && config.db_type !== "consul" && config.db_type !== "starrocks" && config.db_type !== "mongodb" && config.db_type !== "victoriametrics") {
config.ca_cert_path = undefined;
} else {
config.ca_cert_path = config.ca_cert_path?.trim() || "";
@@ -5442,7 +5556,7 @@ function openExternalUrl(url: string) {
<TabsContent value="connection" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">
<div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto pt-4 pr-2 pb-6" :class="{ 'connection-form-body--nacos': form.db_type === 'nacos' }">
- <div v-if="!isJdbcConnection && form.db_type !== 'nacos'" class="grid grid-cols-4 items-center gap-4">
+ <div v-if="!isJdbcConnection && form.db_type !== 'nacos' && form.db_type !== 'consul'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.connectionUrlOptional") }}</Label>
<div class="col-span-3 flex items-center gap-1">
<Input v-model="connectionUrlInput" class="flex-1" :placeholder="connectionUrlPlaceholder" @keydown.enter.prevent="applyConnectionUrl" />
@@ -6174,6 +6288,80 @@ function openExternalUrl(url: string) {
</div>
</template>
+ <!-- Consul KV: HTTP endpoint, ACL token and scope -->
+ <template v-else-if="form.db_type === 'consul'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulAddress") }}</Label>
+ <Input v-model="consulServerAddr" class="col-span-3" placeholder="http://127.0.0.1:8500" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulToken") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.consulTokenPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulDatacenter") }}</Label>
+ <Input v-model="consulDatacenter" class="col-span-3" placeholder="dc1" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulNamespace") }}</Label>
+ <Input v-model="consulNamespace" class="col-span-3" placeholder="default" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulPartition") }}</Label>
+ <Input v-model="consulPartition" class="col-span-3" placeholder="default" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.consulAgentTargetNode") }}</Label>
+ <Input v-model="consulAgentTargetNode" class="col-span-3" placeholder="consul-client-1" />
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulAgentTargetAddress") }}</Label>
+ <div class="col-span-3 space-y-1">
+ <Input v-model="consulAgentTargetAddress" placeholder="127.0.0.1" />
+ <p class="text-xs text-muted-foreground">{{ t("connection.consulAgentTargetHint") }}</p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulConsistency") }}</Label>
+ <Select v-model="consulConsistency">
+ <SelectTrigger class="col-span-3 h-9"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="default">{{ t("connection.consulConsistencyDefault") }}</SelectItem>
+ <SelectItem value="stale">{{ t("connection.consulConsistencyStale") }}</SelectItem>
+ <SelectItem value="consistent">{{ t("connection.consulConsistencyConsistent") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.consulTlsSkipVerify") }}</Label>
+ <div class="col-span-3 flex items-center gap-2">
+ <Switch v-model="consulTlsSkipVerify" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.consulTlsSkipVerifyHint") }}</span>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulMeshFeatures") }}</Label>
+ <div class="col-span-3 flex items-start justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
+ <div class="space-y-1">
+ <div class="text-sm font-medium">{{ t("connection.consulMeshVisible") }}</div>
+ <p class="text-xs text-muted-foreground">{{ t("connection.consulMeshVisibleHint") }}</p>
+ </div>
+ <Switch v-model="consulMeshVisible" class="mt-0.5 shrink-0" />
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelTopClass">{{ t("connection.consulOperatorWrites") }}</Label>
+ <div class="col-span-3 grid gap-2 rounded-md border bg-muted/20 px-3 py-2 text-xs">
+ <label class="flex items-center gap-2"><input v-model="consulOperatorVisible" type="checkbox" />{{ t("connection.consulOperatorVisible") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorSnapshotRestoreEnabled" type="checkbox" />{{ t("connection.consulOperatorSnapshotRestore") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorAutopilotWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorAutopilot") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorRaftWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorRaft") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorKeyringWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorKeyring") }}</label>
+ <label class="flex items-center gap-2"><input v-model="consulOperatorLicenseWriteEnabled" type="checkbox" />{{ t("connection.consulOperatorLicense") }}</label>
+ </div>
+ </div>
+ </template>
+
<!-- etcd: endpoints, user, password, TLS -->
<template v-else-if="form.db_type === 'etcd'">
<div class="grid grid-cols-4 items-center gap-4">
@@ -6997,7 +7185,7 @@ function openExternalUrl(url: string) {
<TabsContent v-if="supportsTlsToggle" value="tls" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">
<div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2 pb-6">
- <div v-if="!supportsPostgresTlsOptions && !supportsMysqlTlsOptions" class="grid grid-cols-4 items-center gap-4">
+ <div v-if="!supportsPostgresTlsOptions && !supportsMysqlTlsOptions && form.db_type !== 'consul'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelSmallClass">SSL/TLS</Label>
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="tlsEnabled" class="mr-0" />
@@ -7050,7 +7238,7 @@ function openExternalUrl(url: string) {
</label>
</div>
- <template v-if="form.db_type === 'etcd'">
+ <template v-if="form.db_type === 'etcd' || form.db_type === 'consul'">
<div class="grid grid-cols-4 items-start gap-4">
<Label :class="connectionLabelSmallPaddedClass">
<span class="inline-flex items-center justify-end gap-1">
diff --git a/apps/desktop/src/components/consul/ConsulAcl.vue b/apps/desktop/src/components/consul/ConsulAcl.vue
new file mode 100644
index 0000000000..5f0ec7b172
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulAcl.vue
@@ -0,0 +1,296 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from "vue";
+import { Clipboard, Eye, EyeOff, Loader2, Pencil, Plus, RefreshCcw, Trash2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import NacosConfigDiffDialog from "@/components/nacos/NacosConfigDiffDialog.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import * as api from "@/lib/backend/api";
+import type { ConsulAclItem, ConsulAclKind, ConsulAclReferences, ConsulAclWrite, ConsulCapabilities } from "@/types/consul";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{ connectionId: string; capabilities: ConsulCapabilities | null }>();
+const { t } = useI18n();
+const store = useConnectionStore();
+const readOnly = computed(() => Boolean(store.getConfig(props.connectionId)?.read_only));
+const active = ref<ConsulAclKind>("token");
+const items = ref<Record<string, unknown>[]>([]);
+const loading = ref(false);
+const error = ref("");
+const editorOpen = ref(false);
+const editorId = ref<string | null>(null);
+const editorJson = ref("{}");
+const editorOriginalJson = ref("");
+const savePreviewOpen = ref(false);
+const references = ref<ConsulAclReferences | null>(null);
+const editReferences = ref<ConsulAclReferences | null>(null);
+const pendingDelete = ref<{ id: string; label: string; kind: ConsulAclKind } | null>(null);
+const secretOnce = ref("");
+const secretRevealed = ref(false);
+const operationBusy = ref(false);
+let loadSequence = 0;
+
+const tabs = computed<{ value: ConsulAclKind; label: string }[]>(() => [
+ { value: "token", label: t("consul.ui.tokens") },
+ { value: "policy", label: t("consul.ui.policies") },
+ { value: "role", label: t("consul.ui.roles") },
+ { value: "authMethod", label: t("consul.ui.authMethods") },
+ { value: "bindingRule", label: t("consul.ui.bindingRules") },
+ { value: "templatedPolicy", label: t("consul.ui.templatedPolicies") },
+]);
+const activeLabel = computed(() => tabs.value.find((tab) => tab.value === active.value)?.label || active.value);
+function capabilityLabel(status?: string) {
+ if (status === "supported") return t("consul.ui.capabilitySupported");
+ if (status === "unsupported") return t("consul.ui.capabilityUnsupported");
+ if (status === "disabled") return t("consul.ui.capabilityDisabled");
+ if (status === "forbidden") return t("consul.ui.capabilityForbidden");
+ return t("consul.ui.capabilityUnknown");
+}
+const capability = computed(() => (active.value === "authMethod" ? props.capabilities?.authMethods : active.value === "bindingRule" ? props.capabilities?.bindingRules : active.value === "templatedPolicy" ? props.capabilities?.templatedPolicies : props.capabilities?.acl));
+const canWrite = computed(() => !readOnly.value && capability.value === "supported" && active.value !== "templatedPolicy");
+
+function itemId(item: Record<string, unknown>): string {
+ return String(item.AccessorID || item.ID || item.Name || item.TemplateName || "");
+}
+function itemLabel(item: Record<string, unknown>): string {
+ return String(item.Name || item.Description || item.AccessorID || item.ID || item.TemplateName || "-");
+}
+function clearSecret() {
+ secretOnce.value = "";
+ secretRevealed.value = false;
+}
+function scrubSecret(item: Record<string, unknown>) {
+ if (typeof item.SecretID === "string" && item.SecretID) {
+ secretOnce.value = item.SecretID;
+ secretRevealed.value = false;
+ delete item.SecretID;
+ }
+}
+async function load() {
+ const sequence = ++loadSequence;
+ const connectionId = props.connectionId;
+ const kind = active.value;
+ loading.value = true;
+ error.value = "";
+ items.value = [];
+ try {
+ const result = await api.consulAclList(connectionId, kind);
+ if (sequence !== loadSequence || connectionId !== props.connectionId || kind !== active.value) return;
+ items.value = (result.items as Record<string, unknown>[]).map((item) => {
+ const safe = { ...item };
+ delete safe.SecretID;
+ return safe;
+ });
+ } catch (cause) {
+ if (sequence === loadSequence && connectionId === props.connectionId && kind === active.value) error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (sequence === loadSequence && connectionId === props.connectionId && kind === active.value) loading.value = false;
+ }
+}
+function openCreate() {
+ editorId.value = null;
+ editorOriginalJson.value = "";
+ editorJson.value = JSON.stringify(defaultItem(active.value), null, 2);
+ editorOpen.value = true;
+}
+async function openEdit(item: Record<string, unknown>) {
+ const id = itemId(item);
+ editorId.value = id;
+ if (active.value === "templatedPolicy") {
+ editorJson.value = JSON.stringify(item, null, 2);
+ editorOriginalJson.value = editorJson.value;
+ editReferences.value = null;
+ editorOpen.value = true;
+ return;
+ }
+ try {
+ const [result, impact]: [ConsulAclItem, ConsulAclReferences | null] = await Promise.all([
+ api.consulAclGet(props.connectionId, active.value, id),
+ active.value === "policy" || active.value === "role" || active.value === "authMethod" ? api.consulAclReferences(props.connectionId, active.value, id) : Promise.resolve(null),
+ ]);
+ editReferences.value = impact;
+ const value = { ...(result.item as Record<string, unknown>) };
+ delete value.SecretID;
+ editorJson.value = JSON.stringify(value, null, 2);
+ editorOriginalJson.value = editorJson.value;
+ editorOpen.value = true;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function save() {
+ error.value = "";
+ try {
+ JSON.parse(editorJson.value);
+ savePreviewOpen.value = true;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function confirmSave() {
+ error.value = "";
+ try {
+ const item = JSON.parse(editorJson.value) as Record<string, unknown>;
+ delete item.SecretID;
+ const value = { kind: active.value, item } as ConsulAclWrite;
+ const result = await api.consulAclApply(props.connectionId, editorId.value, value);
+ scrubSecret(result.item as Record<string, unknown>);
+ savePreviewOpen.value = false;
+ editorOpen.value = false;
+ await load();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function runOperation(action: () => Promise<void>) {
+ if (operationBusy.value) return;
+ operationBusy.value = true;
+ error.value = "";
+ try {
+ await action();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ operationBusy.value = false;
+ }
+}
+async function inspectDelete(item: Record<string, unknown>) {
+ const id = itemId(item);
+ const label = itemLabel(item);
+ const kind = active.value;
+ const connectionId = props.connectionId;
+ await runOperation(async () => {
+ references.value = await api.consulAclReferences(connectionId, kind, id);
+ pendingDelete.value = { id, label, kind };
+ });
+}
+async function cloneToken(item: Record<string, unknown>) {
+ const description = window.prompt(t("consul.ui.cloneTokenDescription"), String(item.Description || ""));
+ if (description === null) return;
+ await runOperation(async () => {
+ const result = await api.consulAclTokenClone(props.connectionId, itemId(item), description);
+ scrubSecret(result as Record<string, unknown>);
+ await load();
+ });
+}
+async function remove() {
+ const pending = pendingDelete.value;
+ if (!pending || !references.value?.complete) return;
+ await runOperation(async () => {
+ await api.consulAclDelete(props.connectionId, pending.kind, pending.id);
+ pendingDelete.value = null;
+ references.value = null;
+ await load();
+ });
+}
+async function copySecret() {
+ if (!secretOnce.value) return;
+ await runOperation(async () => {
+ await navigator.clipboard.writeText(secretOnce.value);
+ clearSecret();
+ });
+}
+function closeDelete() {
+ pendingDelete.value = null;
+ references.value = null;
+}
+function defaultItem(kind: ConsulAclKind): Record<string, unknown> {
+ if (kind === "token") return { Description: "", Local: false, Policies: [], Roles: [] };
+ if (kind === "policy") return { Name: "", Description: "", Rules: "", Datacenters: [] };
+ if (kind === "role") return { Name: "", Description: "", Policies: [] };
+ if (kind === "authMethod") return { Name: "", Type: "jwt", DisplayName: "", Description: "", Config: {} };
+ return { Description: "", AuthMethod: "", Selector: "", BindType: "service", BindName: "" };
+}
+watch([active, () => props.connectionId], () => {
+ clearSecret();
+ void load();
+});
+onMounted(() => void load());
+onDeactivated(clearSecret);
+onBeforeUnmount(() => {
+ loadSequence += 1;
+ clearSecret();
+});
+defineExpose({
+ refresh: () => {
+ void load();
+ return true;
+ },
+});
+</script>
+
+<template>
+ <div class="flex h-full min-h-0 flex-col">
+ <Tabs v-model="active" class="flex min-h-0 flex-1 flex-col">
+ <div class="flex h-11 items-center justify-between border-b px-3">
+ <TabsList class="h-8 p-0.5"
+ ><TabsTrigger v-for="tab in tabs" :key="tab.value" :value="tab.value" class="h-7 px-2 text-xs">{{ tab.label }}</TabsTrigger></TabsList
+ >
+ <div class="flex gap-1">
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="loading || operationBusy" :title="t('consul.ui.refresh')" @click="load"><RefreshCcw class="h-3.5 w-3.5" /></Button
+ ><Button v-if="canWrite" size="sm" class="h-7 gap-1 text-xs" :disabled="operationBusy" @click="openCreate"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.create") }}</Button>
+ </div>
+ </div>
+ <TabsContent v-for="tab in tabs" :key="tab.value" :value="tab.value" class="m-0 min-h-0 flex-1 overflow-auto p-4">
+ <div v-if="capability !== 'supported'" class="border px-3 py-2 text-sm text-muted-foreground">{{ t("consul.ui.capability", { status: capabilityLabel(capability) }) }}</div>
+ <div v-else-if="loading" class="flex h-28 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ <div v-else-if="error" class="border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ error }}</div>
+ <div v-else class="divide-y border">
+ <div v-for="item in items" :key="itemId(item)" class="flex min-h-12 items-center gap-3 px-3 py-2">
+ <div class="min-w-0 flex-1">
+ <div class="truncate text-sm font-medium">{{ itemLabel(item) }}</div>
+ <div class="truncate text-xs text-muted-foreground">{{ itemId(item) }}</div>
+ </div>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="operationBusy" :title="t('consul.ui.viewOrEdit')" @click="openEdit(item)"><component :is="canWrite ? Pencil : Eye" class="h-3.5 w-3.5" /></Button
+ ><Button v-if="canWrite && active === 'token'" variant="ghost" size="icon" class="h-7 w-7" :disabled="operationBusy" :title="t('consul.ui.cloneToken')" @click="cloneToken(item)"><Clipboard class="h-3.5 w-3.5" /></Button
+ ><Button v-if="canWrite" variant="ghost" size="icon" class="h-7 w-7 text-destructive" :disabled="operationBusy" :title="t('consul.ui.deleteAndInspectReferences')" @click="inspectDelete(item)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div v-if="!items.length" class="p-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.noResources") }}</div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ <div v-if="secretOnce" class="m-3 flex items-center gap-2 border border-amber-300 bg-amber-50 p-3 text-sm dark:bg-amber-950/30">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ secretRevealed ? secretOnce : "****************" }}</span
+ ><Button variant="ghost" size="icon" class="h-7 w-7" :title="secretRevealed ? t('consul.ui.hide') : t('consul.ui.reveal')" @click="secretRevealed = !secretRevealed"><EyeOff v-if="secretRevealed" class="h-3.5 w-3.5" /><Eye v-else class="h-3.5 w-3.5" /></Button
+ ><Button size="sm" class="h-7 gap-1" :disabled="operationBusy" @click="copySecret"><Clipboard class="h-3.5 w-3.5" />{{ t("consul.ui.copyOnce") }}</Button
+ ><Button variant="ghost" size="sm" @click="clearSecret">{{ t("consul.ui.hide") }}</Button>
+ </div>
+ </div>
+ <Dialog v-model:open="editorOpen"
+ ><DialogContent class="max-w-2xl"
+ ><DialogHeader
+ ><DialogTitle>{{ editorId ? t("consul.ui.editResource", { kind: activeLabel }) : t("consul.ui.createResource", { kind: activeLabel }) }}</DialogTitle></DialogHeader
+ >
+ <div v-if="editReferences" class="border bg-muted/20 px-3 py-2 text-xs">
+ {{ t("consul.ui.knownImpact", { tokens: editReferences.tokenAccessorIds.length, roles: editReferences.roleIds.length, bindingRules: editReferences.bindingRuleIds.length }) }}<span v-if="!editReferences.complete" class="ml-2 text-destructive">{{ t("consul.ui.incomplete") }}</span>
+ </div>
+ <textarea v-model="editorJson" class="h-80 w-full resize-none rounded-md border bg-background p-3 font-mono text-xs outline-none" spellcheck="false" :readonly="active === 'templatedPolicy'" /><DialogFooter
+ ><Button variant="outline" @click="editorOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button v-if="canWrite" @click="save">{{ t("consul.ui.save") }}</Button></DialogFooter
+ ></DialogContent
+ ></Dialog
+ >
+ <NacosConfigDiffDialog v-model:open="savePreviewOpen" :title="t('consul.ui.reviewAclChanges')" :before="editorOriginalJson" :after="editorJson" :confirm-label="t('consul.ui.apply')" @confirm="confirmSave" />
+ <Dialog
+ :open="Boolean(pendingDelete)"
+ @update:open="
+ (value) => {
+ if (!value) closeDelete();
+ }
+ "
+ ><DialogContent
+ ><DialogHeader
+ ><DialogTitle>{{ t("consul.ui.deleteResource", { label: pendingDelete?.label }) }}</DialogTitle></DialogHeader
+ >
+ <div v-if="references" class="space-y-2 text-sm">
+ <p>{{ t("consul.ui.tokenReferences", { tokens: references.tokenAccessorIds.length, roles: references.roleIds.length, bindingRules: references.bindingRuleIds.length }) }}</p>
+ <p v-if="!references.complete" class="text-destructive">{{ t("consul.ui.impactBlocked") }}</p>
+ </div>
+ <DialogFooter
+ ><Button variant="outline" :disabled="operationBusy" @click="closeDelete">{{ t("consul.ui.cancel") }}</Button
+ ><Button variant="destructive" :disabled="operationBusy || !references?.complete" @click="remove">{{ t("consul.ui.delete") }}</Button></DialogFooter
+ ></DialogContent
+ ></Dialog
+ >
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulHealth.vue b/apps/desktop/src/components/consul/ConsulHealth.vue
new file mode 100644
index 0000000000..373a8e5c13
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulHealth.vue
@@ -0,0 +1,666 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from "vue";
+import { CircleCheck, CircleX, Loader2, Pause, Plus, Radio, RefreshCcw, Search, Trash2, TriangleAlert, X } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import ConsulListPagination from "@/components/consul/ConsulListPagination.vue";
+import * as api from "@/lib/backend/api";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useConsulStore } from "@/stores/consulStore";
+import { nextWatchIndex } from "@/lib/consul/watchState";
+import { consulAgentWriteTargetSafe } from "@/lib/consul/agentTarget";
+import { clampConsulPage, CONSUL_LIST_PAGE_SIZE, paginateConsulItems } from "@/lib/consul/pagination";
+import { useI18n } from "vue-i18n";
+import type { ConsulAgentCheckDefinition, ConsulAgentCheckRegistration, ConsulAgentIdentity, ConsulCheckStatus, ConsulDomainWatchResponse, ConsulHealthCheck, ConsulScope, ConsulServiceInstance } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string }>();
+const { t } = useI18n();
+const store = useConnectionStore();
+const consulStore = useConsulStore();
+const state = ref("any");
+const browseMode = ref<"state" | "node" | "service">("state");
+const browseName = ref("");
+const browseNameDraft = ref("");
+const keywordFilter = ref("");
+const statusFilter = ref("any");
+const typeFilter = ref("any");
+const checks = ref<ConsulHealthCheck[]>([]);
+const selectedCheck = ref<ConsulHealthCheck | null>(null);
+const serviceInstances = ref<ConsulServiceInstance[]>([]);
+const localChecks = ref<Record<string, ConsulHealthCheck>>({});
+const identity = ref<ConsulAgentIdentity | null>(null);
+const checkPage = ref(1);
+const localCheckPage = ref(1);
+const serviceInstancePage = ref(1);
+const agentTarget = computed(() => {
+ const external = store.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ const raw = config.agentTarget || config.agent_target;
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const target = raw as Record<string, unknown>;
+ const node = String(target.node || "").trim();
+ const address = String(target.address || "").trim();
+ return node && address ? { node, address } : null;
+});
+const canAgentWrite = computed(() => consulAgentWriteTargetSafe(store.getConfig(props.connectionId), identity.value?.node));
+const errors = ref<Record<string, string>>({});
+const loading = ref(false);
+const editorOpen = ref(false);
+const saving = ref(false);
+const form = ref({ id: "", name: "", serviceId: "", type: "ttl", endpoint: "", interval: "10s", timeout: "2s", ttl: "30s", args: "" });
+let sequence = 0;
+const watchEnabled = ref(false);
+const watchPaused = ref(false);
+const watchIndex = ref<string | null>(null);
+let watchConnectionId = "";
+let watchScope: ConsulScope = { datacenter: "", namespace: "", partition: "" };
+let watchGeneration = 0;
+let watchOperationId = "";
+
+function normalizedCheckStatus(check: ConsulHealthCheck): string {
+ return check.Maintenance ? "maintenance" : String(check.Status || "unknown").toLocaleLowerCase();
+}
+
+function checkType(check: ConsulHealthCheck): string {
+ if (check.Maintenance) return "maintenance";
+ if (check.Definition?.TTL) return "ttl";
+ if (check.Definition?.HTTP) return "http";
+ if (check.Definition?.TCP) return "tcp";
+ if (check.Definition?.GRPC) return "grpc";
+ const raw = String(check.Type || "")
+ .trim()
+ .toLocaleLowerCase();
+ if (raw) return raw;
+ return check.ServiceID ? "service" : "node";
+}
+
+function matchesHealthFilters(check: ConsulHealthCheck): boolean {
+ if (statusFilter.value !== "any" && normalizedCheckStatus(check) !== statusFilter.value) return false;
+ if (typeFilter.value !== "any" && checkType(check) !== typeFilter.value) return false;
+ const query = keywordFilter.value.trim().toLocaleLowerCase();
+ if (!query) return true;
+ return [check.Name, check.CheckID, check.Node, check.ServiceName, check.ServiceID, check.Output, check.Notes, check.Type, check.ServiceTags.join(" "), JSON.stringify(check.Definition)].join(" ").toLocaleLowerCase().includes(query);
+}
+
+const localCheckItems = computed(() => Object.values(localChecks.value).sort((left, right) => left.Name.localeCompare(right.Name) || left.CheckID.localeCompare(right.CheckID)));
+const filteredChecks = computed(() => checks.value.filter(matchesHealthFilters));
+const filteredLocalChecks = computed(() => localCheckItems.value.filter(matchesHealthFilters));
+const pagedChecks = computed(() => paginateConsulItems(filteredChecks.value, checkPage.value));
+const pagedLocalChecks = computed(() => paginateConsulItems(filteredLocalChecks.value, localCheckPage.value));
+const pagedServiceInstances = computed(() => paginateConsulItems(serviceInstances.value, serviceInstancePage.value));
+const availableCheckTypes = computed(() => [...new Set([...checks.value, ...localCheckItems.value].map(checkType))].sort());
+const healthSummary = computed(() => {
+ const summary = { passing: 0, warning: 0, critical: 0, maintenance: 0 };
+ for (const check of checks.value) {
+ const status = normalizedCheckStatus(check);
+ if (status in summary) summary[status as keyof typeof summary]++;
+ }
+ return summary;
+});
+const hasActiveHealthFilters = computed(() => Boolean(keywordFilter.value.trim() || statusFilter.value !== "any" || typeFilter.value !== "any"));
+
+function errorMessage(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+function selectCheck(check: ConsulHealthCheck) {
+ selectedCheck.value = selectedCheck.value?.CheckID === check.CheckID && selectedCheck.value?.Node === check.Node ? null : check;
+}
+function currentScope(): ConsulScope {
+ const external = store.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ return {
+ datacenter: String(config.datacenter || config.consulDatacenter || config.consul_datacenter || ""),
+ namespace: String(config.namespace || config.consulNamespace || config.consul_namespace || ""),
+ partition: String(config.partition || config.consulPartition || config.consul_partition || ""),
+ };
+}
+function newWatchId() {
+ return globalThis.crypto?.randomUUID?.() || `consul-health-${Date.now()}-${Math.random()}`;
+}
+function watchActive(operationId: string) {
+ return watchEnabled.value && !watchPaused.value && watchOperationId === operationId && watchConnectionId === props.connectionId && watchGeneration === consulStore.generation;
+}
+async function stopWatch() {
+ const operationId = watchOperationId;
+ watchOperationId = "";
+ if (!operationId) return;
+ consulStore.completeOperation(operationId);
+ await api.consulCancelBlocking(watchConnectionId, watchScope, watchGeneration, operationId).catch(() => false);
+}
+function watchTarget(name: string) {
+ if (browseMode.value === "node") return { kind: "healthNode" as const, node: name };
+ if (browseMode.value === "service") return { kind: "healthServiceInstances" as const, service: name, passing: null };
+ return { kind: "healthState" as const, state: name };
+}
+
+async function runWatch(operationId: string, name: string, mode: typeof browseMode.value) {
+ let index: string | null = null;
+ while (watchActive(operationId) && browseMode.value === mode && (mode === "state" ? state.value : browseName.value) === name) {
+ try {
+ const result = (await api.consulDomainWatch(watchConnectionId, {
+ operationId,
+ generation: watchGeneration,
+ target: watchTarget(name),
+ index,
+ waitSeconds: 300,
+ })) as ConsulDomainWatchResponse<ConsulHealthCheck[] | ConsulServiceInstance[]>;
+ index = nextWatchIndex(index, result.metadata.index).index;
+ watchIndex.value = index;
+ if (result.changed || result.indexReset) {
+ if (mode === "service") {
+ serviceInstances.value = result.items as ConsulServiceInstance[];
+ checks.value = serviceInstances.value.flatMap((instance) => instance.Checks);
+ } else checks.value = result.items as ConsulHealthCheck[];
+ selectedCheck.value = checks.value.find((check) => check.CheckID === selectedCheck.value?.CheckID && check.Node === selectedCheck.value?.Node) || null;
+ }
+ } catch (error) {
+ if (watchActive(operationId) && !String(error).includes("CANCELLED")) errors.value = { ...errors.value, [t("consul.ui.watch")]: errorMessage(error) };
+ break;
+ }
+ }
+ consulStore.completeOperation(operationId);
+}
+async function startWatch() {
+ if (watchOperationId && watchEnabled.value && !watchPaused.value) return;
+ watchEnabled.value = true;
+ watchPaused.value = false;
+ watchConnectionId = props.connectionId;
+ watchScope = currentScope();
+ consulStore.bindConnection(watchConnectionId, watchScope);
+ watchGeneration = consulStore.generation;
+ watchOperationId = newWatchId();
+ consulStore.registerOperation(watchOperationId);
+ const name = browseMode.value === "state" ? state.value : browseName.value;
+ if (!name.trim()) {
+ watchEnabled.value = false;
+ consulStore.completeOperation(watchOperationId);
+ watchOperationId = "";
+ return;
+ }
+ void runWatch(watchOperationId, name, browseMode.value);
+}
+async function pauseWatch() {
+ watchPaused.value = true;
+ await stopWatch();
+}
+async function independent(name: string, action: () => Promise<void>) {
+ try {
+ await action();
+ } catch (error) {
+ errors.value = { ...errors.value, [name]: errorMessage(error) };
+ }
+}
+
+async function reloadHealthQuery() {
+ const resume = watchEnabled.value && !watchPaused.value;
+ await stopWatch();
+ await load();
+ if (resume && (browseMode.value === "state" || browseName.value.trim())) await startWatch();
+}
+
+async function switchHealthBrowseMode(mode: typeof browseMode.value) {
+ if (browseMode.value === mode) return;
+ browseMode.value = mode;
+ browseName.value = "";
+ browseNameDraft.value = "";
+ selectedCheck.value = null;
+ await reloadHealthQuery();
+}
+
+async function applyBrowseTarget() {
+ const target = browseNameDraft.value.trim();
+ if (!target) return;
+ browseName.value = target;
+ selectedCheck.value = null;
+ await reloadHealthQuery();
+}
+
+function clearHealthFilters() {
+ keywordFilter.value = "";
+ statusFilter.value = "any";
+ typeFilter.value = "any";
+ selectedCheck.value = null;
+}
+
+function applyStatusFilter(status: string) {
+ statusFilter.value = statusFilter.value === status ? "any" : status;
+}
+
+function checkTypeLabel(type: string): string {
+ const labels: Record<string, string> = {
+ ttl: t("consul.ui.ttl"),
+ http: t("consul.ui.http"),
+ tcp: t("consul.ui.tcp"),
+ grpc: t("consul.ui.grpc"),
+ docker: t("consul.ui.docker"),
+ script: t("consul.ui.script"),
+ maintenance: t("consul.ui.maintenance"),
+ service: t("consul.ui.service"),
+ node: t("consul.ui.node"),
+ };
+ return labels[type] || type;
+}
+
+async function load() {
+ const current = ++sequence;
+ loading.value = true;
+ errors.value = {};
+ await Promise.all([
+ independent(t("consul.ui.healthChecks"), async () => {
+ if (browseMode.value === "state") {
+ const value = await api.consulHealthState(props.connectionId, state.value);
+ if (current === sequence) {
+ checks.value = value.items;
+ serviceInstances.value = [];
+ }
+ } else if (browseMode.value === "node") {
+ if (!browseName.value.trim()) {
+ checks.value = [];
+ return;
+ }
+ const value = await api.consulHealthNode(props.connectionId, browseName.value);
+ if (current === sequence) {
+ checks.value = value.items;
+ serviceInstances.value = [];
+ }
+ } else {
+ if (!browseName.value.trim()) {
+ checks.value = [];
+ serviceInstances.value = [];
+ return;
+ }
+ const value = await api.consulHealthService(props.connectionId, browseName.value);
+ if (current === sequence) {
+ serviceInstances.value = value.items;
+ checks.value = value.items.flatMap((instance) => instance.Checks);
+ }
+ }
+ }),
+ independent(t("consul.ui.agent"), async () => {
+ const value = await api.consulAgentSelf(props.connectionId);
+ if (current === sequence) identity.value = value;
+ }),
+ independent(t("consul.ui.localAgentChecks"), async () => {
+ const value = await api.consulAgentChecks(props.connectionId);
+ if (current === sequence) localChecks.value = value;
+ }),
+ ]);
+ if (current === sequence) {
+ selectedCheck.value = checks.value.find((check) => check.CheckID === selectedCheck.value?.CheckID && check.Node === selectedCheck.value?.Node) || null;
+ loading.value = false;
+ }
+}
+
+function definition(): ConsulAgentCheckDefinition {
+ const common = { interval: form.value.interval, timeout: form.value.timeout };
+ if (form.value.type === "http") return { type: "http", url: form.value.endpoint, method: "GET", ...common, tlsSkipVerify: false };
+ if (form.value.type === "tcp") return { type: "tcp", address: form.value.endpoint, ...common };
+ if (form.value.type === "grpc") return { type: "grpc", address: form.value.endpoint, ...common, tls: false };
+ if (form.value.type === "docker") return { type: "docker", containerId: form.value.endpoint, shell: "", args: form.value.args.split(/\s+/).filter(Boolean), ...common };
+ if (form.value.type === "script") return { type: "script", args: form.value.args.split(/\s+/).filter(Boolean), ...common };
+ return { type: "ttl", ttl: form.value.ttl };
+}
+
+async function registerCheck() {
+ if (!canAgentWrite.value || !form.value.name.trim()) return;
+ saving.value = true;
+ try {
+ const registration: ConsulAgentCheckRegistration = { id: form.value.id.trim(), name: form.value.name.trim(), notes: "", serviceId: form.value.serviceId.trim(), status: "critical", definition: definition() };
+ await api.consulAgentRegisterCheck(props.connectionId, registration);
+ editorOpen.value = false;
+ await load();
+ } catch (error) {
+ errors.value = { ...errors.value, [t("consul.ui.writeOperation")]: errorMessage(error) };
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function updateTtl(id: string, status: ConsulCheckStatus) {
+ if (canAgentWrite.value)
+ await independent(t("consul.ui.writeOperation"), async () => {
+ await api.consulAgentUpdateTtl(props.connectionId, id, status);
+ await load();
+ });
+}
+async function deregister(id: string) {
+ if (canAgentWrite.value && window.confirm(t("consul.ui.deregisterCheck", { id, node: agentTarget.value?.node || t("consul.ui.targetAgent") })))
+ await independent(t("consul.ui.writeOperation"), async () => {
+ await api.consulAgentDeregisterCheck(props.connectionId, id);
+ await load();
+ });
+}
+function statusClass(check: ConsulHealthCheck) {
+ if (check.Maintenance) return "text-blue-700 dark:text-blue-300";
+ if (check.Status === "passing") return "text-emerald-700 dark:text-emerald-300";
+ if (check.Status === "warning") return "text-amber-700 dark:text-amber-300";
+ return "text-destructive";
+}
+function statusLabel(check: ConsulHealthCheck) {
+ if (check.Maintenance) return t("consul.ui.maintenance");
+ if (check.Status === "passing") return t("consul.ui.passing");
+ if (check.Status === "warning") return t("consul.ui.warning");
+ if (check.Status === "critical") return t("consul.ui.critical");
+ return t("consul.ui.unknown");
+}
+
+watch(
+ () => props.connectionId,
+ async () => {
+ await stopWatch();
+ watchEnabled.value = false;
+ watchPaused.value = false;
+ watchIndex.value = null;
+ await load();
+ },
+);
+watch(state, async () => {
+ if (browseMode.value === "state") await reloadHealthQuery();
+});
+watch([keywordFilter, statusFilter, typeFilter], () => {
+ checkPage.value = 1;
+ localCheckPage.value = 1;
+ selectedCheck.value = null;
+});
+watch(filteredChecks, (items) => {
+ checkPage.value = clampConsulPage(checkPage.value, items.length);
+});
+watch(filteredLocalChecks, (items) => {
+ localCheckPage.value = clampConsulPage(localCheckPage.value, items.length);
+});
+watch(serviceInstances, (items) => {
+ serviceInstancePage.value = clampConsulPage(serviceInstancePage.value, items.length);
+});
+onMounted(load);
+onDeactivated(() => {
+ watchPaused.value = true;
+ void stopWatch();
+});
+onBeforeUnmount(() => {
+ void stopWatch();
+});
+defineExpose({ refresh: () => (void load(), true) });
+</script>
+
+<template>
+ <div class="h-full overflow-auto p-4">
+ <header class="mb-4 flex flex-wrap items-start justify-between gap-3 border-b pb-3">
+ <div class="min-w-0">
+ <h2 class="text-lg font-semibold">{{ t("consul.ui.healthChecks") }}</h2>
+ <div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <Badge :variant="canAgentWrite ? 'secondary' : 'outline'" :class="canAgentWrite ? 'text-emerald-700 dark:text-emerald-300' : 'border-amber-500/40 text-amber-700 dark:text-amber-300'">{{
+ t("consul.ui.agentTarget", { target: canAgentWrite && agentTarget ? `${agentTarget.node} (${agentTarget.address})` : t("consul.ui.unknownWritesDisabled") })
+ }}</Badge>
+ <span v-if="watchEnabled">{{ watchPaused ? t("consul.ui.watchPaused") : t("consul.ui.watchingIndex", { index: watchIndex || "1" }) }}</span>
+ </div>
+ </div>
+ <div class="flex shrink-0 items-center gap-2">
+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :title="watchEnabled && !watchPaused ? t('consul.ui.pauseWatch') : t('consul.ui.startWatch')" :disabled="browseMode !== 'state' && !browseName.trim()" @click="watchEnabled && !watchPaused ? pauseWatch() : startWatch()"
+ ><Pause v-if="watchEnabled && !watchPaused" class="h-3.5 w-3.5" /><Radio v-else class="h-3.5 w-3.5" />{{ watchEnabled && !watchPaused ? t("consul.ui.pauseWatch") : t("consul.ui.startWatch") }}</Button
+ >
+ <Button size="icon" variant="outline" class="h-8 w-8" :disabled="loading" :title="t('consul.ui.refresh')" @click="load"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ <Button size="sm" class="h-8 gap-1.5" :disabled="!canAgentWrite" @click="editorOpen = !editorOpen"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.register") }}</Button>
+ </div>
+ </header>
+
+ <section class="mb-4 rounded-lg border bg-muted/10 p-3">
+ <div class="flex flex-wrap items-center gap-2">
+ <div class="grid shrink-0 grid-cols-3 text-xs">
+ <Button size="sm" class="h-8 rounded-r-none" :variant="browseMode === 'state' ? 'default' : 'outline'" @click="switchHealthBrowseMode('state')">{{ t("consul.ui.state") }}</Button>
+ <Button size="sm" class="h-8 rounded-none" :variant="browseMode === 'node' ? 'default' : 'outline'" @click="switchHealthBrowseMode('node')">{{ t("consul.ui.node") }}</Button>
+ <Button size="sm" class="h-8 rounded-l-none" :variant="browseMode === 'service' ? 'default' : 'outline'" @click="switchHealthBrowseMode('service')">{{ t("consul.ui.service") }}</Button>
+ </div>
+ <select v-if="browseMode === 'state'" v-model="state" class="h-8 rounded-md border bg-background px-2 text-xs">
+ <option value="any">{{ t("consul.ui.allStates") }}</option>
+ <option value="passing">{{ t("consul.ui.passing") }}</option>
+ <option value="warning">{{ t("consul.ui.warning") }}</option>
+ <option value="critical">{{ t("consul.ui.critical") }}</option>
+ </select>
+ <div v-else class="flex min-w-56 flex-1 sm:max-w-sm">
+ <Input v-model="browseNameDraft" class="h-8 rounded-r-none text-xs" :placeholder="browseMode === 'node' ? t('consul.ui.nodeName') : t('consul.ui.serviceName')" @keydown.enter="applyBrowseTarget" />
+ <Button size="sm" class="h-8 rounded-l-none px-3" :disabled="!browseNameDraft.trim()" @click="applyBrowseTarget">{{ t("consul.ui.query") }}</Button>
+ </div>
+ <div class="hidden h-6 w-px bg-border lg:block" />
+ <div class="relative min-w-64 flex-1">
+ <Search class="pointer-events-none absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
+ <Input v-model="keywordFilter" class="h-8 pl-8 text-xs" :placeholder="t('consul.ui.searchHealthChecks')" />
+ </div>
+ <select v-model="statusFilter" class="h-8 rounded-md border bg-background px-2 text-xs">
+ <option value="any">{{ t("consul.ui.allStates") }}</option>
+ <option value="passing">{{ t("consul.ui.passing") }}</option>
+ <option value="warning">{{ t("consul.ui.warning") }}</option>
+ <option value="critical">{{ t("consul.ui.critical") }}</option>
+ <option value="maintenance">{{ t("consul.ui.maintenance") }}</option>
+ </select>
+ <select v-model="typeFilter" class="h-8 rounded-md border bg-background px-2 text-xs">
+ <option value="any">{{ t("consul.ui.allCheckTypes") }}</option>
+ <option v-for="type in availableCheckTypes" :key="type" :value="type">{{ checkTypeLabel(type) }}</option>
+ </select>
+ <Button v-if="hasActiveHealthFilters" size="sm" variant="ghost" class="h-8 gap-1 px-2 text-xs" @click="clearHealthFilters"><X class="h-3.5 w-3.5" />{{ t("consul.ui.clearFilters") }}</Button>
+ </div>
+ <div class="mt-3 flex flex-wrap items-center gap-2 border-t pt-3 text-xs">
+ <span class="mr-1 text-muted-foreground">{{ t("consul.ui.healthResultCount", { filtered: filteredChecks.length, total: checks.length }) }}</span>
+ <button type="button" @click="applyStatusFilter('passing')">
+ <Badge variant="outline" :class="statusFilter === 'passing' ? 'border-emerald-500/50 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300' : 'text-emerald-700 dark:text-emerald-300'">{{ t("consul.ui.passing") }} {{ healthSummary.passing }}</Badge>
+ </button>
+ <button type="button" @click="applyStatusFilter('warning')">
+ <Badge variant="outline" :class="statusFilter === 'warning' ? 'border-amber-500/50 bg-amber-500/10 text-amber-700 dark:text-amber-300' : 'text-amber-700 dark:text-amber-300'">{{ t("consul.ui.warning") }} {{ healthSummary.warning }}</Badge>
+ </button>
+ <button type="button" @click="applyStatusFilter('critical')">
+ <Badge variant="outline" :class="statusFilter === 'critical' ? 'border-destructive/50 bg-destructive/10 text-destructive' : 'text-destructive'">{{ t("consul.ui.critical") }} {{ healthSummary.critical }}</Badge>
+ </button>
+ <button type="button" @click="applyStatusFilter('maintenance')">
+ <Badge variant="outline" :class="statusFilter === 'maintenance' ? 'border-blue-500/50 bg-blue-500/10 text-blue-700 dark:text-blue-300' : ''">{{ t("consul.ui.maintenance") }} {{ healthSummary.maintenance }}</Badge>
+ </button>
+ </div>
+ </section>
+ <div v-if="Object.keys(errors).length" class="mb-3 rounded-lg border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800 dark:bg-amber-950/30 dark:text-amber-200">
+ <div v-for="(error, name) in errors" :key="name">
+ <strong>{{ name }}:</strong> {{ error }}
+ </div>
+ </div>
+ <section v-if="editorOpen" class="mb-4 overflow-hidden rounded-lg border">
+ <div class="border-b bg-muted/30 px-4 py-3">
+ <h3 class="text-sm font-medium">{{ t("consul.ui.register") }}</h3>
+ <p class="mt-1 text-xs text-amber-700 dark:text-amber-300">{{ t("consul.ui.checkRegistrationHint", { node: agentTarget?.node || t("consul.ui.targetAgent") }) }}</p>
+ </div>
+ <div class="grid gap-x-5 gap-y-4 p-4 md:grid-cols-3">
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.name") }}</Label
+ ><Input v-model="form.name" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.id") }}</Label
+ ><Input v-model="form.id" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.serviceId") }}</Label
+ ><Input v-model="form.serviceId" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.type") }}</Label
+ ><select v-model="form.type" class="h-9 w-full rounded-md border bg-background px-2 text-sm">
+ <option value="ttl">{{ t("consul.ui.ttl") }}</option>
+ <option value="http">{{ t("consul.ui.http") }}</option>
+ <option value="tcp">{{ t("consul.ui.tcp") }}</option>
+ <option value="grpc">{{ t("consul.ui.grpc") }}</option>
+ <option value="docker">{{ t("consul.ui.docker") }}</option>
+ <option value="script">{{ t("consul.ui.script") }}</option>
+ </select>
+ </div>
+ <div v-if="form.type === 'ttl'" class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.ttl") }}</Label
+ ><Input v-model="form.ttl" class="h-9" />
+ </div>
+ <div v-else-if="form.type === 'script'" class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.arguments") }}</Label
+ ><Input v-model="form.args" class="h-9" />
+ </div>
+ <div v-else class="space-y-1.5">
+ <Label class="text-xs">{{ form.type === "docker" ? t("consul.ui.containerId") : t("consul.ui.endpoint") }}</Label
+ ><Input v-model="form.endpoint" class="h-9" />
+ </div>
+ <template v-if="form.type !== 'ttl'">
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.interval") }}</Label
+ ><Input v-model="form.interval" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.timeout") }}</Label
+ ><Input v-model="form.timeout" class="h-9" />
+ </div>
+ <div v-if="form.type === 'docker'" class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.commandArguments") }}</Label
+ ><Input v-model="form.args" class="h-9" />
+ </div>
+ </template>
+ </div>
+ <div class="flex justify-end gap-2 border-t bg-muted/10 px-4 py-3">
+ <Button size="sm" variant="outline" @click="editorOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button size="sm" :disabled="saving || !canAgentWrite || !form.name.trim()" @click="registerCheck"><Loader2 v-if="saving" class="mr-1 h-3.5 w-3.5 animate-spin" />{{ t("consul.ui.registerOn", { node: agentTarget?.node || t("consul.ui.targetAgent") }) }}</Button>
+ </div>
+ </section>
+ <section class="mb-4 overflow-hidden rounded-lg border">
+ <div class="flex flex-wrap items-center justify-between gap-2 border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <span>{{ browseMode === "state" ? t("consul.ui.clusterHealth") : browseMode === "node" ? t("consul.ui.nodeHealth", { node: browseName || "-" }) : t("consul.ui.serviceHealth", { service: browseName || "-" }) }}</span
+ ><Badge variant="secondary">{{ filteredChecks.length }}</Badge>
+ </div>
+ <ConsulListPagination
+ :total="filteredChecks.length"
+ :page="checkPage"
+ :page-size="CONSUL_LIST_PAGE_SIZE"
+ @update:page="
+ checkPage = $event;
+ selectedCheck = null;
+ "
+ />
+ </div>
+ <button
+ v-for="check in pagedChecks"
+ :key="`${check.Node}-${check.CheckID}`"
+ type="button"
+ class="grid min-h-16 w-full grid-cols-[2rem_minmax(0,1fr)] items-center gap-x-3 gap-y-2 border-b px-4 py-3 text-left text-xs last:border-0 hover:bg-muted/30 focus-visible:bg-muted/30 focus-visible:outline-none"
+ :class="selectedCheck?.CheckID === check.CheckID && selectedCheck?.Node === check.Node && 'bg-muted/40'"
+ :aria-expanded="selectedCheck?.CheckID === check.CheckID && selectedCheck?.Node === check.Node"
+ @click="selectCheck(check)"
+ >
+ <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted/60"
+ ><CircleCheck v-if="check.Status === 'passing' && !check.Maintenance" class="h-4 w-4 text-emerald-600" /><TriangleAlert v-else-if="check.Status === 'warning' || check.Maintenance" class="h-4 w-4 text-amber-600" /><CircleX v-else class="h-4 w-4 text-destructive"
+ /></span>
+ <span class="grid min-w-0 gap-x-8 gap-y-2 md:grid-cols-[minmax(12rem,1.1fr)_minmax(10rem,.75fr)] xl:grid-cols-[minmax(14rem,1fr)_minmax(10rem,.65fr)_minmax(14rem,1.15fr)]">
+ <span class="min-w-0">
+ <span class="flex min-w-0 flex-wrap items-center gap-2"
+ ><span class="truncate font-medium">{{ check.Name }}</span
+ ><Badge variant="outline" class="h-5 px-1.5 text-[10px]" :class="statusClass(check)">{{ statusLabel(check) }}</Badge
+ ><Badge variant="secondary" class="h-5 px-1.5 text-[10px]">{{ checkTypeLabel(checkType(check)) }}</Badge></span
+ >
+ <span class="mt-1 block truncate font-mono text-[11px] text-muted-foreground" :title="check.CheckID">{{ check.CheckID }}</span>
+ </span>
+ <span class="min-w-0">
+ <span class="block text-[10px] uppercase tracking-wide text-muted-foreground">{{ check.ServiceID ? t("consul.ui.service") : t("consul.ui.node") }}</span>
+ <span class="mt-1 block truncate font-medium" :title="check.ServiceName || check.Node">{{ check.ServiceName || check.Node }}</span>
+ <span v-if="check.ServiceID" class="mt-0.5 block truncate text-muted-foreground" :title="check.Node">{{ check.Node }}</span>
+ </span>
+ <span class="min-w-0 md:col-span-2 xl:col-span-1">
+ <span class="block text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("consul.ui.output") }}</span>
+ <span class="mt-1 block truncate text-muted-foreground" :title="check.Output || check.Notes">{{ check.Output || check.Notes || "-" }}</span>
+ </span>
+ </span>
+ </button>
+ <div v-if="!filteredChecks.length && !loading" class="px-3 py-8 text-center text-xs text-muted-foreground">{{ t("consul.ui.noMatchingHealthChecks") }}</div>
+ <div v-if="loading" class="flex items-center justify-center px-3 py-8 text-xs text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ </section>
+ <section v-if="selectedCheck" class="mb-4 overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between border-b bg-muted/30 px-3 py-2.5 text-sm font-medium">
+ <span>{{ t("consul.ui.checkDetails", { check: selectedCheck.Name }) }}</span
+ ><Button size="icon" variant="ghost" class="h-7 w-7" :title="t('consul.ui.close')" @click="selectedCheck = null"><CircleX class="h-3.5 w-3.5" /></Button>
+ </div>
+ <dl class="grid text-xs md:grid-cols-2">
+ <div class="border-b px-3 py-3 md:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.checkId") }}</dt>
+ <dd class="mt-1 break-all font-mono">{{ selectedCheck.CheckID }}</dd>
+ </div>
+ <div class="border-b px-3 py-3">
+ <dt class="text-muted-foreground">{{ t("consul.ui.serviceId") }}</dt>
+ <dd class="mt-1 break-all font-mono">{{ selectedCheck.ServiceID || "-" }}</dd>
+ </div>
+ <div class="border-b px-3 py-3 md:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.notes") }}</dt>
+ <dd class="mt-1 whitespace-pre-wrap break-words">{{ selectedCheck.Notes || "-" }}</dd>
+ </div>
+ <div class="border-b px-3 py-3">
+ <dt class="text-muted-foreground">{{ t("consul.ui.output") }}</dt>
+ <dd class="mt-1 whitespace-pre-wrap break-words">{{ selectedCheck.Output || "-" }}</dd>
+ </div>
+ <div class="border-b px-3 py-3 md:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.definition") }}</dt>
+ <dd class="mt-1 break-all font-mono">{{ JSON.stringify(selectedCheck.Definition) }}</dd>
+ </div>
+ <div class="border-b px-3 py-3">
+ <dt class="text-muted-foreground">{{ t("consul.ui.indexes") }}</dt>
+ <dd class="mt-1 font-mono">{{ selectedCheck.CreateIndex }} / {{ selectedCheck.ModifyIndex }}</dd>
+ </div>
+ </dl>
+ </section>
+ <section v-if="browseMode === 'service' && serviceInstances.length" class="mb-4 overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <span>{{ t("consul.ui.serviceInstances") }}</span
+ ><Badge variant="secondary">{{ serviceInstances.length }}</Badge>
+ </div>
+ <ConsulListPagination :total="serviceInstances.length" :page="serviceInstancePage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="serviceInstancePage = $event" />
+ </div>
+ <div v-for="instance in pagedServiceInstances" :key="`${instance.Node.Node}-${instance.Service.ID}`" class="border-b px-3 py-2.5 text-xs last:border-0">
+ <span class="font-medium">{{ instance.Node.Node }}</span
+ ><span class="ml-2 text-muted-foreground">{{ instance.Service.Address || instance.Node.Address }}:{{ instance.Service.Port }} · {{ instance.Service.ID }}</span>
+ </div>
+ </section>
+ <section class="overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between gap-2 border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <span>{{ t("consul.ui.localAgentChecks") }}</span
+ ><Badge variant="secondary"
+ >{{ filteredLocalChecks.length }}<span v-if="hasActiveHealthFilters"> / {{ localCheckItems.length }}</span></Badge
+ >
+ </div>
+ <ConsulListPagination :total="filteredLocalChecks.length" :page="localCheckPage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="localCheckPage = $event" />
+ </div>
+ <div v-for="check in pagedLocalChecks" :key="check.CheckID" class="grid min-h-16 gap-3 border-b px-4 py-3 text-xs last:border-0 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center">
+ <div class="grid min-w-0 grid-cols-[2rem_minmax(0,1fr)] items-center gap-x-3 gap-y-2 sm:grid-cols-[2rem_minmax(12rem,1fr)_minmax(10rem,.7fr)] xl:grid-cols-[2rem_minmax(13rem,.9fr)_minmax(10rem,.65fr)_minmax(13rem,1fr)]">
+ <span class="flex h-8 w-8 items-center justify-center rounded-full bg-muted/60"
+ ><CircleCheck v-if="check.Status === 'passing' && !check.Maintenance" class="h-4 w-4 text-emerald-600" /><TriangleAlert v-else-if="check.Status === 'warning' || check.Maintenance" class="h-4 w-4 text-amber-600" /><CircleX v-else class="h-4 w-4 text-destructive"
+ /></span>
+ <div class="min-w-0">
+ <div class="flex min-w-0 flex-wrap items-center gap-2">
+ <span class="truncate font-medium">{{ check.Name }}</span
+ ><Badge variant="outline" class="h-5 px-1.5 text-[10px]" :class="statusClass(check)">{{ statusLabel(check) }}</Badge
+ ><Badge variant="secondary" class="h-5 px-1.5 text-[10px]">{{ checkTypeLabel(checkType(check)) }}</Badge>
+ </div>
+ <div class="mt-1 truncate font-mono text-[11px] text-muted-foreground" :title="check.CheckID">{{ check.CheckID }}</div>
+ </div>
+ <div class="col-start-2 min-w-0 sm:col-start-auto">
+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ check.ServiceID ? t("consul.ui.service") : t("consul.ui.node") }}</div>
+ <div class="mt-1 truncate font-medium" :title="check.ServiceName || check.Node">{{ check.ServiceName || check.Node }}</div>
+ <div v-if="check.ServiceID" class="mt-0.5 truncate text-muted-foreground" :title="check.Node">{{ check.Node }}</div>
+ </div>
+ <div class="col-start-2 min-w-0 sm:col-span-2 xl:col-span-1 xl:col-start-auto">
+ <div class="text-[10px] uppercase tracking-wide text-muted-foreground">{{ t("consul.ui.output") }}</div>
+ <div class="mt-1 truncate text-muted-foreground" :title="check.Output || check.Notes">{{ check.Output || check.Notes || "-" }}</div>
+ </div>
+ </div>
+ <div class="flex shrink-0 items-center justify-end gap-0.5 border-t pt-2 lg:border-l lg:border-t-0 lg:pl-3 lg:pt-0">
+ <template v-if="check.Definition?.TTL"
+ ><Button size="icon" variant="ghost" class="h-7 w-7 text-emerald-600" :disabled="!canAgentWrite" :title="t('consul.ui.ttlPass')" @click="updateTtl(check.CheckID, 'passing')"><CircleCheck class="h-3.5 w-3.5" /></Button
+ ><Button size="icon" variant="ghost" class="h-7 w-7 text-amber-600" :disabled="!canAgentWrite" :title="t('consul.ui.ttlWarn')" @click="updateTtl(check.CheckID, 'warning')"><TriangleAlert class="h-3.5 w-3.5" /></Button
+ ><Button size="icon" variant="ghost" class="h-7 w-7 text-destructive" :disabled="!canAgentWrite" :title="t('consul.ui.ttlFail')" @click="updateTtl(check.CheckID, 'critical')"><CircleX class="h-3.5 w-3.5" /></Button
+ ></template>
+ <Button size="icon" variant="ghost" class="h-7 w-7 text-destructive" :disabled="!canAgentWrite" :title="t('consul.ui.deregister')" @click="deregister(check.CheckID)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+ <div v-if="!filteredLocalChecks.length && !loading" class="px-3 py-8 text-center text-xs text-muted-foreground">{{ t("consul.ui.noMatchingHealthChecks") }}</div>
+ </section>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulKeyBrowser.vue b/apps/desktop/src/components/consul/ConsulKeyBrowser.vue
new file mode 100644
index 0000000000..3ca55fe3b0
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulKeyBrowser.vue
@@ -0,0 +1,1024 @@
+<script setup lang="ts">
+import { computed, nextTick, onBeforeUnmount, onDeactivated, ref, watch } from "vue";
+import { ArrowRightLeft, Download, FileUp, Loader2, Search, X } from "@lucide/vue";
+import { useI18n } from "vue-i18n";
+import KvKeyBrowser from "@/components/kv/KvKeyBrowser.vue";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { useToast } from "@/composables/useToast";
+import * as api from "@/lib/backend/api";
+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
+import { kvExportFilenameStem, type KvExportScopeRequest } from "@/lib/kv/kvExportScope";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useConsulStore } from "@/stores/consulStore";
+import { isCurrentWatchEvent, nextWatchIndex } from "@/lib/consul/watchState";
+import type { ConsulDeletePrefixPreview, ConsulDeletePrefixReport, ConsulImportConflictPolicy, ConsulImportPreview, ConsulImportReport, ConsulKvBundle, ConsulSearchMatch, ConsulScope, ConsulWatchEvent } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string }>();
+const { t } = useI18n();
+const { toast } = useToast();
+const connectionStore = useConnectionStore();
+const consulStore = useConsulStore();
+const browserRef = ref<InstanceType<typeof KvKeyBrowser> | null>(null);
+const fileInputRef = ref<HTMLInputElement>();
+const readOnly = computed(() => Boolean(connectionStore.getConfig(props.connectionId)?.read_only));
+const consulConnections = computed(() => connectionStore.connections.filter((connection) => connection.db_type === "consul"));
+const transferTargetConnections = computed(() => (transferMode.value === "migration" ? consulConnections.value.filter((connection) => connection.id !== props.connectionId) : consulConnections.value));
+
+const searchOpen = ref(false);
+const searchQuery = ref("");
+const searchPrefix = ref("");
+const searchScope = ref<"all" | "key" | "value">("all");
+const searchCaseSensitive = ref(false);
+const searchRunning = ref(false);
+const searchScanned = ref(0);
+const searchMatched = ref(0);
+const searchLimited = ref(false);
+const searchFiltered = ref(false);
+const searchResults = ref<ConsulSearchMatch[]>([]);
+const searchError = ref("");
+const exportingSearchResults = ref(false);
+const searchHighlight = ref<{ key: string; query: string; caseSensitive: boolean; matchesKey: boolean; matchesValue: boolean } | null>(null);
+let searchRequestId = "";
+let searchConnectionId = "";
+let searchScopeAtStart: ConsulScope = { datacenter: "", namespace: "", partition: "" };
+let searchGeneration = 0;
+let searchProgressTimer: ReturnType<typeof setTimeout> | null = null;
+let searchProgressSequence = 0;
+
+const exportOpen = ref(false);
+const exportPrefix = ref("");
+const exporting = ref(false);
+
+const transferOpen = ref(false);
+const transferMode = ref<"import" | "migration">("import");
+const transferBundle = ref<ConsulKvBundle | null>(null);
+const transferTargetId = ref("");
+const transferSourcePrefix = ref("");
+const transferPolicy = ref<ConsulImportConflictPolicy>("abort");
+const transferPreview = ref<ConsulImportPreview | null>(null);
+const transferReport = ref<ConsulImportReport | null>(null);
+const transferLoading = ref(false);
+const transferApplying = ref(false);
+const transferError = ref("");
+const transferTargetReadOnly = computed(() => Boolean(connectionStore.getConfig(transferTargetId.value)?.read_only));
+
+const deleteOpen = ref(false);
+const deletePrefix = ref("");
+const deletePreview = ref<ConsulDeletePrefixPreview | null>(null);
+const deleteReport = ref<ConsulDeletePrefixReport | null>(null);
+const deleteLoading = ref(false);
+const deleteExecuting = ref(false);
+const deleteError = ref("");
+type PrefixSuggestionTarget = "export" | "migration" | "delete";
+const prefixSuggestionTarget = ref<PrefixSuggestionTarget | null>(null);
+const prefixSuggestions = ref<Array<{ key: string }>>([]);
+const prefixSuggestionIndex = ref(-1);
+const prefixSuggestionDebounceMs = 300;
+let prefixSuggestionTimer: ReturnType<typeof setTimeout> | null = null;
+let prefixSuggestionRequestId = 0;
+const watchPrefix = ref("");
+const watchMode = ref<"key" | "prefix">("prefix");
+const watchRunning = ref(false);
+const watchIndex = ref<string | null>(null);
+const watchError = ref("");
+let watchOperationId = "";
+let watchUnlisten: (() => void) | null = null;
+let watchConnectionId = "";
+let watchScope: ConsulScope = { datacenter: "", namespace: "", partition: "" };
+let watchGeneration = 0;
+
+function currentScope() {
+ const external = connectionStore.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ return {
+ datacenter: String(config.datacenter || config.consulDatacenter || config.consul_datacenter || ""),
+ namespace: String(config.namespace || config.consulNamespace || config.consul_namespace || ""),
+ partition: String(config.partition || config.consulPartition || config.consul_partition || ""),
+ };
+}
+
+async function startWatch() {
+ if (watchRunning.value) return;
+ watchError.value = "";
+ watchIndex.value = null;
+ watchConnectionId = props.connectionId;
+ watchScope = currentScope();
+ consulStore.bindConnection(watchConnectionId, watchScope);
+ watchGeneration = consulStore.generation;
+ watchOperationId = globalThis.crypto?.randomUUID?.() || `watch-${Date.now()}`;
+ consulStore.registerOperation(watchOperationId);
+ watchRunning.value = true;
+ if (isTauriRuntime()) {
+ const { listen } = await import("@tauri-apps/api/event");
+ try {
+ watchUnlisten = await listen<ConsulWatchEvent>("consul-watch", (event) => {
+ const payload = event.payload;
+ if (!isCurrentWatchEvent({ connectionId: watchConnectionId, operationId: watchOperationId, generation: watchGeneration }, payload)) return;
+ if (payload.error) {
+ if (watchRunning.value && !payload.error.includes("CANCELLED")) toast(payload.error, 5000);
+ void stopWatch();
+ return;
+ }
+ if (payload.result) applyWatchResult(payload.result);
+ if (watchRunning.value) void startTauriWatchRequest();
+ });
+ await startTauriWatchRequest();
+ } catch (error) {
+ if (watchRunning.value) toast(error instanceof Error ? error.message : String(error), 5000);
+ await stopWatch();
+ }
+ return;
+ }
+ while (watchRunning.value) {
+ try {
+ const result = await api.consulBlockingQuery(watchConnectionId, {
+ operationId: watchOperationId,
+ generation: watchGeneration,
+ key: watchPrefix.value,
+ prefix: watchMode.value === "prefix",
+ index: watchIndex.value,
+ waitSeconds: 300,
+ });
+ applyWatchResult(result);
+ } catch (error) {
+ if (watchRunning.value && !String(error).includes("CANCELLED")) {
+ watchError.value = error instanceof Error ? error.message : String(error);
+ toast(watchError.value, 5000);
+ }
+ break;
+ }
+ }
+ watchRunning.value = false;
+ consulStore.completeOperation(watchOperationId);
+}
+
+function watchRequest() {
+ return {
+ operationId: watchOperationId,
+ generation: watchGeneration,
+ key: watchPrefix.value,
+ prefix: watchMode.value === "prefix",
+ index: watchIndex.value,
+ waitSeconds: 300,
+ };
+}
+
+async function watchSelectedKey(route: { key: string }) {
+ if (watchRunning.value && watchMode.value === "key" && watchPrefix.value === route.key) {
+ await stopWatch();
+ return;
+ }
+ if (watchRunning.value) await stopWatch();
+ watchMode.value = "key";
+ watchPrefix.value = route.key;
+ await startWatch();
+}
+
+async function startTauriWatchRequest() {
+ await api.consulWatchStart(watchConnectionId, watchRequest());
+}
+
+function applyWatchResult(result: import("@/types/consul").ConsulBlockingResponse) {
+ const next = nextWatchIndex(watchIndex.value, result.metadata.index);
+ watchIndex.value = next.index;
+ if (result.changed) browserRef.value?.refresh();
+}
+
+async function stopWatch() {
+ if (!watchRunning.value) return;
+ watchRunning.value = false;
+ await api.consulCancelBlocking(watchConnectionId, watchScope, watchGeneration, watchOperationId).catch(() => false);
+ watchUnlisten?.();
+ watchUnlisten = null;
+ consulStore.completeOperation(watchOperationId);
+}
+
+const consulApi = {
+ listPrefix: api.consulListPrefix,
+ get: api.consulGet,
+ put: api.consulPut,
+ deleteKey: api.consulDelete,
+ rename: renameConsulKey,
+ copy: copyConsulKey,
+ exportScope: exportConsulScope,
+};
+
+async function mutateConsulKey(connectionId: string, request: { key: string; newKey: string; expectedModRevision?: api.KvInt64 | null }, copy: boolean) {
+ if (!request.expectedModRevision) throw new Error(`CONSUL_CAS_REQUIRED: ${t("consul.ui.sourceKeyMissingModifyIndex")}`);
+ const result = await api.consulRenameKey(connectionId, request.key, request.newKey, request.expectedModRevision, copy);
+ if (!result.committed) {
+ const detail = result.errors.map((error) => `[${error.opIndex}] ${error.message}`).join("; ");
+ throw new Error(`CONSUL_TXN_CONFLICT: ${detail || t("consul.ui.transactionRejected")}`);
+ }
+ return result;
+}
+
+async function renameConsulKey(connectionId: string, request: { key: string; newKey: string; expectedModRevision?: api.KvInt64 | null }) {
+ await mutateConsulKey(connectionId, request, false);
+ return { renamed: true };
+}
+
+async function copyConsulKey(connectionId: string, request: { key: string; newKey: string; expectedModRevision?: api.KvInt64 | null }) {
+ await mutateConsulKey(connectionId, request, true);
+ return { copied: true };
+}
+
+const labels = computed(() => ({
+ prefixPlaceholder: t("consul.prefixPlaceholder"),
+ newKey: t("consul.newKey"),
+ loadingKeys: t("consul.loadingKeys"),
+ empty: t("consul.empty"),
+ loadMore: t("consul.loadMore"),
+ selectKey: t("consul.selectKey"),
+ loadingValue: t("consul.loadingValue"),
+ notFound: t("consul.notFound"),
+ edit: t("consul.edit"),
+ editKey: t("consul.editKey"),
+ delete: t("consul.delete"),
+ deleteTitle: t("consul.deleteTitle"),
+ keyLabel: t("consul.keyLabel"),
+ keyPlaceholder: t("consul.keyPlaceholder"),
+ keyRequired: t("consul.keyRequired"),
+ rootReadonly: t("consul.rootReadonly"),
+ saved: t("consul.saved"),
+ deleted: t("consul.deleted"),
+ base64Readonly: t("consul.base64Readonly"),
+ rename: t("consul.rename"),
+ clone: t("consul.clone"),
+ copyKey: t("consul.copyKey"),
+ export: t("consul.export"),
+ value: t("consul.value"),
+ valueContent: t("consul.valueContent"),
+ format: t("consul.format"),
+ metadata: t("consul.metadata"),
+ prettyJson: t("consul.prettyJson"),
+ invalidJson: t("consul.invalidJson"),
+ summarySize: t("consul.summarySize"),
+ conflict: t("consul.conflict"),
+ keyAlreadyExists: t("consul.keyAlreadyExists"),
+ aclFiltered: t("consul.aclFiltered"),
+ locked: t("consul.locked"),
+ sessionProtected: t("consul.ui.sessionProtected"),
+ sessionProtectedHint: t("consul.ui.sessionProtectedHint"),
+ sessionId: t("consul.ui.sessionId"),
+ copy: t("consul.ui.copy"),
+ copied: t("consul.ui.copied"),
+ copyFailed: t("consul.ui.copyFailed"),
+ valueTooLarge: t("consul.valueTooLarge"),
+ deletePrefix: t("consul.tools.deletePrefix"),
+ watch: t("consul.watchKey"),
+ stopWatching: t("consul.stopWatching"),
+}));
+
+async function exportConsulScope(connectionId: string, request: KvExportScopeRequest) {
+ exporting.value = true;
+ try {
+ const bundle = await api.consulExportBundle(connectionId, { path: request.path, kind: request.kind });
+ const filename = `dbx-consul-${kvExportFilenameStem(request.path)}-${Date.now()}.json`;
+ const saved = await saveBundle(bundle, filename);
+ if (saved) toast(t("consul.tools.exported", { count: bundle.entries.length }), 2500);
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error), 5000);
+ } finally {
+ exporting.value = false;
+ }
+}
+
+async function saveJsonFile(payload: unknown, filename: string, fileType: string): Promise<boolean> {
+ const content = JSON.stringify(payload, null, 2);
+ if (isTauriRuntime()) {
+ const [{ save }, { writeTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
+ const path = await save({ defaultPath: filename, filters: [{ name: fileType, extensions: ["json"] }] });
+ if (!path) return false;
+ await writeTextFile(path, content);
+ return true;
+ }
+ const url = URL.createObjectURL(new Blob([content], { type: "application/json" }));
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.click();
+ URL.revokeObjectURL(url);
+ return true;
+}
+
+async function saveBundle(bundle: ConsulKvBundle, filename: string): Promise<boolean> {
+ return saveJsonFile(bundle, filename, t("consul.ui.bundleFileType"));
+}
+
+async function exportPrefixBundle() {
+ await exportConsulScope(props.connectionId, { path: exportPrefix.value, kind: "prefix" });
+ exportOpen.value = false;
+}
+
+function openSearch() {
+ searchOpen.value = true;
+ searchError.value = "";
+}
+
+async function runSearch() {
+ const query = searchQuery.value.trim();
+ if (!query || searchRunning.value) return;
+ consulStore.bindConnection(props.connectionId, currentScope());
+ searchConnectionId = props.connectionId;
+ searchScopeAtStart = currentScope();
+ searchGeneration = consulStore.generation;
+ searchRequestId = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`;
+ searchRunning.value = true;
+ searchScanned.value = 0;
+ searchMatched.value = 0;
+ searchLimited.value = false;
+ searchFiltered.value = false;
+ searchResults.value = [];
+ searchError.value = "";
+ startSearchProgress();
+ try {
+ const result = await api.consulSearch(props.connectionId, {
+ requestId: searchRequestId,
+ prefix: searchPrefix.value,
+ query,
+ searchKeys: searchScope.value !== "value",
+ searchValues: searchScope.value !== "key",
+ caseSensitive: searchCaseSensitive.value,
+ limit: 1000,
+ maxScan: 10_000,
+ generation: searchGeneration,
+ });
+ if (props.connectionId !== searchConnectionId || consulStore.generation !== searchGeneration) return;
+ searchResults.value = result.matches;
+ searchScanned.value = result.scanned;
+ searchMatched.value = result.matched;
+ searchLimited.value = result.limited;
+ searchFiltered.value = Boolean(result.filteredByAcls);
+ } catch (error) {
+ if (props.connectionId !== searchConnectionId || consulStore.generation !== searchGeneration) return;
+ const message = error instanceof Error ? error.message : String(error);
+ if (!message.includes("CONSUL_SEARCH_CANCELLED")) searchError.value = message;
+ } finally {
+ stopSearchProgress();
+ searchRunning.value = false;
+ }
+}
+
+async function exportSearchResults() {
+ if (!searchResults.value.length || exportingSearchResults.value) return;
+ exportingSearchResults.value = true;
+ try {
+ const report = {
+ format: "dbx-consul-kv-search-results",
+ version: 1,
+ exportedAtUnixMs: Date.now(),
+ source: currentScope(),
+ search: {
+ query: searchQuery.value.trim(),
+ prefix: searchPrefix.value.trim(),
+ scope: searchScope.value,
+ caseSensitive: searchCaseSensitive.value,
+ scanned: searchScanned.value,
+ matched: searchMatched.value,
+ limited: searchLimited.value,
+ filteredByAcls: searchFiltered.value,
+ },
+ results: searchResults.value,
+ };
+ const saved = await saveJsonFile(report, `dbx-consul-search-${Date.now()}.json`, t("consul.tools.searchResultsFileType"));
+ if (saved) toast(t("consul.tools.searchResultsExported", { count: searchResults.value.length }), 2500);
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error), 5000);
+ } finally {
+ exportingSearchResults.value = false;
+ }
+}
+
+function startSearchProgress() {
+ stopSearchProgress();
+ const sequence = ++searchProgressSequence;
+ const poll = async () => {
+ if (sequence !== searchProgressSequence || !searchRequestId) {
+ searchProgressTimer = null;
+ return;
+ }
+ try {
+ const progress = await api.consulSearchProgress(searchConnectionId, searchRequestId, searchScopeAtStart, searchGeneration);
+ if (progress.running) searchScanned.value = progress.scanned;
+ } catch {
+ // Progress is best-effort; the search result carries the authoritative count.
+ }
+ if (sequence === searchProgressSequence && searchRequestId)
+ searchProgressTimer = setTimeout(() => {
+ void poll();
+ }, 250);
+ else searchProgressTimer = null;
+ };
+ searchProgressTimer = setTimeout(() => {
+ void poll();
+ }, 250);
+}
+
+function stopSearchProgress() {
+ searchProgressSequence += 1;
+ if (searchProgressTimer) clearTimeout(searchProgressTimer);
+ searchProgressTimer = null;
+}
+
+async function cancelSearch() {
+ if (!searchRequestId) return;
+ await api.consulCancelSearch(searchConnectionId, searchRequestId, searchScopeAtStart, searchGeneration);
+}
+
+async function openSearchResult(result: ConsulSearchMatch) {
+ searchHighlight.value = {
+ key: result.key,
+ query: searchQuery.value.trim(),
+ caseSensitive: searchCaseSensitive.value,
+ matchesKey: result.matchesKey,
+ matchesValue: result.matchesValue,
+ };
+ searchOpen.value = false;
+ await nextTick();
+ await browserRef.value?.selectKey(result.key);
+}
+
+function validateBundle(value: unknown): ConsulKvBundle {
+ const bundle = value as Partial<ConsulKvBundle>;
+ if (bundle.format !== "dbx-consul-kv-bundle" || bundle.version !== 1 || !Array.isArray(bundle.entries)) {
+ throw new Error(t("consul.tools.invalidBundle"));
+ }
+ return bundle as ConsulKvBundle;
+}
+
+async function chooseImportFile() {
+ if (isTauriRuntime()) {
+ const [{ open }, { readTextFile }] = await Promise.all([import("@tauri-apps/plugin-dialog"), import("@tauri-apps/plugin-fs")]);
+ const path = await open({ multiple: false, filters: [{ name: t("consul.ui.bundleFileType"), extensions: ["json"] }] });
+ if (!path || Array.isArray(path)) return;
+ await loadImportText(await readTextFile(path));
+ return;
+ }
+ fileInputRef.value?.click();
+}
+
+async function onImportFile(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ input.value = "";
+ if (file) await loadImportText(await file.text());
+}
+
+async function loadImportText(text: string) {
+ try {
+ transferMode.value = "import";
+ transferBundle.value = validateBundle(JSON.parse(text));
+ transferTargetId.value = props.connectionId;
+ transferPolicy.value = "abort";
+ transferPreview.value = null;
+ transferReport.value = null;
+ transferError.value = "";
+ transferOpen.value = true;
+ await previewTransfer();
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error), 5000);
+ }
+}
+
+function openMigration() {
+ closePrefixSuggestions();
+ transferMode.value = "migration";
+ transferBundle.value = null;
+ transferTargetId.value = consulConnections.value.find((connection) => connection.id !== props.connectionId)?.id || "";
+ transferSourcePrefix.value = "";
+ transferPolicy.value = "abort";
+ transferPreview.value = null;
+ transferReport.value = null;
+ transferError.value = "";
+ transferOpen.value = true;
+}
+
+async function loadMigrationPreview() {
+ if (!transferTargetId.value) return;
+ transferLoading.value = true;
+ transferError.value = "";
+ try {
+ transferBundle.value = await api.consulExportBundle(props.connectionId, { path: transferSourcePrefix.value, kind: "prefix" });
+ await previewTransfer();
+ } catch (error) {
+ transferError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ transferLoading.value = false;
+ }
+}
+
+async function previewTransfer() {
+ if (!transferBundle.value || !transferTargetId.value) return;
+ transferLoading.value = true;
+ transferPreview.value = null;
+ transferReport.value = null;
+ transferError.value = "";
+ try {
+ transferPreview.value = await api.consulImportPreview(transferTargetId.value, {
+ bundle: transferBundle.value,
+ policy: transferPolicy.value,
+ });
+ } catch (error) {
+ transferError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ transferLoading.value = false;
+ }
+}
+
+async function executeTransfer() {
+ if (!transferBundle.value || !transferTargetId.value || !transferPreview.value?.canApply) return;
+ transferApplying.value = true;
+ transferError.value = "";
+ try {
+ transferReport.value = await api.consulImportExecute(transferTargetId.value, {
+ bundle: transferBundle.value,
+ policy: transferPolicy.value,
+ previewId: transferPreview.value.previewId,
+ });
+ toast(t("consul.tools.importApplied", { count: transferReport.value.succeeded }), 3000);
+ if (transferTargetId.value === props.connectionId) browserRef.value?.refresh();
+ } catch (error) {
+ transferError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ transferApplying.value = false;
+ }
+}
+
+function resetTransferPreview() {
+ transferPreview.value = null;
+ transferReport.value = null;
+ if (transferMode.value === "import") void previewTransfer();
+}
+
+function openDeletePrefix(prefix = "") {
+ closePrefixSuggestions();
+ deletePrefix.value = prefix;
+ deletePreview.value = null;
+ deleteReport.value = null;
+ deleteError.value = "";
+ deleteOpen.value = true;
+}
+
+function closePrefixSuggestions() {
+ prefixSuggestionRequestId++;
+ if (prefixSuggestionTimer) {
+ clearTimeout(prefixSuggestionTimer);
+ prefixSuggestionTimer = null;
+ }
+ prefixSuggestionTarget.value = null;
+ prefixSuggestionIndex.value = -1;
+ prefixSuggestions.value = [];
+}
+
+function prefixValue(target: PrefixSuggestionTarget): string {
+ if (target === "export") return exportPrefix.value;
+ if (target === "migration") return transferSourcePrefix.value;
+ return deletePrefix.value;
+}
+
+function setPrefixValue(target: PrefixSuggestionTarget, value: string) {
+ if (target === "export") exportPrefix.value = value;
+ else if (target === "migration") transferSourcePrefix.value = value;
+ else deletePrefix.value = value;
+}
+
+function schedulePrefixSuggestions(target: PrefixSuggestionTarget, value: string) {
+ closePrefixSuggestions();
+ const query = value.trim();
+ if (!query) {
+ prefixSuggestions.value = [];
+ return;
+ }
+
+ const requestId = ++prefixSuggestionRequestId;
+ const connectionId = props.connectionId;
+ prefixSuggestionTarget.value = target;
+ prefixSuggestionTimer = setTimeout(() => {
+ void api
+ .consulListPrefix(connectionId, query, 8, null)
+ .then((result) => {
+ if (requestId !== prefixSuggestionRequestId || connectionId !== props.connectionId || prefixValue(target).trim() !== query) return;
+ prefixSuggestions.value = result.keys;
+ })
+ .catch(() => {
+ if (requestId === prefixSuggestionRequestId) prefixSuggestions.value = [];
+ });
+ }, prefixSuggestionDebounceMs);
+}
+
+function acceptPrefixSuggestion(target: PrefixSuggestionTarget, index: number) {
+ const suggestion = prefixSuggestions.value[index];
+ if (!suggestion) return;
+ setPrefixValue(target, suggestion.key);
+ // A directory suggestion ends with `/`. Immediately query that accepted
+ // prefix so the user can continue completing the next path segment without
+ // deleting and retyping the slash.
+ schedulePrefixSuggestions(target, suggestion.key);
+}
+
+function movePrefixSuggestion(target: PrefixSuggestionTarget, delta: number) {
+ if (prefixSuggestionTarget.value !== target || !prefixSuggestions.value.length) return;
+ prefixSuggestionIndex.value = (prefixSuggestionIndex.value + delta + prefixSuggestions.value.length) % prefixSuggestions.value.length;
+}
+
+function onPrefixSuggestionKeydown(target: PrefixSuggestionTarget, event: KeyboardEvent) {
+ if (event.isComposing) return;
+ if (event.key === "Escape") {
+ closePrefixSuggestions();
+ return;
+ }
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ if (prefixSuggestionTarget.value !== target || !prefixSuggestions.value.length) return;
+ event.preventDefault();
+ movePrefixSuggestion(target, event.key === "ArrowDown" ? 1 : -1);
+ return;
+ }
+ if (event.key !== "Enter" && event.key !== "Tab") return;
+ if (prefixSuggestionTarget.value === target && prefixSuggestions.value.length > 0) {
+ event.preventDefault();
+ acceptPrefixSuggestion(target, prefixSuggestionIndex.value >= 0 ? prefixSuggestionIndex.value : 0);
+ return;
+ }
+ // With no active completion, Tab keeps its native focus-navigation behavior.
+ if (event.key === "Tab") return;
+ if (target === "delete" && deletePrefix.value.trim() && !deletePreview.value) {
+ event.preventDefault();
+ void previewDeletePrefix();
+ }
+}
+
+async function previewDeletePrefix() {
+ if (!deletePrefix.value.trim()) return;
+ deleteLoading.value = true;
+ deletePreview.value = null;
+ deleteReport.value = null;
+ deleteError.value = "";
+ try {
+ deletePreview.value = await api.consulDeletePrefixPreview(props.connectionId, deletePrefix.value.trim());
+ } catch (error) {
+ deleteError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ deleteLoading.value = false;
+ }
+}
+
+async function executeDeletePrefix() {
+ if (!deletePreview.value?.canExecute) return;
+ deleteExecuting.value = true;
+ deleteError.value = "";
+ try {
+ deleteReport.value = await api.consulDeletePrefixExecute(props.connectionId, {
+ prefix: deletePreview.value.prefix,
+ expected: deletePreview.value.candidates,
+ });
+ toast(t("consul.tools.prefixDeleted", { count: deleteReport.value.succeeded }), 3000);
+ browserRef.value?.refresh();
+ } catch (error) {
+ deleteError.value = error instanceof Error ? error.message : String(error);
+ deletePreview.value = null;
+ } finally {
+ deleteExecuting.value = false;
+ }
+}
+
+function operationVariant(operation: string): "default" | "secondary" | "destructive" | "outline" {
+ if (operation === "create" || operation === "succeeded") return "secondary";
+ if (operation === "conflict" || operation === "locked" || operation === "failed" || operation === "conflicted") return "destructive";
+ return "outline";
+}
+
+function reportBatchCount(items: Array<{ batch: number | null }>): number {
+ return items.reduce((count, item) => Math.max(count, item.batch ?? 0), 0);
+}
+
+function focusSearch(): boolean {
+ return browserRef.value?.focusSearch() ?? false;
+}
+
+function refresh(): boolean {
+ return browserRef.value?.refresh() ?? false;
+}
+
+watch(
+ () => `${props.connectionId}\u0000${currentScope().datacenter}\u0000${currentScope().partition}\u0000${currentScope().namespace}`,
+ () => {
+ void stopWatch();
+ watchIndex.value = null;
+ if (searchRunning.value && searchRequestId) void cancelSearch();
+ stopSearchProgress();
+ },
+);
+
+function stopBackgroundWork() {
+ void stopWatch();
+ if (searchRunning.value && searchRequestId) void cancelSearch();
+ stopSearchProgress();
+}
+
+onDeactivated(stopBackgroundWork);
+onBeforeUnmount(() => {
+ closePrefixSuggestions();
+ stopBackgroundWork();
+});
+
+defineExpose({ focusSearch, refresh });
+</script>
+
+<template>
+ <div class="flex h-full min-h-0 flex-col bg-background">
+ <input ref="fileInputRef" type="file" accept="application/json,.json" class="hidden" @change="onImportFile" />
+ <KvKeyBrowser
+ ref="browserRef"
+ class="min-h-0 flex-1"
+ :connection-id="props.connectionId"
+ :api="consulApi"
+ :labels="labels"
+ metadata-style="consul"
+ lazy-hierarchy
+ lazy-path-style="relative"
+ safe-write
+ allow-binary-edit
+ enable-node-actions
+ supports-flags
+ :read-only="readOnly"
+ :max-value-bytes="512 * 1024"
+ :on-watch-key="watchSelectedKey"
+ :on-delete-prefix="openDeletePrefix"
+ :watch-active-key="watchRunning && watchMode === 'key' ? watchPrefix : null"
+ :search-highlight="searchHighlight"
+ export-format="dbx-consul-kv-bundle"
+ export-file-extension=".dbx-consul.json"
+ export-fallback-name="consul-key"
+ >
+ <template #toolbar-trailing>
+ <Button variant="ghost" size="sm" class="h-9 gap-1.5 whitespace-nowrap" @click="openSearch"> <Search class="h-3.5 w-3.5" />{{ t("consul.tools.search") }} </Button>
+ <Button variant="ghost" size="sm" class="h-9 gap-1.5 whitespace-nowrap" :disabled="exporting" @click="exportOpen = true"> <Download class="h-3.5 w-3.5" />{{ t("consul.tools.exportPrefix") }} </Button>
+ <Button variant="ghost" size="sm" class="h-9 gap-1.5 whitespace-nowrap" :disabled="readOnly" @click="chooseImportFile"> <FileUp class="h-3.5 w-3.5" />{{ t("consul.tools.import") }} </Button>
+ <Button variant="ghost" size="sm" class="h-9 gap-1.5 whitespace-nowrap" @click="openMigration"> <ArrowRightLeft class="h-3.5 w-3.5" />{{ t("consul.tools.migrate") }} </Button>
+ </template>
+ </KvKeyBrowser>
+
+ <Dialog v-model:open="searchOpen">
+ <DialogContent class="flex max-h-[82vh] flex-col sm:max-w-4xl">
+ <DialogHeader
+ ><DialogTitle>{{ t("consul.tools.searchTitle") }}</DialogTitle></DialogHeader
+ >
+ <div class="grid shrink-0 gap-3 sm:grid-cols-[1fr_1fr_160px_auto]">
+ <Input v-model="searchQuery" :placeholder="t('consul.tools.searchQuery')" @keydown.enter="runSearch" />
+ <Input v-model="searchPrefix" :placeholder="t('consul.tools.prefixOptional')" @keydown.enter="runSearch" />
+ <Select v-model="searchScope">
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{{ t("consul.tools.searchAll") }}</SelectItem>
+ <SelectItem value="key">{{ t("consul.tools.searchKeys") }}</SelectItem>
+ <SelectItem value="value">{{ t("consul.tools.searchValues") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button :disabled="searchRunning || !searchQuery.trim()" @click="runSearch"> <Loader2 v-if="searchRunning" class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.tools.search") }} </Button>
+ </div>
+ <label class="flex items-center gap-2 text-xs text-muted-foreground"> <input v-model="searchCaseSensitive" type="checkbox" class="h-4 w-4" />{{ t("consul.tools.caseSensitive") }} </label>
+ <div v-if="searchRunning" class="flex items-center justify-between border-y py-2 text-xs text-muted-foreground">
+ <span>{{ t("consul.tools.scanned", { count: searchScanned }) }}</span>
+ <Button variant="ghost" size="sm" class="h-7 gap-1.5" @click="cancelSearch"><X class="h-3.5 w-3.5" />{{ t("common.cancel") }}</Button>
+ </div>
+ <div v-if="searchError" class="border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ searchError }}</div>
+ <div v-if="searchFiltered" class="border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">{{ t("consul.aclFiltered") }}</div>
+ <div v-if="searchLimited" class="text-xs text-amber-700 dark:text-amber-300">{{ t("consul.tools.searchLimited") }}</div>
+ <div class="min-h-0 flex-1 overflow-auto border">
+ <button v-for="result in searchResults" :key="`${result.key}:${result.modifyIndex}`" class="flex w-full items-center gap-3 border-b px-3 py-2 text-left hover:bg-muted/50" @click="openSearchResult(result)">
+ <span class="min-w-0 flex-1 truncate font-mono text-xs">{{ result.key }}</span>
+ <Badge v-if="result.matchesKey" variant="outline">{{ t("consul.ui.key") }}</Badge>
+ <Badge v-if="result.matchesValue" variant="outline">{{ t("consul.ui.value") }}</Badge>
+ </button>
+ <div v-if="!searchRunning && !searchResults.length" class="flex h-24 items-center justify-center text-sm text-muted-foreground">{{ t("consul.tools.noSearchResults") }}</div>
+ </div>
+ <div class="flex shrink-0 items-center justify-between gap-3 text-xs text-muted-foreground">
+ <span>{{ t("consul.tools.searchSummary", { matched: searchMatched, scanned: searchScanned }) }}</span>
+ <Button v-if="searchResults.length" size="sm" variant="outline" class="h-8 gap-1.5" :disabled="exportingSearchResults" @click="exportSearchResults">
+ <Loader2 v-if="exportingSearchResults" class="h-3.5 w-3.5 animate-spin" />
+ <Download v-else class="h-3.5 w-3.5" />
+ {{ t("consul.tools.exportSearchResults") }}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="exportOpen">
+ <DialogContent class="sm:max-w-lg">
+ <DialogHeader
+ ><DialogTitle>{{ t("consul.tools.exportPrefix") }}</DialogTitle></DialogHeader
+ >
+ <div class="grid gap-2">
+ <Label>{{ t("consul.tools.prefix") }}</Label>
+ <Popover :open="prefixSuggestionTarget === 'export' && prefixSuggestions.length > 0">
+ <PopoverAnchor as-child>
+ <Input
+ v-model="exportPrefix"
+ autocomplete="off"
+ :placeholder="t('consul.tools.emptyPrefixAll')"
+ @input="schedulePrefixSuggestions('export', ($event.target as HTMLInputElement).value)"
+ @focus="schedulePrefixSuggestions('export', exportPrefix)"
+ @blur="closePrefixSuggestions"
+ @keydown="onPrefixSuggestionKeydown('export', $event)"
+ />
+ </PopoverAnchor>
+ <PopoverContent align="start" side="bottom" :collision-padding="12" class="z-[60] max-h-[var(--reka-popover-content-available-height)] w-[var(--reka-popover-trigger-width)] gap-0 overflow-y-auto p-1" @open-auto-focus.prevent>
+ <button
+ v-for="(suggestion, index) in prefixSuggestions"
+ :key="suggestion.key"
+ type="button"
+ role="option"
+ :aria-selected="prefixSuggestionIndex === index"
+ class="flex w-full items-center px-3 py-1.5 text-left font-mono text-xs"
+ :class="prefixSuggestionIndex === index ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/70'"
+ @mouseenter="prefixSuggestionIndex = index"
+ @mousedown.prevent="acceptPrefixSuggestion('export', index)"
+ >
+ {{ suggestion.key }}
+ </button>
+ </PopoverContent>
+ </Popover>
+ <p class="text-xs text-muted-foreground">{{ t("consul.tools.exportLimitHint") }}</p>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="exportOpen = false">{{ t("common.cancel") }}</Button>
+ <Button :disabled="exporting" @click="exportPrefixBundle"><Loader2 v-if="exporting" class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.export") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="transferOpen">
+ <DialogContent class="flex max-h-[86vh] flex-col sm:max-w-5xl">
+ <DialogHeader
+ ><DialogTitle>{{ transferMode === "migration" ? t("consul.tools.migrateTitle") : t("consul.tools.importTitle") }}</DialogTitle></DialogHeader
+ >
+ <div class="grid shrink-0 gap-3 sm:grid-cols-3">
+ <div v-if="transferMode === 'migration'" class="grid gap-2">
+ <Label>{{ t("consul.tools.sourcePrefix") }}</Label>
+ <Popover :open="prefixSuggestionTarget === 'migration' && prefixSuggestions.length > 0">
+ <PopoverAnchor as-child>
+ <Input
+ v-model="transferSourcePrefix"
+ autocomplete="off"
+ :placeholder="t('consul.tools.emptyPrefixAll')"
+ @input="schedulePrefixSuggestions('migration', ($event.target as HTMLInputElement).value)"
+ @focus="schedulePrefixSuggestions('migration', transferSourcePrefix)"
+ @blur="closePrefixSuggestions"
+ @keydown="onPrefixSuggestionKeydown('migration', $event)"
+ />
+ </PopoverAnchor>
+ <PopoverContent align="start" side="bottom" :collision-padding="12" class="z-[60] max-h-[var(--reka-popover-content-available-height)] w-[var(--reka-popover-trigger-width)] gap-0 overflow-y-auto p-1" @open-auto-focus.prevent>
+ <button
+ v-for="(suggestion, index) in prefixSuggestions"
+ :key="suggestion.key"
+ type="button"
+ role="option"
+ :aria-selected="prefixSuggestionIndex === index"
+ class="flex w-full items-center px-3 py-1.5 text-left font-mono text-xs"
+ :class="prefixSuggestionIndex === index ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/70'"
+ @mouseenter="prefixSuggestionIndex = index"
+ @mousedown.prevent="acceptPrefixSuggestion('migration', index)"
+ >
+ {{ suggestion.key }}
+ </button>
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div class="grid gap-2">
+ <Label>{{ t("consul.tools.targetConnection") }}</Label>
+ <Select v-model="transferTargetId" @update:model-value="resetTransferPreview">
+ <SelectTrigger><SelectValue :placeholder="t('consul.tools.selectTarget')" /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-for="connection in transferTargetConnections" :key="connection.id" :value="connection.id">{{ connection.name }}</SelectItem></SelectContent
+ >
+ </Select>
+ </div>
+ <div class="grid gap-2">
+ <Label>{{ t("consul.tools.conflictPolicy") }}</Label>
+ <Select v-model="transferPolicy" @update:model-value="resetTransferPreview">
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="abort">{{ t("consul.tools.policyAbort") }}</SelectItem>
+ <SelectItem value="skip">{{ t("consul.tools.policySkip") }}</SelectItem>
+ <SelectItem value="cas">{{ t("consul.tools.policyCas") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ <div v-if="transferBundle" class="text-xs text-muted-foreground">
+ {{ t("consul.tools.bundleSummary", { count: transferBundle.entries.length, dc: transferBundle.source.datacenter || "-", ns: transferBundle.source.namespace || "-", partition: transferBundle.source.partition || "-" }) }}
+ </div>
+ <div v-if="transferMode === 'migration'" class="border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">{{ t("consul.ui.clientSideMigration") }}</div>
+ <div v-if="transferTargetReadOnly" class="border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">{{ t("consul.tools.targetReadOnly") }}</div>
+ <div v-if="transferError" class="border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ transferError }}</div>
+ <div v-if="transferPreview" class="flex flex-wrap gap-2 text-xs">
+ <Badge variant="secondary">{{ t("consul.tools.creates", { count: transferPreview.creates }) }}</Badge>
+ <Badge variant="secondary">{{ t("consul.tools.updates", { count: transferPreview.updates }) }}</Badge>
+ <Badge variant="outline">{{ t("consul.tools.unchanged", { count: transferPreview.unchanged }) }}</Badge>
+ <Badge variant="outline">{{ t("consul.tools.skipped", { count: transferPreview.skipped }) }}</Badge>
+ <Badge :variant="transferPreview.conflicts ? 'destructive' : 'outline'">{{ t("consul.tools.conflicts", { count: transferPreview.conflicts }) }}</Badge>
+ </div>
+ <div v-if="transferReport" class="flex flex-wrap gap-2 text-xs">
+ <Badge :variant="transferReport.atomic ? 'default' : 'destructive'">{{ transferReport.atomic ? t("consul.ui.atomicTransaction") : t("consul.ui.nonAtomicBatches", { count: reportBatchCount(transferReport.items) }) }}</Badge>
+ <Badge variant="outline">{{ t("consul.ui.operationTotals", { succeeded: transferReport.succeeded, conflicted: transferReport.conflicted, skipped: transferReport.skipped, failed: transferReport.failed }) }}</Badge>
+ </div>
+ <div class="min-h-0 flex-1 overflow-auto border">
+ <div v-for="row in transferReport?.items || transferPreview?.rows || []" :key="row.key" class="grid grid-cols-[minmax(0,1fr)_120px] gap-3 border-b px-3 py-2 text-xs">
+ <div class="min-w-0">
+ <div class="truncate font-mono">{{ row.key }}</div>
+ <div v-if="'batch' in row && row.batch" class="mt-1 text-muted-foreground">{{ t("consul.ui.batchOperation", { batch: row.batch, op: row.opIndex ?? "-" }) }}</div>
+ <div v-if="('message' in row && row.message) || ('reason' in row && row.reason)" class="mt-1 text-muted-foreground">{{ "message" in row ? row.message : "reason" in row ? row.reason : "" }}</div>
+ </div>
+ <Badge :variant="operationVariant('outcome' in row ? row.outcome : row.operation)" class="justify-center">{{ t(`consul.tools.operation.${"outcome" in row ? row.outcome : row.operation}`) }}</Badge>
+ </div>
+ <div v-if="transferLoading" class="flex h-24 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.tools.loadingPreview") }}</div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="transferOpen = false">{{ t("common.close") }}</Button>
+ <Button v-if="transferMode === 'migration' && !transferPreview" variant="outline" :disabled="transferLoading || !transferTargetId" @click="loadMigrationPreview">{{ t("consul.tools.loadPreview") }}</Button>
+ <Button v-else-if="transferMode === 'import' && !transferPreview" variant="outline" :disabled="transferLoading || !transferTargetId" @click="previewTransfer">{{ t("consul.tools.loadPreview") }}</Button>
+ <Button v-if="transferPreview && !transferReport" :disabled="transferApplying || transferTargetReadOnly || !transferPreview.canApply" @click="executeTransfer"><Loader2 v-if="transferApplying" class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.tools.apply") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="deleteOpen">
+ <DialogContent class="flex max-h-[82vh] flex-col sm:max-w-3xl">
+ <DialogHeader
+ ><DialogTitle>{{ t("consul.tools.deletePrefixTitle") }}</DialogTitle></DialogHeader
+ >
+ <div class="flex shrink-0 gap-2">
+ <div class="min-w-0 flex-1">
+ <Popover :open="prefixSuggestionTarget === 'delete' && prefixSuggestions.length > 0">
+ <PopoverAnchor as-child>
+ <Input
+ v-model="deletePrefix"
+ autocomplete="off"
+ :placeholder="t('consul.tools.deletePrefixPlaceholder')"
+ :disabled="Boolean(deletePreview)"
+ @input="schedulePrefixSuggestions('delete', ($event.target as HTMLInputElement).value)"
+ @focus="schedulePrefixSuggestions('delete', deletePrefix)"
+ @blur="closePrefixSuggestions"
+ @keydown="onPrefixSuggestionKeydown('delete', $event)"
+ />
+ </PopoverAnchor>
+ <PopoverContent align="start" side="bottom" :collision-padding="12" class="z-[60] max-h-[var(--reka-popover-content-available-height)] w-[var(--reka-popover-trigger-width)] gap-0 overflow-y-auto p-1" @open-auto-focus.prevent>
+ <button
+ v-for="(suggestion, index) in prefixSuggestions"
+ :key="suggestion.key"
+ type="button"
+ role="option"
+ :aria-selected="prefixSuggestionIndex === index"
+ class="flex w-full items-center px-3 py-1.5 text-left font-mono text-xs"
+ :class="prefixSuggestionIndex === index ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/70'"
+ @mouseenter="prefixSuggestionIndex = index"
+ @mousedown.prevent="acceptPrefixSuggestion('delete', index)"
+ >
+ {{ suggestion.key }}
+ </button>
+ </PopoverContent>
+ </Popover>
+ </div>
+ <Button variant="outline" :disabled="deleteLoading || !deletePrefix.trim() || Boolean(deletePreview)" @click="previewDeletePrefix"><Loader2 v-if="deleteLoading" class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.tools.preview") }}</Button>
+ </div>
+ <div class="border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">{{ t("consul.tools.deletePrefixWarning") }}</div>
+ <div v-if="deleteError" class="border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ deleteError }}</div>
+ <div v-if="deletePreview" class="flex flex-wrap gap-2 text-xs">
+ <Badge variant="secondary">{{ t("consul.tools.candidates", { count: deletePreview.candidates.length }) }}</Badge>
+ <Badge :variant="deletePreview.locked ? 'destructive' : 'outline'">{{ t("consul.tools.lockedCount", { count: deletePreview.locked }) }}</Badge>
+ <Badge :variant="deletePreview.filteredByAcls ? 'destructive' : 'outline'">ACL {{ deletePreview.filteredByAcls ? t("consul.tools.filtered") : t("consul.tools.complete") }}</Badge>
+ </div>
+ <div v-if="deleteReport" class="flex flex-wrap gap-2 text-xs">
+ <Badge :variant="deleteReport.atomic ? 'default' : 'destructive'">{{ deleteReport.atomic ? t("consul.ui.atomicTransaction") : t("consul.ui.nonAtomicBatches", { count: reportBatchCount(deleteReport.items) }) }}</Badge>
+ <Badge variant="outline">{{ t("consul.ui.deleteOperationTotals", { succeeded: deleteReport.succeeded, conflicted: deleteReport.conflicted, failed: deleteReport.failed }) }}</Badge>
+ </div>
+ <div class="min-h-0 flex-1 overflow-auto border">
+ <div v-for="row in deleteReport?.items || deletePreview?.candidates || []" :key="row.key" class="grid grid-cols-[minmax(0,1fr)_140px] gap-3 border-b px-3 py-2 text-xs" :class="'session' in row && row.session ? 'bg-destructive/5' : ''">
+ <span class="min-w-0">
+ <span class="flex min-w-0 items-center gap-2"
+ ><span class="truncate font-mono">{{ row.key }}</span
+ ><Badge v-if="'session' in row && row.session" variant="destructive" class="shrink-0">{{ t("consul.ui.locked") }}</Badge></span
+ >
+ <span v-if="'session' in row && row.session" class="mt-1 block truncate font-mono text-muted-foreground">{{ t("consul.ui.sessionValue", { id: row.session }) }}</span>
+ <span v-if="'batch' in row && row.batch" class="block truncate text-muted-foreground">{{ t("consul.ui.batchOperation", { batch: row.batch, op: row.opIndex ?? "-" }) }}</span>
+ <span v-if="'message' in row && row.message" class="mt-1 block truncate text-destructive" :title="row.message">{{ row.message }}</span>
+ </span>
+ <Badge v-if="'outcome' in row" :variant="operationVariant(row.outcome)" class="justify-center">{{ t(`consul.tools.operation.${row.outcome}`) }}</Badge>
+ <span v-else class="truncate text-right font-mono text-muted-foreground">{{ row.modifyIndex }}</span>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="deleteOpen = false">{{ t("common.close") }}</Button>
+ <Button v-if="deletePreview && !deleteReport" variant="destructive" :disabled="deleteExecuting || !deletePreview.canExecute" @click="executeDeletePrefix"><Loader2 v-if="deleteExecuting" class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.tools.confirmDeletePrefix") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulListPagination.vue b/apps/desktop/src/components/consul/ConsulListPagination.vue
new file mode 100644
index 0000000000..5e7d279b97
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulListPagination.vue
@@ -0,0 +1,32 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { ChevronLeft, ChevronRight } from "@lucide/vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { clampConsulPage, consulPageCount } from "@/lib/consul/pagination";
+
+const props = withDefaults(defineProps<{ total: number; page: number; pageSize: number; compact?: boolean }>(), {
+ compact: false,
+});
+const emit = defineEmits<{ "update:page": [page: number] }>();
+const { t } = useI18n();
+const pages = computed(() => consulPageCount(props.total, props.pageSize));
+const current = computed(() => clampConsulPage(props.page, props.total, props.pageSize));
+const status = computed(() => t("consul.ui.pageStatus", { page: current.value, pages: pages.value, total: props.total }));
+
+function move(delta: number) {
+ emit("update:page", clampConsulPage(current.value + delta, props.total, props.pageSize));
+}
+</script>
+
+<template>
+ <div v-if="pages > 1" class="flex shrink-0 items-center justify-center gap-1 text-xs text-muted-foreground" :title="status">
+ <Button size="icon" variant="ghost" class="h-7 w-7" :disabled="current <= 1" :title="t('consul.ui.previousPage')" @click="move(-1)">
+ <ChevronLeft class="h-3.5 w-3.5" />
+ </Button>
+ <span class="min-w-12 whitespace-nowrap text-center tabular-nums">{{ compact ? `${current} / ${pages}` : status }}</span>
+ <Button size="icon" variant="ghost" class="h-7 w-7" :disabled="current >= pages" :title="t('consul.ui.nextPage')" @click="move(1)">
+ <ChevronRight class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulMesh.vue b/apps/desktop/src/components/consul/ConsulMesh.vue
new file mode 100644
index 0000000000..cebfae8e19
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulMesh.vue
@@ -0,0 +1,403 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from "vue";
+import { Clipboard, Eye, EyeOff, Loader2, Plus, RefreshCcw, Trash2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import PasswordInput from "@/components/ui/PasswordInput.vue";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import NacosConfigDiffDialog from "@/components/nacos/NacosConfigDiffDialog.vue";
+import * as api from "@/lib/backend/api";
+import { useConnectionStore } from "@/stores/connectionStore";
+import type { ConsulCapabilities, ConsulConfigEntry, ConsulDiscoveryChain, ConsulExportedService, ConsulIntention, ConsulPeering } from "@/types/consul";
+import { useI18n } from "vue-i18n";
+
+type MeshTab = "config" | "intentions" | "discovery" | "peering" | "exported";
+const props = defineProps<{ connectionId: string; capabilities: ConsulCapabilities | null }>();
+const store = useConnectionStore();
+const readOnly = computed(() => Boolean(store.getConfig(props.connectionId)?.read_only));
+const { t } = useI18n();
+function capabilityLabel(value?: string) {
+ if (value === "supported") return t("consul.ui.capabilitySupported");
+ if (value === "unsupported") return t("consul.ui.capabilityUnsupported");
+ if (value === "disabled") return t("consul.ui.capabilityDisabled");
+ if (value === "forbidden") return t("consul.ui.capabilityForbidden");
+ return t("consul.ui.capabilityUnknown");
+}
+const active = ref<MeshTab>("config");
+const loading = ref(false);
+const error = ref("");
+const configKind = ref("service-defaults");
+const configs = ref<ConsulConfigEntry[]>([]);
+const intentions = ref<ConsulIntention[]>([]);
+const peerings = ref<ConsulPeering[]>([]);
+const exported = ref<ConsulExportedService[]>([]);
+const discoveryService = ref("");
+const chain = ref<ConsulDiscoveryChain | null>(null);
+const editorOpen = ref(false);
+const editorMode = ref<"config" | "intention" | "exported">("config");
+const editorJson = ref("{}");
+const editingConfig = ref<ConsulConfigEntry | null>(null);
+const peeringName = ref("");
+const peeringToken = ref("");
+const tokenOnce = ref("");
+const editingExported = ref<ConsulConfigEntry | null>(null);
+const tokenRevealed = ref(false);
+const editorOriginalJson = ref("");
+const savePreviewOpen = ref(false);
+const pendingEditorRaw = ref<Record<string, unknown> | null>(null);
+const intentionSource = ref("");
+const intentionDestination = ref("");
+const intentionCheckResult = ref<boolean | null>(null);
+const intentionMatches = ref<ConsulIntention[]>([]);
+let loadSequence = 0;
+const capability = computed(() =>
+ active.value === "config" ? props.capabilities?.configEntries : active.value === "intentions" ? props.capabilities?.intentions : active.value === "peering" ? props.capabilities?.peering : active.value === "exported" ? props.capabilities?.exportedServices : "supported",
+);
+const canWrite = computed(() => !readOnly.value && capability.value === "supported");
+const chainRows = computed(() => {
+ if (!chain.value?.Nodes) return [];
+ const nodes = chain.value.Nodes;
+ const rows: Array<{ id: string; depth: number; type: string; next: string[] }> = [];
+ const seen = new Set<string>();
+ const queue: Array<{ id: string; depth: number }> = [{ id: chain.value.StartNode || Object.keys(nodes)[0] || "", depth: 0 }];
+ while (queue.length) {
+ const current = queue.shift()!;
+ if (!current.id || seen.has(current.id)) continue;
+ seen.add(current.id);
+ const value = nodes[current.id];
+ const next = collectNextNodes(value);
+ rows.push({ id: current.id, depth: current.depth, type: nodeType(value), next });
+ for (const id of next) if (nodes[id] && !seen.has(id)) queue.push({ id, depth: current.depth + 1 });
+ }
+ for (const id of Object.keys(nodes)) if (!seen.has(id)) rows.push({ id, depth: 0, type: nodeType(nodes[id]), next: collectNextNodes(nodes[id]) });
+ return rows;
+});
+function nodeType(value: unknown) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "node";
+ return String((value as Record<string, unknown>).Type || (value as Record<string, unknown>).type || "node");
+}
+function collectNextNodes(value: unknown): string[] {
+ const found = new Set<string>();
+ function visit(item: unknown) {
+ if (Array.isArray(item)) {
+ item.forEach(visit);
+ return;
+ }
+ if (!item || typeof item !== "object") return;
+ for (const [key, child] of Object.entries(item as Record<string, unknown>)) {
+ if (key.toLowerCase() === "nextnode" && typeof child === "string" && child) found.add(child);
+ else visit(child);
+ }
+ }
+ visit(value);
+ return [...found];
+}
+async function load() {
+ const sequence = ++loadSequence;
+ const connectionId = props.connectionId;
+ const tab = active.value;
+ const kind = configKind.value;
+ loading.value = true;
+ error.value = "";
+ try {
+ if (tab === "config") {
+ const value = await api.consulMeshConfigList(connectionId, kind);
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) configs.value = value;
+ } else if (tab === "intentions") {
+ const value = await api.consulMeshIntentionsList(connectionId);
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) intentions.value = value;
+ } else if (tab === "peering") {
+ const value = await api.consulMeshPeeringList(connectionId);
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) peerings.value = value;
+ } else if (tab === "exported") {
+ const value = await api.consulMeshExportedServicesList(connectionId);
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) exported.value = value;
+ }
+ } catch (cause) {
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (sequence === loadSequence && connectionId === props.connectionId && tab === active.value) loading.value = false;
+ }
+}
+function openConfig(item?: ConsulConfigEntry) {
+ editorMode.value = "config";
+ editingConfig.value = item || null;
+ editorOriginalJson.value = item ? JSON.stringify(item.raw, null, 2) : "";
+ editorJson.value = JSON.stringify(item?.raw || { Kind: configKind.value, Name: "" }, null, 2);
+ editorOpen.value = true;
+}
+async function openIntention(item?: ConsulIntention) {
+ let value = item;
+ if (item && !item.ID && item.SourceName && item.DestinationName) value = await api.consulMeshIntentionGetExact(props.connectionId, { source: item.SourceName, destination: item.DestinationName });
+ editorMode.value = "intention";
+ editorOriginalJson.value = value ? JSON.stringify(value, null, 2) : "";
+ editorJson.value = JSON.stringify(value || { SourceName: "", DestinationName: "", Action: "allow", Permissions: [] }, null, 2);
+ editorOpen.value = true;
+}
+async function openExported() {
+ error.value = "";
+ try {
+ const entries = await api.consulMeshConfigList(props.connectionId, "exported-services");
+ editingExported.value = entries[0] || null;
+ const raw = editingExported.value?.raw || { Kind: "exported-services", Name: "default", Services: [] };
+ editorMode.value = "exported";
+ editorOriginalJson.value = editingExported.value ? JSON.stringify(raw, null, 2) : "";
+ editorJson.value = JSON.stringify(raw, null, 2);
+ editorOpen.value = true;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function save() {
+ try {
+ pendingEditorRaw.value = JSON.parse(editorJson.value) as Record<string, unknown>;
+ savePreviewOpen.value = true;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function confirmSave() {
+ const raw = pendingEditorRaw.value;
+ if (!raw) return;
+ try {
+ if (editorMode.value === "config") {
+ const kind = String(raw.Kind || configKind.value),
+ name = String(raw.Name || "");
+ await api.consulMeshConfigApply(props.connectionId, { kind, name, expectedModifyIndex: editingConfig.value?.modifyIndex || 0, raw });
+ } else if (editorMode.value === "intention") await api.consulMeshIntentionUpsert(props.connectionId, raw as ConsulIntention);
+ else await api.consulMeshExportedServicesApply(props.connectionId, String(raw.Name || "default"), editingExported.value?.modifyIndex || 0, raw);
+ savePreviewOpen.value = false;
+ editorOpen.value = false;
+ pendingEditorRaw.value = null;
+ editingExported.value = null;
+ await load();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function removeConfig(item: ConsulConfigEntry) {
+ if (!confirm(t("consul.ui.deleteConfig", { kind: item.kind, name: item.name }))) return;
+ await api.consulMeshConfigDelete(props.connectionId, item.kind, item.name, item.modifyIndex);
+ await load();
+}
+async function removeIntention(item: ConsulIntention) {
+ if (item.ID) {
+ if (!confirm(t("consul.ui.deleteIntention", { id: item.ID }))) return;
+ await api.consulMeshIntentionDelete(props.connectionId, item.ID);
+ } else if (item.SourceName && item.DestinationName) {
+ if (!confirm(t("consul.ui.deleteIntentionExact", { source: item.SourceName, destination: item.DestinationName }))) return;
+ await api.consulMeshIntentionDeleteExact(props.connectionId, { source: item.SourceName, destination: item.DestinationName });
+ } else return;
+ await load();
+}
+function permissionsSummary(item: ConsulIntention) {
+ return item.Permissions?.length ? t("consul.ui.permissions", { count: item.Permissions.length }) : t("consul.ui.actionRule");
+}
+function intentionActionLabel(action?: string) {
+ return action === "allow" ? t("consul.ui.allowed") : action === "deny" ? t("consul.ui.denied") : action || t("consul.ui.unknown");
+}
+function peeringStateLabel(state?: string) {
+ const value = String(state || "").toLowerCase();
+ if (value === "pending") return t("consul.ui.peeringPending");
+ if (value === "establishing") return t("consul.ui.peeringEstablishing");
+ if (value === "active") return t("consul.ui.peeringActive");
+ if (value === "failing") return t("consul.ui.peeringFailing");
+ if (value === "deleting") return t("consul.ui.peeringDeleting");
+ if (value === "terminated") return t("consul.ui.peeringTerminated");
+ return state || t("consul.ui.unknown");
+}
+async function checkIntention() {
+ if (!intentionSource.value.trim() || !intentionDestination.value.trim()) return;
+ try {
+ const result = await api.consulMeshIntentionCheck(props.connectionId, { source: intentionSource.value.trim(), destination: intentionDestination.value.trim() });
+ intentionCheckResult.value = result.Allowed;
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function matchIntentions(by: "source" | "destination") {
+ const name = (by === "source" ? intentionSource.value : intentionDestination.value).trim();
+ if (!name) return;
+ try {
+ intentionMatches.value = await api.consulMeshIntentionMatch(props.connectionId, { by, name });
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function loadChain() {
+ loading.value = true;
+ error.value = "";
+ try {
+ chain.value = await api.consulMeshDiscoveryChain(props.connectionId, discoveryService.value);
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ loading.value = false;
+ }
+}
+function clearToken() {
+ tokenOnce.value = "";
+ tokenRevealed.value = false;
+}
+async function generateToken() {
+ try {
+ const result = await api.consulMeshPeeringGenerateToken(props.connectionId, { PeerName: peeringName.value });
+ tokenOnce.value = result.PeeringToken;
+ tokenRevealed.value = false;
+ peeringName.value = "";
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function establishPeering() {
+ try {
+ await api.consulMeshPeeringEstablish(props.connectionId, { PeerName: peeringName.value, PeeringToken: peeringToken.value });
+ peeringToken.value = "";
+ peeringName.value = "";
+ await load();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function copyToken() {
+ await navigator.clipboard.writeText(tokenOnce.value);
+ clearToken();
+}
+async function removePeering(name: string) {
+ if (!confirm(t("consul.ui.deletePeering", { name }))) return;
+ await api.consulMeshPeeringDelete(props.connectionId, name);
+ await load();
+}
+watch([active, () => props.connectionId], () => {
+ clearToken();
+ void load();
+});
+onMounted(() => void load());
+onDeactivated(clearToken);
+onBeforeUnmount(() => {
+ loadSequence += 1;
+ clearToken();
+});
+defineExpose({
+ refresh: () => {
+ void load();
+ return true;
+ },
+});
+</script>
+<template>
+ <Tabs v-model="active" class="flex h-full min-h-0 flex-col">
+ <div class="flex h-11 items-center justify-between border-b px-3">
+ <TabsList class="h-8 p-0.5"
+ ><TabsTrigger value="config" class="h-7 px-2 text-xs">{{ t("consul.ui.configEntries") }}</TabsTrigger
+ ><TabsTrigger value="intentions" class="h-7 px-2 text-xs">{{ t("consul.ui.intentions") }}</TabsTrigger
+ ><TabsTrigger value="discovery" class="h-7 px-2 text-xs">{{ t("consul.ui.discoveryChain") }}</TabsTrigger
+ ><TabsTrigger value="peering" class="h-7 px-2 text-xs">{{ t("consul.ui.peering") }}</TabsTrigger
+ ><TabsTrigger value="exported" class="h-7 px-2 text-xs">{{ t("consul.ui.exportedServices") }}</TabsTrigger></TabsList
+ ><Button variant="ghost" size="icon" class="h-7 w-7" :title="t('consul.ui.refresh')" @click="load"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div v-if="capability !== 'supported'" class="m-4 border p-3 text-sm text-muted-foreground">{{ t("consul.ui.capability", { status: capabilityLabel(capability) }) }}</div>
+ <div v-else-if="error" class="m-4 border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{{ error }}</div>
+ <div v-if="loading" class="flex h-24 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ <TabsContent value="config" class="m-0 min-h-0 flex-1 overflow-auto p-4"
+ ><div class="mb-3 flex gap-2">
+ <Input v-model="configKind" class="max-w-xs" :placeholder="t('consul.ui.configEntryKind')" /><Button variant="outline" size="sm" @click="load">{{ t("consul.ui.loadKind") }}</Button
+ ><Button v-if="canWrite" size="sm" class="gap-1" @click="openConfig()"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.newJson") }}</Button>
+ </div>
+ <div class="divide-y border">
+ <div v-for="item in configs" :key="`${item.kind}/${item.name}`" class="flex min-h-12 items-center gap-3 px-3 py-2">
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{{ item.name }}</div>
+ <div class="text-xs text-muted-foreground">{{ item.kind }} · {{ t("consul.ui.modifyIndex", { index: item.modifyIndex }) }}</div>
+ </div>
+ <Button variant="outline" size="sm" @click="openConfig(item)">{{ t("consul.ui.rawJson") }}</Button
+ ><Button v-if="canWrite" variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="removeConfig(item)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div></div
+ ></TabsContent>
+ <TabsContent value="intentions" class="m-0 min-h-0 flex-1 overflow-auto p-4">
+ <div class="mb-3 flex flex-wrap items-center gap-2">
+ <Button v-if="canWrite" size="sm" class="gap-1" @click="openIntention()"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.newIntention") }}</Button>
+ <Input v-model="intentionSource" class="max-w-48" :placeholder="t('consul.ui.sourceService')" />
+ <Input v-model="intentionDestination" class="max-w-48" :placeholder="t('consul.ui.destinationService')" />
+ <Button variant="outline" size="sm" @click="checkIntention">{{ t("consul.ui.check") }}</Button>
+ <Button variant="ghost" size="sm" @click="matchIntentions('source')">{{ t("consul.ui.matchSource") }}</Button>
+ <Button variant="ghost" size="sm" @click="matchIntentions('destination')">{{ t("consul.ui.matchDestination") }}</Button>
+ <span v-if="intentionCheckResult !== null" class="text-xs font-medium" :class="intentionCheckResult ? 'text-emerald-600' : 'text-destructive'">{{ intentionCheckResult ? t("consul.ui.allowed") : t("consul.ui.denied") }}</span>
+ </div>
+ <div v-if="intentionMatches.length" class="mb-3 border bg-muted/20 p-2 text-xs">{{ t("consul.ui.matchedIntentions", { count: intentionMatches.length }) }}</div>
+ <div class="divide-y border">
+ <div v-for="item in intentionMatches.length ? intentionMatches : intentions" :key="item.ID || `${item.SourceName}:${item.DestinationName}`" class="flex min-h-12 items-center gap-3 px-3 py-2">
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{{ item.SourceName }} → {{ item.DestinationName }}</div>
+ <div class="text-xs text-muted-foreground">
+ {{ intentionActionLabel(item.Action) }} · {{ permissionsSummary(item) }} · {{ item.SourcePartition || t("consul.ui.default") }}/{{ item.SourceNamespace || t("consul.ui.default") }} → {{ item.DestinationPartition || t("consul.ui.default") }}/{{
+ item.DestinationNamespace || t("consul.ui.default")
+ }}
+ </div>
+ </div>
+ <Button variant="outline" size="sm" @click="openIntention(item)">{{ t("consul.ui.details") }}</Button
+ ><Button v-if="canWrite" variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="removeIntention(item)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+ </TabsContent>
+ <TabsContent value="discovery" class="m-0 min-h-0 flex-1 overflow-auto p-4">
+ <div class="flex max-w-xl gap-2">
+ <Input v-model="discoveryService" :placeholder="t('consul.ui.serviceName')" @keyup.enter="loadChain" /><Button @click="loadChain">{{ t("consul.ui.compile") }}</Button>
+ </div>
+ <div v-if="chain" class="mt-4 space-y-3">
+ <div class="border bg-muted/20 px-3 py-2 text-xs">{{ chain.ServiceName }} · {{ chain.Protocol || t("consul.ui.defaultProtocol") }} · {{ chain.Datacenter || t("consul.ui.configuredDatacenter") }}</div>
+ <div class="divide-y border">
+ <div v-for="row in chainRows" :key="row.id" class="grid min-h-12 grid-cols-[minmax(0,1fr)_8rem_minmax(0,1fr)] items-center gap-3 px-3 py-2 text-xs" :style="{ paddingLeft: `${12 + row.depth * 20}px` }">
+ <div class="min-w-0 truncate font-mono">
+ <span v-if="row.id === chain.StartNode" class="mr-1 text-emerald-600">{{ t("consul.ui.start") }}</span
+ >{{ row.id }}
+ </div>
+ <Badge variant="outline" class="w-fit">{{ row.type }}</Badge>
+ <div class="truncate text-muted-foreground">{{ row.next.length ? t("consul.ui.next", { nodes: row.next.join(", ") }) : t("consul.ui.terminalTarget") }}</div>
+ </div>
+ </div>
+ <details v-if="chain.Targets && Object.keys(chain.Targets).length" class="border">
+ <summary class="cursor-pointer px-3 py-2 text-xs font-medium">{{ t("consul.ui.upstreamTargets", { count: Object.keys(chain.Targets).length }) }}</summary>
+ <pre class="max-h-64 overflow-auto border-t bg-muted/20 p-3 text-xs">{{ JSON.stringify(chain.Targets, null, 2) }}</pre>
+ </details>
+ </div>
+ </TabsContent>
+ <TabsContent value="peering" class="m-0 min-h-0 flex-1 overflow-auto p-4"
+ ><div v-if="canWrite" class="mb-3 grid max-w-2xl grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_auto_auto] gap-2">
+ <Input v-model="peeringName" :placeholder="t('consul.ui.peerName')" /><PasswordInput v-model="peeringToken" :placeholder="t('consul.ui.peeringToken')" /><Button :disabled="!peeringName" variant="outline" @click="generateToken">{{ t("consul.ui.generateToken") }}</Button
+ ><Button :disabled="!peeringName || !peeringToken" @click="establishPeering">{{ t("consul.ui.establish") }}</Button>
+ </div>
+ <div v-if="tokenOnce" class="mb-3 flex items-center gap-2 border border-amber-300 bg-amber-50 p-3 text-sm dark:bg-amber-950/30">
+ <span class="min-w-0 flex-1 truncate font-mono">{{ tokenRevealed ? tokenOnce : "****************" }}</span
+ ><Button variant="ghost" size="icon" class="h-7 w-7" :title="tokenRevealed ? t('consul.ui.hide') : t('consul.ui.reveal')" @click="tokenRevealed = !tokenRevealed"><EyeOff v-if="tokenRevealed" class="h-3.5 w-3.5" /><Eye v-else class="h-3.5 w-3.5" /></Button
+ ><Button size="sm" class="gap-1" @click="copyToken"><Clipboard class="h-3.5 w-3.5" />{{ t("consul.ui.copyOnce") }}</Button
+ ><Button variant="ghost" size="sm" @click="clearToken">{{ t("consul.ui.hide") }}</Button>
+ </div>
+ <div class="divide-y border">
+ <div v-for="item in peerings" :key="item.Name" class="flex min-h-12 items-center gap-3 px-3 py-2">
+ <div class="flex-1">
+ <div class="text-sm font-medium">{{ item.Name }}</div>
+ <div class="text-xs text-muted-foreground">{{ peeringStateLabel(item.State) }} · {{ item.Partition || t("consul.ui.default") }}</div>
+ </div>
+ <Button v-if="canWrite" variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="removePeering(String(item.Name))"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div></div
+ ></TabsContent>
+ <TabsContent value="exported" class="m-0 min-h-0 flex-1 overflow-auto p-4"
+ ><Button v-if="canWrite" size="sm" class="mb-3 gap-1" @click="openExported"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.editExportedServices") }}</Button>
+ <pre class="max-h-[60vh] overflow-auto border bg-muted/20 p-3 text-xs">{{ JSON.stringify(exported, null, 2) }}</pre>
+ </TabsContent>
+ </Tabs>
+ <Dialog v-model:open="editorOpen"
+ ><DialogContent class="max-w-3xl"
+ ><DialogHeader
+ ><DialogTitle>{{ editorMode === "config" ? t("consul.ui.serviceMeshConfigEntry") : editorMode === "intention" ? t("consul.ui.intentions") : t("consul.ui.exportedServices") }}</DialogTitle></DialogHeader
+ ><textarea v-model="editorJson" class="h-96 w-full resize-none rounded-md border bg-background p-3 font-mono text-xs outline-none" spellcheck="false" /><DialogFooter
+ ><Button variant="outline" @click="editorOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button v-if="canWrite" @click="save">{{ t("consul.ui.applyWithCas") }}</Button></DialogFooter
+ ></DialogContent
+ ></Dialog
+ >
+ <NacosConfigDiffDialog v-model:open="savePreviewOpen" :title="t('consul.ui.reviewMeshChanges')" :before="editorOriginalJson" :after="editorJson" :confirm-label="t('consul.ui.apply')" @confirm="confirmSave" />
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulOperator.vue b/apps/desktop/src/components/consul/ConsulOperator.vue
new file mode 100644
index 0000000000..67795f19ef
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulOperator.vue
@@ -0,0 +1,165 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { Download, RefreshCcw } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import * as api from "@/lib/backend/api";
+import type { ConsulCapabilities, ConsulOperatorDocument, ConsulOperatorReadKind } from "@/types/consul";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{ connectionId: string; capabilities: ConsulCapabilities | null }>();
+const { t } = useI18n();
+const connectionStore = useConnectionStore();
+const kinds: ConsulOperatorReadKind[] = ["autopilot_configuration", "autopilot_health", "autopilot_state", "raft_configuration", "usage", "license", "audit"];
+const documents = ref<Record<string, ConsulOperatorDocument>>({});
+const failures = ref<Record<string, string>>({});
+const loading = ref(false);
+const writeError = ref("");
+const snapshot = ref({ data: "", datacenter: "", confirmation: "" });
+const autopilot = ref({ cleanupDeadServers: true, confirmation: "" });
+const raft = ref({ serverId: "", address: "", confirmation: "" });
+const keyring = ref({ operation: "install" as "install" | "use" | "remove", key: "", confirmation: "" });
+const license = ref({ value: "", confirmation: "" });
+const settings = computed(() => {
+ const external = connectionStore.getConfig(props.connectionId)?.external_config;
+ return external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+});
+const readOnly = computed(() => Boolean(connectionStore.getConfig(props.connectionId)?.read_only));
+const autopilotWriteVisible = computed(() => settings.value.consulOperatorAutopilotWriteEnabled && props.capabilities?.operatorAutopilot === "supported");
+const raftWriteVisible = computed(() => settings.value.consulOperatorRaftWriteEnabled && props.capabilities?.operatorRaft === "supported");
+const keyringWriteVisible = computed(() => settings.value.consulOperatorKeyringWriteEnabled && props.capabilities?.operatorKeyring === "supported");
+const licenseWriteVisible = computed(() => settings.value.consulOperatorLicenseWriteEnabled && props.capabilities?.operatorLicense === "supported");
+
+async function refresh() {
+ loading.value = true;
+ await Promise.all(
+ kinds.map(async (kind) => {
+ try {
+ documents.value[kind] = await api.consulOperatorRead(props.connectionId, kind);
+ delete failures.value[kind];
+ } catch (error) {
+ failures.value[kind] = error instanceof Error ? error.message : String(error);
+ }
+ }),
+ );
+ loading.value = false;
+}
+
+async function downloadSnapshot() {
+ const snapshot = await api.consulSnapshotGenerate(props.connectionId);
+ const binary = atob(snapshot.dataBase64);
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
+ const link = document.createElement("a");
+ link.href = URL.createObjectURL(new Blob([bytes], { type: "application/octet-stream" }));
+ link.download = `consul-${snapshot.datacenter || "snapshot"}.snap`;
+ link.click();
+ URL.revokeObjectURL(link.href);
+}
+
+async function selectSnapshot(event: Event) {
+ const file = (event.target as HTMLInputElement).files?.[0];
+ if (!file) return;
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ if (bytes.length < 10 || bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) {
+ snapshot.value.data = "";
+ writeError.value = "CONSUL_SNAPSHOT_INVALID: Snapshot must be a gzip archive generated by Consul";
+ return;
+ }
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ snapshot.value.data = btoa(binary);
+}
+
+async function runWrite(action: () => Promise<void>) {
+ writeError.value = "";
+ try {
+ await action();
+ await refresh();
+ } catch (error) {
+ writeError.value = error instanceof Error ? error.message : String(error);
+ }
+}
+
+onMounted(refresh);
+defineExpose({ refresh });
+</script>
+
+<template>
+ <div class="h-full overflow-auto">
+ <div class="sticky top-0 z-10 flex h-10 items-center justify-between border-b bg-background px-3">
+ <span class="text-sm font-medium">{{ t("consul.ui.operatorReadOnly") }}</span>
+ <div class="flex gap-1">
+ <Button variant="outline" size="sm" @click="downloadSnapshot"><Download class="mr-1 h-3.5 w-3.5" />{{ t("consul.ui.snapshot") }}</Button
+ ><Button variant="ghost" size="icon" class="h-7 w-7" :disabled="loading" :title="t('consul.ui.refresh')" @click="refresh"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+ <div class="grid gap-3 p-3 lg:grid-cols-2">
+ <section v-for="kind in kinds" :key="kind" class="border">
+ <h3 class="border-b px-3 py-2 text-xs font-medium uppercase">{{ kind.replaceAll("_", " ") }}</h3>
+ <p v-if="failures[kind]" class="px-3 py-3 text-xs text-destructive">{{ failures[kind] }}</p>
+ <dl v-else class="divide-y">
+ <div v-for="field in documents[kind]?.fields || []" :key="field.name" class="grid grid-cols-[minmax(8rem,1fr)_2fr] gap-3 px-3 py-2 text-xs">
+ <dt class="text-muted-foreground">{{ field.name }}</dt>
+ <dd class="break-all">{{ field.value }}</dd>
+ </div>
+ </dl>
+ </section>
+ </div>
+ <div v-if="writeError" class="mx-3 mb-3 border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{{ writeError }}</div>
+ <div v-if="!readOnly" class="grid gap-3 px-3 pb-3 lg:grid-cols-2">
+ <section v-if="settings.consulOperatorSnapshotRestoreEnabled" class="border p-3">
+ <h3 class="mb-3 text-xs font-medium uppercase">{{ t("consul.ui.snapshotRestore") }}</h3>
+ <div class="grid gap-2">
+ <Input type="file" @change="selectSnapshot" /><Input v-model="snapshot.datacenter" :placeholder="t('consul.ui.targetDatacenter')" /><Input v-model="snapshot.confirmation" :placeholder="t('consul.ui.restoreSnapshotConfirmation', { datacenter: snapshot.datacenter })" /><Button
+ size="sm"
+ :disabled="!snapshot.data"
+ @click="runWrite(() => api.consulSnapshotRestore(props.connectionId, { snapshotBase64: snapshot.data, targetDatacenter: snapshot.datacenter, confirmation: snapshot.confirmation }))"
+ >{{ t("consul.ui.restoreSnapshot") }}</Button
+ >
+ </div>
+ </section>
+ <section v-if="autopilotWriteVisible" class="border p-3">
+ <h3 class="mb-3 text-xs font-medium uppercase">{{ t("consul.ui.autopilotUpdate") }}</h3>
+ <label class="mb-2 flex items-center gap-2 text-xs"><input v-model="autopilot.cleanupDeadServers" type="checkbox" />{{ t("consul.ui.cleanupDeadServers") }}</label
+ ><Input v-model="autopilot.confirmation" :placeholder="t('consul.ui.updateAutopilotConfirmation')" /><Button class="mt-2" size="sm" @click="runWrite(() => api.consulAutopilotUpdate(props.connectionId, { CleanupDeadServers: autopilot.cleanupDeadServers }, autopilot.confirmation))">{{
+ t("consul.ui.updateAutopilot")
+ }}</Button>
+ </section>
+ <section v-if="raftWriteVisible" class="border p-3">
+ <h3 class="mb-3 text-xs font-medium uppercase">{{ t("consul.ui.raftOperations") }}</h3>
+ <div class="grid gap-2">
+ <Input v-model="raft.serverId" :placeholder="t('consul.ui.serverId')" /><Input v-model="raft.address" :placeholder="t('consul.ui.peerAddress')" /><Input v-model="raft.confirmation" :placeholder="t('consul.ui.reenterIdAddress')" />
+ <div class="flex gap-2">
+ <Button size="sm" @click="runWrite(() => api.consulRaftTransfer(props.connectionId, { serverId: raft.serverId || null, address: null, confirmation: raft.confirmation }))">{{ t("consul.ui.transferLeader") }}</Button
+ ><Button size="sm" variant="destructive" @click="runWrite(() => api.consulRaftRemove(props.connectionId, { serverId: raft.serverId || null, address: raft.address || null, confirmation: raft.confirmation }))">{{ t("consul.ui.removePeer") }}</Button>
+ </div>
+ </div>
+ </section>
+ <section v-if="keyringWriteVisible" class="border p-3">
+ <h3 class="mb-3 text-xs font-medium uppercase">{{ t("consul.ui.gossipKeyring") }}</h3>
+ <div class="grid gap-2">
+ <Label>{{ t("consul.ui.operation") }}</Label
+ ><select v-model="keyring.operation" class="h-9 border bg-background px-2 text-sm">
+ <option value="install">{{ t("consul.ui.install") }}</option>
+ <option value="use">{{ t("consul.ui.use") }}</option>
+ <option value="remove">{{ t("consul.ui.remove") }}</option></select
+ ><Input v-model="keyring.key" type="password" :placeholder="t('consul.ui.gossipKey')" /><Input v-model="keyring.confirmation" :placeholder="t('consul.ui.changeKeyringConfirmation')" /><Button size="sm" @click="runWrite(() => api.consulKeyringWrite(props.connectionId, keyring))">{{
+ t("consul.ui.changeKeyring")
+ }}</Button>
+ </div>
+ </section>
+ <section v-if="licenseWriteVisible" class="border p-3">
+ <h3 class="mb-3 text-xs font-medium uppercase">{{ t("consul.ui.licenseUpdate") }}</h3>
+ <div class="grid gap-2">
+ <Input v-model="license.value" type="password" :placeholder="t('consul.ui.license')" /><Input v-model="license.confirmation" :placeholder="t('consul.ui.updateLicenseConfirmation')" /><Button
+ size="sm"
+ @click="runWrite(() => api.consulLicenseWrite(props.connectionId, { license: license.value, confirmation: license.confirmation }))"
+ >{{ t("consul.ui.updateLicense") }}</Button
+ >
+ </div>
+ </section>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulOverview.vue b/apps/desktop/src/components/consul/ConsulOverview.vue
new file mode 100644
index 0000000000..dd919cb01d
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulOverview.vue
@@ -0,0 +1,157 @@
+<script setup lang="ts">
+import { computed, onMounted, ref, watch } from "vue";
+import { AlertTriangle, Loader2, RefreshCcw, Server } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { useI18n } from "vue-i18n";
+import * as api from "@/lib/backend/api";
+import type { ConsulAgentIdentity, ConsulAgentMember, ConsulCapabilities, ConsulOperatorDocument } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string }>();
+const { t } = useI18n();
+const capabilities = ref<ConsulCapabilities | null>(null);
+const identity = ref<ConsulAgentIdentity | null>(null);
+const leader = ref<string | null>(null);
+const peers = ref<string[]>([]);
+const members = ref<ConsulAgentMember[]>([]);
+const autopilotHealth = ref<ConsulOperatorDocument | null>(null);
+const errors = ref<Record<string, string>>({});
+const loading = ref(false);
+let sequence = 0;
+type ProbeState = "loading" | "ready" | "forbidden" | "unsupported" | "error";
+const probeKeys = ["capabilities", "agent", "leader", "peers", "members", "autopilot"] as const;
+type ProbeKey = (typeof probeKeys)[number];
+const probeStates = ref<Record<ProbeKey, ProbeState>>({ capabilities: "loading", agent: "loading", leader: "loading", peers: "loading", members: "loading", autopilot: "loading" });
+
+const memberSummary = computed(() => {
+ const alive = members.value.filter((member) => member.Status === 1).length;
+ return `${alive}/${members.value.length}`;
+});
+
+function message(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+function classifyProbeError(error: unknown): ProbeState {
+ const detail = message(error).toLowerCase();
+ if (detail.includes("consul_permission_denied") || detail.includes("forbidden") || detail.includes("403")) return "forbidden";
+ if (detail.includes("unsupported") || detail.includes("not found") || detail.includes("404")) return "unsupported";
+ return "error";
+}
+
+function probeLabel(key: ProbeKey) {
+ return key === "capabilities" ? t("consul.ui.capabilities") : key === "agent" ? t("consul.ui.agent") : key === "leader" ? t("consul.ui.leader") : key === "peers" ? t("consul.ui.raftPeers") : key === "members" ? t("consul.ui.members") : t("consul.ui.autopilotHealth");
+}
+
+function probeStateLabel(state: ProbeState) {
+ return t(`consul.ui.probe${state[0].toUpperCase()}${state.slice(1)}`);
+}
+
+async function load() {
+ const current = ++sequence;
+ loading.value = true;
+ errors.value = {};
+ probeStates.value = { capabilities: "loading", agent: "loading", leader: "loading", peers: "loading", members: "loading", autopilot: "loading" };
+ const tasks = [
+ ["capabilities", api.consulCapabilities(props.connectionId), (value: ConsulCapabilities) => (capabilities.value = value)],
+ ["agent", api.consulAgentSelf(props.connectionId), (value: ConsulAgentIdentity) => (identity.value = value)],
+ ["leader", api.consulStatusLeader(props.connectionId), (value: string) => (leader.value = value)],
+ ["peers", api.consulStatusPeers(props.connectionId), (value: string[]) => (peers.value = value)],
+ ["members", api.consulAgentMembers(props.connectionId), (value: ConsulAgentMember[]) => (members.value = value)],
+ ["autopilot", api.consulOperatorRead(props.connectionId, "autopilot_health"), (value: ConsulOperatorDocument) => (autopilotHealth.value = value)],
+ ] as const;
+ await Promise.all(
+ tasks.map(async ([name, promise, assign]) => {
+ try {
+ const value = await promise;
+ if (current === sequence) {
+ (assign as (value: never) => void)(value as never);
+ probeStates.value = { ...probeStates.value, [name]: "ready" };
+ }
+ } catch (error) {
+ if (current === sequence) {
+ errors.value = { ...errors.value, [name]: message(error) };
+ probeStates.value = { ...probeStates.value, [name]: classifyProbeError(error) };
+ }
+ }
+ }),
+ );
+ if (current === sequence) loading.value = false;
+}
+
+watch(() => props.connectionId, load);
+onMounted(load);
+defineExpose({ refresh: () => (void load(), true) });
+</script>
+
+<template>
+ <div class="h-full overflow-auto p-4">
+ <div class="mb-3 flex items-center justify-between">
+ <h2 class="flex items-center gap-2 text-sm font-medium"><Server class="h-4 w-4" /> {{ t("consul.ui.overview") }}</h2>
+ <Button size="icon" variant="ghost" class="h-7 w-7" :disabled="loading" :title="t('consul.ui.refresh')" @click="load"> <Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" /><RefreshCcw v-else class="h-3.5 w-3.5" /> </Button>
+ </div>
+ <div class="grid border-l border-t sm:grid-cols-2 lg:grid-cols-4">
+ <div
+ v-for="row in [
+ [t('consul.ui.datacenter'), identity?.datacenter || capabilities?.datacenter || '-'],
+ [t('consul.ui.agentNode'), identity?.node || capabilities?.nodeName || '-'],
+ [t('consul.ui.agentAddress'), identity?.address || '-'],
+ [t('consul.ui.version'), identity?.version || capabilities?.version || '-'],
+ [t('consul.ui.mode'), (identity?.server ?? capabilities?.server) == null ? '-' : (identity?.server ?? capabilities?.server) ? t('consul.ui.server') : t('consul.ui.client')],
+ [t('consul.ui.leader'), leader || '-'],
+ [t('consul.ui.raftPeers'), String(peers.length)],
+ [t('consul.ui.membersAlive'), memberSummary],
+ ]"
+ :key="row[0]"
+ class="min-h-16 border-b border-r p-3"
+ >
+ <div class="text-xs text-muted-foreground">{{ row[0] }}</div>
+ <div class="mt-1 truncate text-sm font-medium" :title="row[1]">{{ row[1] }}</div>
+ </div>
+ </div>
+ <div class="mt-4 grid border-l border-t sm:grid-cols-2 lg:grid-cols-3">
+ <div v-for="key in probeKeys" :key="key" class="flex min-h-10 items-center justify-between gap-3 border-b border-r px-3 py-2 text-xs">
+ <span class="truncate font-medium">{{ probeLabel(key) }}</span>
+ <span class="shrink-0" :class="probeStates[key] === 'ready' ? 'text-emerald-700 dark:text-emerald-300' : probeStates[key] === 'loading' ? 'text-muted-foreground' : probeStates[key] === 'error' ? 'text-destructive' : 'text-amber-700 dark:text-amber-300'" :title="errors[key] || undefined">
+ {{ probeStateLabel(probeStates[key]) }}
+ </span>
+ </div>
+ </div>
+ <div v-if="Object.keys(errors).length" class="mt-4 divide-y border">
+ <div v-for="(error, source) in errors" :key="source" class="flex gap-2 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
+ <AlertTriangle class="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <div>
+ <strong class="mr-1">{{ source }}</strong
+ >{{ error }}
+ </div>
+ </div>
+ </div>
+ <div v-if="autopilotHealth?.fields.length" class="mt-4 overflow-hidden border">
+ <div class="border-b bg-muted/30 px-3 py-2 text-xs font-medium">{{ t("consul.ui.autopilotHealth") }}</div>
+ <dl class="grid sm:grid-cols-2 lg:grid-cols-3">
+ <div v-for="field in autopilotHealth.fields" :key="field.name" class="min-w-0 border-b border-r px-3 py-2 text-xs">
+ <dt class="truncate text-muted-foreground">{{ field.name }}</dt>
+ <dd class="mt-1 truncate font-medium" :title="field.value">{{ field.value }}</dd>
+ </div>
+ </dl>
+ </div>
+ <div class="mt-4 overflow-hidden border">
+ <div class="border-b bg-muted/30 px-3 py-2 text-xs font-medium">{{ t("consul.ui.members") }}</div>
+ <table class="w-full table-fixed text-xs">
+ <thead>
+ <tr class="border-b text-left text-muted-foreground">
+ <th class="px-3 py-2">{{ t("consul.ui.node") }}</th>
+ <th class="px-3 py-2">{{ t("consul.ui.address") }}</th>
+ <th class="w-24 px-3 py-2">{{ t("consul.ui.status") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="member in members" :key="`${member.Name}-${member.Addr}`" class="border-b last:border-0">
+ <td class="truncate px-3 py-2">{{ member.Name }}</td>
+ <td class="truncate px-3 py-2">{{ member.Addr }}:{{ member.Port }}</td>
+ <td class="px-3 py-2">{{ member.Status === 1 ? t("consul.ui.alive") : member.Status === 2 ? t("consul.ui.leaving") : t("consul.ui.failed") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulScope.vue b/apps/desktop/src/components/consul/ConsulScope.vue
new file mode 100644
index 0000000000..66f19671c0
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulScope.vue
@@ -0,0 +1,221 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { Loader2, Pencil, Plus, RefreshCcw, Trash2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import * as api from "@/lib/backend/api";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useI18n } from "vue-i18n";
+import type { ConsulCapabilities, ConsulEnterpriseKind, ConsulEnterpriseWrite, ConsulScopeImpact } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string; capabilities: ConsulCapabilities | null }>();
+const { t } = useI18n();
+const store = useConnectionStore();
+const readOnly = computed(() => Boolean(store.getConfig(props.connectionId)?.read_only));
+const active = ref<ConsulEnterpriseKind>("namespace");
+const items = ref<Record<string, unknown>[]>([]);
+const loading = ref(false);
+const error = ref("");
+const editorOpen = ref(false);
+const editorName = ref<string | null>(null);
+const editorJson = ref("{}");
+const pendingDelete = ref<string | null>(null);
+const impact = ref<ConsulScopeImpact | null>(null);
+const impactLoading = ref(false);
+let impactSequence = 0;
+let loadSequence = 0;
+const status = computed(() => (active.value === "namespace" ? props.capabilities?.namespaces : props.capabilities?.partitions));
+const canWrite = computed(() => status.value === "supported" && !readOnly.value);
+const activeLabel = computed(() => (active.value === "namespace" ? t("consul.ui.namespace") : t("consul.ui.adminPartition")));
+function capabilityLabel(value?: string) {
+ if (value === "supported") return t("consul.ui.capabilitySupported");
+ if (value === "unsupported") return t("consul.ui.capabilityUnsupported");
+ if (value === "disabled") return t("consul.ui.capabilityDisabled");
+ if (value === "forbidden") return t("consul.ui.capabilityForbidden");
+ return t("consul.ui.capabilityUnknown");
+}
+const connectionScope = computed(() => {
+ const config = store.getConfig(props.connectionId);
+ const external = (config?.external_config || {}) as Record<string, unknown>;
+ return { dc: String(external.datacenter || external.consulDatacenter || "default"), partition: String(external.partition || external.consulPartition || "default"), namespace: String(external.namespace || external.consulNamespace || "default") };
+});
+async function load() {
+ const sequence = ++loadSequence;
+ const connectionId = props.connectionId;
+ const kind = active.value;
+ loading.value = true;
+ error.value = "";
+ items.value = [];
+ try {
+ const result = await api.consulEnterpriseList(connectionId, kind);
+ if (sequence !== loadSequence || connectionId !== props.connectionId || kind !== active.value) return;
+ items.value = result.items as Record<string, unknown>[];
+ } catch (cause) {
+ if (sequence === loadSequence && connectionId === props.connectionId && kind === active.value) error.value = cause instanceof Error ? cause.message : String(cause);
+ } finally {
+ if (sequence === loadSequence && connectionId === props.connectionId && kind === active.value) loading.value = false;
+ }
+}
+function nameOf(item: Record<string, unknown>) {
+ return String(item.Name || "");
+}
+function openCreate() {
+ editorName.value = null;
+ editorJson.value = JSON.stringify({ Name: "", ...(active.value === "namespace" ? { Partition: connectionScope.value.partition } : {}), Description: "", Meta: {} }, null, 2);
+ editorOpen.value = true;
+}
+function openEdit(item: Record<string, unknown>) {
+ editorName.value = nameOf(item);
+ editorJson.value = JSON.stringify(item, null, 2);
+ editorOpen.value = true;
+}
+async function save() {
+ try {
+ const item = JSON.parse(editorJson.value) as Record<string, unknown>;
+ const value = { kind: active.value, item } as ConsulEnterpriseWrite;
+ await api.consulEnterpriseApply(props.connectionId, editorName.value, value);
+ editorOpen.value = false;
+ await load();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+async function inspectDelete(name: string) {
+ const current = ++impactSequence;
+ pendingDelete.value = name;
+ impact.value = null;
+ impactLoading.value = true;
+ try {
+ const value = await api.consulEnterpriseImpact(props.connectionId, active.value, name);
+ if (current === impactSequence && pendingDelete.value === name) impact.value = value;
+ } catch (cause) {
+ if (current === impactSequence) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ pendingDelete.value = null;
+ }
+ } finally {
+ if (current === impactSequence) impactLoading.value = false;
+ }
+}
+async function remove() {
+ if (!pendingDelete.value || !impact.value?.complete) return;
+ try {
+ await api.consulEnterpriseDelete(props.connectionId, active.value, pendingDelete.value);
+ pendingDelete.value = null;
+ impact.value = null;
+ await load();
+ } catch (cause) {
+ error.value = cause instanceof Error ? cause.message : String(cause);
+ }
+}
+function closeDelete() {
+ impactSequence += 1;
+ pendingDelete.value = null;
+ impact.value = null;
+ impactLoading.value = false;
+}
+function impactRows(value: ConsulScopeImpact) {
+ return [
+ ["services", value.services],
+ ["nodes", value.nodes],
+ ["kvKeys", value.kvKeys],
+ ["healthChecks", value.healthChecks],
+ ["sessions", value.sessions],
+ ["configEntries", value.configEntries],
+ ["intentions", value.intentions],
+ ["peerings", value.peerings],
+ ["namespaces", value.namespaces],
+ ["aclTokens", value.aclTokens],
+ ["aclPolicies", value.aclPolicies],
+ ["aclRoles", value.aclRoles],
+ ["aclAuthMethods", value.aclAuthMethods],
+ ["aclBindingRules", value.aclBindingRules],
+ ] as const;
+}
+watch([active, () => props.connectionId], () => void load());
+onMounted(() => void load());
+onBeforeUnmount(() => {
+ loadSequence += 1;
+ impactSequence += 1;
+});
+defineExpose({
+ refresh: () => {
+ void load();
+ return true;
+ },
+});
+</script>
+<template>
+ <div class="flex h-full min-h-0 flex-col">
+ <div class="border-b px-4 py-2 text-xs text-muted-foreground">
+ {{ t("consul.ui.datacenter") }}: <b>{{ connectionScope.dc }}</b> · {{ t("consul.ui.adminPartition") }}: <b>{{ connectionScope.partition }}</b> · {{ t("consul.ui.namespace") }}: <b>{{ connectionScope.namespace }}</b>
+ </div>
+ <Tabs v-model="active" class="flex min-h-0 flex-1 flex-col">
+ <div class="flex h-11 items-center justify-between border-b px-3">
+ <TabsList class="h-8 p-0.5"
+ ><TabsTrigger value="namespace" class="h-7 px-3 text-xs">{{ t("consul.ui.namespaces") }}</TabsTrigger
+ ><TabsTrigger value="partition" class="h-7 px-3 text-xs">{{ t("consul.workspace.partitions") }}</TabsTrigger></TabsList
+ >
+ <div class="flex gap-1">
+ <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('consul.ui.refresh')" @click="load"><RefreshCcw class="h-3.5 w-3.5" /></Button><Button v-if="canWrite" size="sm" class="h-7 gap-1 text-xs" @click="openCreate"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.create") }}</Button>
+ </div>
+ </div>
+ <TabsContent v-for="kind in ['namespace', 'partition']" :key="kind" :value="kind" class="m-0 min-h-0 flex-1 overflow-auto p-4">
+ <div v-if="status !== 'supported'" class="border px-3 py-2 text-sm text-muted-foreground">{{ t("consul.ui.enterpriseCapability", { status: capabilityLabel(status) }) }}</div>
+ <div v-else-if="loading" class="flex h-28 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ <div v-else-if="error" class="border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{{ error }}</div>
+ <div v-else class="divide-y border">
+ <div v-for="item in items" :key="nameOf(item)" class="flex min-h-12 items-center gap-3 px-3 py-2">
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{{ nameOf(item) }}</div>
+ <div class="truncate text-xs text-muted-foreground">{{ item.Description || "-" }}</div>
+ </div>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('consul.ui.edit')" @click="openEdit(item)"><Pencil class="h-3.5 w-3.5" /></Button
+ ><Button v-if="canWrite" variant="ghost" size="icon" class="h-7 w-7 text-destructive" :title="t('consul.ui.inspectImpactAndDelete')" @click="inspectDelete(nameOf(item))"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div v-if="!items.length" class="p-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.noResources") }}</div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+ <Dialog v-model:open="editorOpen"
+ ><DialogContent class="max-w-2xl"
+ ><DialogHeader
+ ><DialogTitle>{{ editorName ? t("consul.ui.editResource", { kind: activeLabel }) : t("consul.ui.createResource", { kind: activeLabel }) }}</DialogTitle></DialogHeader
+ ><textarea v-model="editorJson" class="h-72 w-full resize-none rounded-md border bg-background p-3 font-mono text-xs outline-none" spellcheck="false" /><DialogFooter
+ ><Button variant="outline" @click="editorOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button v-if="canWrite" @click="save">{{ t("consul.ui.save") }}</Button></DialogFooter
+ ></DialogContent
+ ></Dialog
+ >
+ <Dialog
+ :open="Boolean(pendingDelete)"
+ @update:open="
+ (value) => {
+ if (!value) closeDelete();
+ }
+ "
+ ><DialogContent
+ ><DialogHeader
+ ><DialogTitle>{{ t("consul.ui.deleteResource", { label: pendingDelete }) }}</DialogTitle></DialogHeader
+ >
+ <div v-if="impactLoading" class="flex min-h-24 items-center justify-center text-sm text-muted-foreground"><Loader2 class="mr-2 h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ <div v-else-if="impact" class="text-sm">
+ <dl class="grid grid-cols-2 border-l border-t text-xs">
+ <div v-for="[resource, count] in impactRows(impact)" :key="resource" class="flex items-center justify-between gap-3 border-b border-r px-3 py-2">
+ <dt class="truncate text-muted-foreground">{{ t(`consul.ui.impactResource.${resource}`) }}</dt>
+ <dd class="font-mono font-medium">{{ count }}</dd>
+ </div>
+ </dl>
+ <p v-if="impact.filteredByAcls" class="mt-2 text-destructive">{{ t("consul.ui.impactAclFiltered") }}</p>
+ <p v-if="impact.unavailableResources.length" class="mt-2 break-words text-destructive">{{ t("consul.ui.impactUnavailable", { resources: impact.unavailableResources.join(", ") }) }}</p>
+ <p v-if="!impact.complete" class="mt-2 text-destructive">{{ t("consul.ui.impactBlocked") }}</p>
+ </div>
+ <DialogFooter
+ ><Button variant="outline" @click="closeDelete">{{ t("consul.ui.cancel") }}</Button
+ ><Button variant="destructive" :disabled="impactLoading || !impact?.complete" @click="remove">{{ t("consul.ui.delete") }}</Button></DialogFooter
+ ></DialogContent
+ ></Dialog
+ >
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulServices.vue b/apps/desktop/src/components/consul/ConsulServices.vue
new file mode 100644
index 0000000000..48afa089fb
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulServices.vue
@@ -0,0 +1,941 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from "vue";
+import { CircleCheck, Loader2, LockKeyhole, Pause, Plus, Radio, RefreshCcw, Search, ServerCog, Trash2, Wrench } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import ConsulListPagination from "@/components/consul/ConsulListPagination.vue";
+import * as api from "@/lib/backend/api";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useConsulStore } from "@/stores/consulStore";
+import { nextWatchIndex } from "@/lib/consul/watchState";
+import { consulAgentWriteTargetSafe } from "@/lib/consul/agentTarget";
+import { clampConsulPage, CONSUL_LIST_PAGE_SIZE, paginateConsulItems } from "@/lib/consul/pagination";
+import { useI18n } from "vue-i18n";
+import type { ConsulAgentIdentity, ConsulAgentService, ConsulAgentServiceRegistration, ConsulCatalogNode, ConsulCatalogServiceNode, ConsulDomainWatchResponse, ConsulHealthCheck, ConsulNodeServices, ConsulScope } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string }>();
+const { t } = useI18n();
+const store = useConnectionStore();
+const consulStore = useConsulStore();
+const services = ref<Record<string, string[]>>({});
+const nodes = ref<ConsulCatalogNode[]>([]);
+const localServices = ref<Record<string, ConsulAgentService>>({});
+const localChecks = ref<Record<string, ConsulHealthCheck>>({});
+const selectedLocalService = ref<ConsulAgentService | null>(null);
+const identity = ref<ConsulAgentIdentity | null>(null);
+const agentTarget = computed(() => {
+ const external = store.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ const raw = config.agentTarget || config.agent_target;
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const target = raw as Record<string, unknown>;
+ const node = String(target.node || "").trim();
+ const address = String(target.address || "").trim();
+ return node && address ? { node, address } : null;
+});
+const canAgentWrite = computed(() => consulAgentWriteTargetSafe(store.getConfig(props.connectionId), identity.value?.node));
+const agentTargetStatus = computed<"verifying" | "writable" | "readonly">(() => {
+ if (agentLoading.value && !identity.value) return "verifying";
+ return canAgentWrite.value ? "writable" : "readonly";
+});
+const selected = ref("");
+const selectedNode = ref("");
+const browseMode = ref<"service" | "node">("service");
+const browseFilter = ref("");
+const localServiceFilter = ref("");
+const instances = ref<ConsulCatalogServiceNode[]>([]);
+const selectedCatalogInstanceKey = ref("");
+const nodeServices = ref<ConsulNodeServices | null>(null);
+const selectedNodeServiceId = ref("");
+const browsePage = ref(1);
+const catalogInstancePage = ref(1);
+const nodeServicePage = ref(1);
+const localServicePage = ref(1);
+const errors = ref<Record<string, string>>({});
+const loading = ref(false);
+const agentLoading = ref(true);
+const saving = ref(false);
+const editorOpen = ref(false);
+const maintenancePendingId = ref("");
+const form = ref({ id: "", name: "", tags: "", address: "", port: 0 });
+let sequence = 0;
+const watchEnabled = ref(false);
+const watchPaused = ref(false);
+const watchIndex = ref<string | null>(null);
+let watchConnectionId = "";
+let watchScope: ConsulScope = { datacenter: "", namespace: "", partition: "" };
+let watchGeneration = 0;
+let servicesWatchId = "";
+let instancesWatchId = "";
+let nodesWatchId = "";
+let nodeServicesWatchId = "";
+
+const serviceNames = computed(() => Object.keys(services.value).sort());
+const nodeNames = computed(() =>
+ nodes.value
+ .map((node) => node.Node)
+ .filter(Boolean)
+ .sort(),
+);
+const normalizedBrowseFilter = computed(() => browseFilter.value.trim().toLocaleLowerCase());
+const filteredServiceNames = computed(() =>
+ serviceNames.value.filter((name) => {
+ const query = normalizedBrowseFilter.value;
+ return !query || `${name} ${services.value[name]?.join(" ") || ""}`.toLocaleLowerCase().includes(query);
+ }),
+);
+const filteredNodeNames = computed(() => nodeNames.value.filter((name) => !normalizedBrowseFilter.value || name.toLocaleLowerCase().includes(normalizedBrowseFilter.value)));
+const localServiceItems = computed(() => Object.values(localServices.value).sort((left, right) => left.Service.localeCompare(right.Service) || left.ID.localeCompare(right.ID)));
+const normalizedLocalServiceFilter = computed(() => localServiceFilter.value.trim().toLocaleLowerCase());
+const filteredLocalServiceItems = computed(() =>
+ localServiceItems.value.filter((service) => {
+ const query = normalizedLocalServiceFilter.value;
+ if (!query) return true;
+ const metadata = Object.entries(service.Meta || {})
+ .map(([key, value]) => `${key} ${value}`)
+ .join(" ");
+ return `${service.Service} ${service.ID} ${service.Address} ${service.Port} ${service.Tags.join(" ")} ${metadata}`.toLocaleLowerCase().includes(query);
+ }),
+);
+const nodeServiceItems = computed(() => Object.values(nodeServices.value?.Services || {}).sort((left, right) => left.Service.localeCompare(right.Service) || left.ID.localeCompare(right.ID)));
+const pagedServiceNames = computed(() => paginateConsulItems(filteredServiceNames.value, browsePage.value));
+const pagedNodeNames = computed(() => paginateConsulItems(filteredNodeNames.value, browsePage.value));
+const pagedCatalogInstances = computed(() => paginateConsulItems(instances.value, catalogInstancePage.value));
+const pagedNodeServices = computed(() => paginateConsulItems(nodeServiceItems.value, nodeServicePage.value));
+const pagedLocalServices = computed(() => paginateConsulItems(filteredLocalServiceItems.value, localServicePage.value));
+const maintenanceServiceIds = computed(
+ () =>
+ new Set(
+ Object.values(localChecks.value)
+ .filter((check) => check.Type === "maintenance" || check.CheckID.startsWith("_service_maintenance:"))
+ .map((check) => check.ServiceID || check.CheckID.slice("_service_maintenance:".length)),
+ ),
+);
+function errorMessage(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+function normalizeCatalogServices(value: Record<string, string[]>): Record<string, string[]> {
+ return Object.fromEntries(Object.entries(value).map(([name, tags]) => [name, [...tags].sort((left, right) => left.localeCompare(right))]));
+}
+
+function isServiceInMaintenance(id: string) {
+ return maintenanceServiceIds.value.has(id);
+}
+
+async function withTimeout<T>(promise: Promise<T>, milliseconds: number, message: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ promise,
+ new Promise<T>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(message)), milliseconds);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
+function currentScope(): ConsulScope {
+ const external = store.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ return {
+ datacenter: String(config.datacenter || config.consulDatacenter || config.consul_datacenter || ""),
+ namespace: String(config.namespace || config.consulNamespace || config.consul_namespace || ""),
+ partition: String(config.partition || config.consulPartition || config.consul_partition || ""),
+ };
+}
+
+function watchId(kind: string) {
+ return globalThis.crypto?.randomUUID?.() || `${kind}-${Date.now()}-${Math.random()}`;
+}
+function watchActive(operationId: string) {
+ return watchEnabled.value && !watchPaused.value && watchConnectionId === props.connectionId && watchGeneration === consulStore.generation && operationId !== "";
+}
+
+async function stopWatches() {
+ const operations = [servicesWatchId, instancesWatchId, nodesWatchId, nodeServicesWatchId].filter(Boolean);
+ servicesWatchId = "";
+ instancesWatchId = "";
+ nodesWatchId = "";
+ nodeServicesWatchId = "";
+ await Promise.all(
+ operations.map(async (operationId) => {
+ consulStore.completeOperation(operationId);
+ await api.consulCancelBlocking(watchConnectionId, watchScope, watchGeneration, operationId).catch(() => false);
+ }),
+ );
+}
+
+async function runServicesWatch(operationId: string) {
+ let index: string | null = null;
+ while (watchActive(operationId) && servicesWatchId === operationId) {
+ try {
+ const result = (await api.consulDomainWatch(watchConnectionId, {
+ operationId,
+ generation: watchGeneration,
+ target: { kind: "catalogServices" },
+ index,
+ waitSeconds: 300,
+ })) as ConsulDomainWatchResponse<Record<string, string[]>>;
+ index = nextWatchIndex(index, result.metadata.index).index;
+ watchIndex.value = index;
+ if (result.changed || result.indexReset) {
+ services.value = normalizeCatalogServices(result.items);
+ if (!selected.value || !services.value[selected.value]) {
+ selected.value = serviceNames.value[0] || "";
+ await loadInstances();
+ await startInstanceWatch();
+ }
+ }
+ } catch (error) {
+ if (watchActive(operationId) && !String(error).includes("CANCELLED")) errors.value = { ...errors.value, [t("consul.ui.watch")]: errorMessage(error) };
+ break;
+ }
+ }
+ consulStore.completeOperation(operationId);
+}
+
+async function runInstancesWatch(operationId: string, service: string) {
+ let index: string | null = null;
+ while (watchActive(operationId) && instancesWatchId === operationId && selected.value === service) {
+ try {
+ const result = (await api.consulDomainWatch(watchConnectionId, {
+ operationId,
+ generation: watchGeneration,
+ target: { kind: "catalogServiceNodes", service },
+ index,
+ waitSeconds: 300,
+ })) as ConsulDomainWatchResponse<ConsulCatalogServiceNode[]>;
+ index = nextWatchIndex(index, result.metadata.index).index;
+ watchIndex.value = index;
+ if (result.changed || result.indexReset) instances.value = result.items;
+ } catch (error) {
+ if (watchActive(operationId) && !String(error).includes("CANCELLED")) errors.value = { ...errors.value, [t("consul.ui.watch")]: errorMessage(error) };
+ break;
+ }
+ }
+ consulStore.completeOperation(operationId);
+}
+
+async function runNodesWatch(operationId: string) {
+ let index: string | null = null;
+ while (watchActive(operationId) && nodesWatchId === operationId && browseMode.value === "node") {
+ try {
+ const result = (await api.consulDomainWatch(watchConnectionId, {
+ operationId,
+ generation: watchGeneration,
+ target: { kind: "catalogNodes" },
+ index,
+ waitSeconds: 300,
+ })) as ConsulDomainWatchResponse<ConsulCatalogNode[]>;
+ index = nextWatchIndex(index, result.metadata.index).index;
+ watchIndex.value = index;
+ if (result.changed || result.indexReset) {
+ nodes.value = result.items;
+ if (!selectedNode.value || !nodeNames.value.includes(selectedNode.value)) {
+ selectedNode.value = nodeNames.value[0] || "";
+ await loadNodeServices();
+ await startNodeServicesWatch();
+ }
+ }
+ } catch (error) {
+ if (watchActive(operationId) && !String(error).includes("CANCELLED")) errors.value = { ...errors.value, [t("consul.ui.watch")]: errorMessage(error) };
+ break;
+ }
+ }
+ consulStore.completeOperation(operationId);
+}
+
+async function runNodeServicesWatch(operationId: string, node: string) {
+ let index: string | null = null;
+ while (watchActive(operationId) && nodeServicesWatchId === operationId && browseMode.value === "node" && selectedNode.value === node) {
+ try {
+ const result = (await api.consulDomainWatch(watchConnectionId, {
+ operationId,
+ generation: watchGeneration,
+ target: { kind: "catalogNodeServices", node },
+ index,
+ waitSeconds: 300,
+ })) as ConsulDomainWatchResponse<ConsulNodeServices>;
+ index = nextWatchIndex(index, result.metadata.index).index;
+ watchIndex.value = index;
+ if (result.changed || result.indexReset) nodeServices.value = result.items;
+ } catch (error) {
+ if (watchActive(operationId) && !String(error).includes("CANCELLED")) errors.value = { ...errors.value, [t("consul.ui.watch")]: errorMessage(error) };
+ break;
+ }
+ }
+ consulStore.completeOperation(operationId);
+}
+
+async function startInstanceWatch() {
+ if (!watchEnabled.value || watchPaused.value || !selected.value) return;
+ if (instancesWatchId) await stopInstanceWatch();
+ const operationId = watchId("consul-catalog-instances");
+ instancesWatchId = operationId;
+ consulStore.registerOperation(operationId);
+ void runInstancesWatch(operationId, selected.value);
+}
+
+async function stopInstanceWatch() {
+ const operationId = instancesWatchId;
+ instancesWatchId = "";
+ if (!operationId) return;
+ consulStore.completeOperation(operationId);
+ await api.consulCancelBlocking(watchConnectionId, watchScope, watchGeneration, operationId).catch(() => false);
+}
+
+async function startNodeServicesWatch() {
+ if (!watchEnabled.value || watchPaused.value || !selectedNode.value || browseMode.value !== "node") return;
+ if (nodeServicesWatchId) {
+ const previousOperationId = nodeServicesWatchId;
+ nodeServicesWatchId = "";
+ consulStore.completeOperation(previousOperationId);
+ await api.consulCancelBlocking(watchConnectionId, watchScope, watchGeneration, previousOperationId).catch(() => false);
+ }
+ const operationId = watchId("consul-catalog-node-services");
+ nodeServicesWatchId = operationId;
+ consulStore.registerOperation(operationId);
+ void runNodeServicesWatch(operationId, selectedNode.value);
+}
+
+async function startWatches() {
+ if ((servicesWatchId || nodesWatchId) && watchEnabled.value && !watchPaused.value) return;
+ watchEnabled.value = true;
+ watchPaused.value = false;
+ watchConnectionId = props.connectionId;
+ watchScope = currentScope();
+ consulStore.bindConnection(watchConnectionId, watchScope);
+ watchGeneration = consulStore.generation;
+ if (browseMode.value === "service") {
+ servicesWatchId = watchId("consul-catalog-services");
+ consulStore.registerOperation(servicesWatchId);
+ void runServicesWatch(servicesWatchId);
+ await startInstanceWatch();
+ } else {
+ nodesWatchId = watchId("consul-catalog-nodes");
+ consulStore.registerOperation(nodesWatchId);
+ void runNodesWatch(nodesWatchId);
+ await startNodeServicesWatch();
+ }
+}
+
+async function pauseWatches() {
+ watchPaused.value = true;
+ await stopWatches();
+}
+
+async function independent(name: string, action: () => Promise<void>) {
+ try {
+ await action();
+ } catch (error) {
+ errors.value = { ...errors.value, [name]: errorMessage(error) };
+ }
+}
+
+async function load() {
+ const current = ++sequence;
+ loading.value = true;
+ agentLoading.value = true;
+ errors.value = {};
+ // Catalog browsing must remain responsive even when an Agent endpoint is slow or unavailable.
+ // The local-Agent section is supplementary, while Catalog is the primary navigation surface.
+ await Promise.all([
+ independent(t("consul.ui.catalogServices"), async () => {
+ const result = await api.consulCatalogServices(props.connectionId);
+ if (current === sequence) services.value = normalizeCatalogServices(result.items);
+ }),
+ independent(t("consul.ui.catalogNodes"), async () => {
+ const result = await api.consulCatalogNodes(props.connectionId);
+ if (current === sequence) nodes.value = result.items;
+ }),
+ ]);
+ if (current === sequence) {
+ if (!selected.value || !services.value[selected.value]) selected.value = serviceNames.value[0] || "";
+ if (!selectedNode.value || !nodeNames.value.includes(selectedNode.value)) selectedNode.value = nodeNames.value[0] || "";
+ loading.value = false;
+ if (browseMode.value === "service") await loadInstances();
+ else await loadNodeServices();
+ }
+ void loadAgentData(current);
+}
+
+async function loadAgentData(current = sequence) {
+ agentLoading.value = true;
+ await Promise.all([
+ independent(t("consul.ui.agent"), async () => {
+ const result = await withTimeout(api.consulAgentSelf(props.connectionId), 8_000, t("consul.ui.agentIdentityRequestTimedOut"));
+ if (current === sequence) identity.value = result;
+ }),
+ independent(t("consul.ui.localAgentServices"), async () => {
+ const result = await withTimeout(api.consulAgentServices(props.connectionId), 8_000, t("consul.ui.localServicesRequestTimedOut"));
+ if (current === sequence) localServices.value = result;
+ }),
+ independent(t("consul.ui.localAgentChecks"), async () => {
+ const result = await withTimeout(api.consulAgentChecks(props.connectionId), 8_000, t("consul.ui.localChecksRequestTimedOut"));
+ if (current === sequence) localChecks.value = result;
+ }),
+ ]);
+ if (current === sequence) agentLoading.value = false;
+}
+
+async function selectService(service: string) {
+ selected.value = service;
+ await loadInstances();
+ await startInstanceWatch();
+}
+
+async function selectNode(node: string) {
+ selectedNode.value = node;
+ await loadNodeServices();
+ await startNodeServicesWatch();
+}
+
+async function loadInstances() {
+ instances.value = [];
+ catalogInstancePage.value = 1;
+ selectedCatalogInstanceKey.value = "";
+ const service = selected.value;
+ if (!service) return;
+ await independent(t("consul.ui.serviceInstances"), async () => {
+ const result = await api.consulCatalogServiceNodes(props.connectionId, service);
+ if (selected.value === service) instances.value = result.items;
+ });
+}
+
+function catalogInstanceKey(item: ConsulCatalogServiceNode) {
+ return `${item.Node}\u0000${item.ServiceID}`;
+}
+
+function toggleCatalogInstance(item: ConsulCatalogServiceNode) {
+ const key = catalogInstanceKey(item);
+ selectedCatalogInstanceKey.value = selectedCatalogInstanceKey.value === key ? "" : key;
+}
+
+async function loadNodeServices() {
+ nodeServices.value = null;
+ nodeServicePage.value = 1;
+ selectedNodeServiceId.value = "";
+ const node = selectedNode.value;
+ if (!node) return;
+ await independent(t("consul.ui.nodeServices"), async () => {
+ const result = await api.consulCatalogNodeServices(props.connectionId, node);
+ if (selectedNode.value === node) nodeServices.value = result.items;
+ });
+}
+
+function toggleNodeService(id: string) {
+ selectedNodeServiceId.value = selectedNodeServiceId.value === id ? "" : id;
+}
+
+function updateCatalogInstancePage(page: number) {
+ catalogInstancePage.value = page;
+ selectedCatalogInstanceKey.value = "";
+}
+
+function updateNodeServicePage(page: number) {
+ nodeServicePage.value = page;
+ selectedNodeServiceId.value = "";
+}
+
+function updateLocalServicePage(page: number) {
+ localServicePage.value = page;
+ selectedLocalService.value = null;
+}
+
+async function switchBrowseMode(mode: "service" | "node") {
+ if (browseMode.value === mode) return;
+ const resume = watchEnabled.value && !watchPaused.value;
+ await stopWatches();
+ browseMode.value = mode;
+ if (mode === "service") await loadInstances();
+ else await loadNodeServices();
+ if (resume) await startWatches();
+}
+
+async function openLocalService(id: string) {
+ if (selectedLocalService.value?.ID === id) {
+ selectedLocalService.value = null;
+ return;
+ }
+ await independent(t("consul.ui.localServiceDetails"), async () => {
+ selectedLocalService.value = await api.consulAgentService(props.connectionId, id);
+ });
+}
+
+async function registerService() {
+ if (!canAgentWrite.value || !form.value.name.trim()) return;
+ saving.value = true;
+ try {
+ const registration: ConsulAgentServiceRegistration = {
+ id: form.value.id.trim(),
+ name: form.value.name.trim(),
+ tags: form.value.tags
+ .split(",")
+ .map((tag) => tag.trim())
+ .filter(Boolean),
+ address: form.value.address.trim(),
+ port: Number(form.value.port) || 0,
+ meta: {},
+ weights: { Passing: 1, Warning: 1 },
+ kind: "",
+ enableTagOverride: false,
+ proxy: null,
+ checks: [],
+ };
+ await api.consulAgentRegisterService(props.connectionId, registration);
+ editorOpen.value = false;
+ await load();
+ } catch (error) {
+ errors.value = { ...errors.value, [t("consul.ui.writeOperation")]: errorMessage(error) };
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function deregister(id: string) {
+ if (!canAgentWrite.value || !window.confirm(t("consul.ui.deregisterService", { id, node: agentTarget.value?.node || t("consul.ui.targetAgent") }))) return;
+ await independent(t("consul.ui.writeOperation"), async () => {
+ await api.consulAgentDeregisterService(props.connectionId, id);
+ await load();
+ });
+}
+
+async function maintenance(id: string, enable: boolean) {
+ if (!canAgentWrite.value) return;
+ maintenancePendingId.value = id;
+ try {
+ await independent(t("consul.ui.writeOperation"), async () => {
+ await api.consulAgentServiceMaintenance(props.connectionId, id, enable, t("consul.ui.maintenanceReason"));
+ await loadAgentData();
+ });
+ } finally {
+ maintenancePendingId.value = "";
+ }
+}
+
+watch([browseFilter, browseMode], () => {
+ browsePage.value = 1;
+});
+watch(localServiceFilter, () => {
+ localServicePage.value = 1;
+ selectedLocalService.value = null;
+});
+watch(filteredServiceNames, (items) => {
+ if (browseMode.value === "service") browsePage.value = clampConsulPage(browsePage.value, items.length);
+});
+watch(filteredNodeNames, (items) => {
+ if (browseMode.value === "node") browsePage.value = clampConsulPage(browsePage.value, items.length);
+});
+watch(instances, (items) => {
+ catalogInstancePage.value = clampConsulPage(catalogInstancePage.value, items.length);
+});
+watch(nodeServiceItems, (items) => {
+ nodeServicePage.value = clampConsulPage(nodeServicePage.value, items.length);
+});
+watch(filteredLocalServiceItems, (items) => {
+ localServicePage.value = clampConsulPage(localServicePage.value, items.length);
+});
+watch(
+ () => props.connectionId,
+ async () => {
+ await stopWatches();
+ watchEnabled.value = false;
+ watchPaused.value = false;
+ watchIndex.value = null;
+ identity.value = null;
+ agentLoading.value = true;
+ browsePage.value = 1;
+ catalogInstancePage.value = 1;
+ nodeServicePage.value = 1;
+ localServicePage.value = 1;
+ await load();
+ },
+);
+onMounted(load);
+onDeactivated(() => {
+ watchPaused.value = true;
+ void stopWatches();
+});
+onBeforeUnmount(() => {
+ void stopWatches();
+});
+defineExpose({ refresh: () => (void load(), true) });
+</script>
+
+<template>
+ <div class="flex h-full min-h-0">
+ <aside class="flex w-64 shrink-0 flex-col border-r bg-muted/10">
+ <div class="shrink-0 border-b bg-background">
+ <div class="flex h-11 items-center justify-between px-3">
+ <div class="text-sm font-medium">{{ browseMode === "service" ? t("consul.ui.catalogServices") : t("consul.ui.catalogNodes") }}</div>
+ <Button size="icon" variant="ghost" class="h-7 w-7" :disabled="loading" :title="t('consul.ui.refresh')" @click="load"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div class="grid grid-cols-2 px-3 pb-2 text-xs">
+ <Button size="sm" class="h-7 rounded-r-none" :variant="browseMode === 'service' ? 'default' : 'outline'" @click="switchBrowseMode('service')">{{ t("consul.ui.service") }}</Button>
+ <Button size="sm" class="h-7 rounded-l-none" :variant="browseMode === 'node' ? 'default' : 'outline'" @click="switchBrowseMode('node')">{{ t("consul.ui.node") }}</Button>
+ </div>
+ <div class="relative px-3 pb-3">
+ <Search class="pointer-events-none absolute left-5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
+ <Input v-model="browseFilter" class="h-8 pl-7 text-xs" :placeholder="browseMode === 'service' ? t('consul.ui.searchAllServices') : t('consul.ui.searchAllNodes')" />
+ </div>
+ </div>
+ <div class="min-h-0 flex-1 overflow-auto py-1">
+ <template v-if="browseMode === 'service'">
+ <Button v-for="name in pagedServiceNames" :key="name" type="button" size="sm" :variant="selected === name ? 'secondary' : 'ghost'" class="h-auto min-h-11 w-full justify-start rounded-none px-3 py-2 text-left text-xs" @click="selectService(name)">
+ <span class="min-w-0 flex-1 truncate font-medium" :title="name">{{ name }}</span>
+ </Button>
+ <div v-if="!filteredServiceNames.length && !loading" class="p-3 text-xs text-muted-foreground">{{ serviceNames.length ? t("consul.ui.noMatchingServices") : t("consul.ui.noVisibleServices") }}</div>
+ </template>
+ <template v-else>
+ <Button v-for="name in pagedNodeNames" :key="name" type="button" size="sm" :variant="selectedNode === name ? 'secondary' : 'ghost'" class="h-auto min-h-11 w-full justify-start rounded-none px-3 py-2 text-left text-xs" @click="selectNode(name)"
+ ><span class="truncate font-medium">{{ name }}</span></Button
+ >
+ <div v-if="!filteredNodeNames.length && !loading" class="p-3 text-xs text-muted-foreground">{{ nodeNames.length ? t("consul.ui.noMatchingNodes") : t("consul.ui.noVisibleNodes") }}</div>
+ </template>
+ </div>
+ <div v-if="(browseMode === 'service' ? filteredServiceNames.length : filteredNodeNames.length) > CONSUL_LIST_PAGE_SIZE" class="shrink-0 border-t bg-background px-2 py-1">
+ <ConsulListPagination compact :total="browseMode === 'service' ? filteredServiceNames.length : filteredNodeNames.length" :page="browsePage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="browsePage = $event" />
+ </div>
+ </aside>
+
+ <main class="min-w-0 flex-1 overflow-auto p-4">
+ <header class="mb-4 flex flex-col gap-3 border-b pb-3 sm:flex-row sm:items-center sm:justify-between">
+ <div class="min-w-0">
+ <div class="text-xs font-medium text-muted-foreground">{{ browseMode === "service" ? t("consul.ui.catalogServices") : t("consul.ui.catalogNodes") }}</div>
+ <h2 class="mt-0.5 truncate text-lg font-semibold">{{ browseMode === "service" ? selected || t("consul.ui.services") : selectedNode || t("consul.ui.nodes") }}</h2>
+ <div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <Badge :variant="agentTargetStatus === 'writable' ? 'secondary' : 'outline'" :class="agentTargetStatus === 'writable' ? 'text-emerald-700 dark:text-emerald-300' : agentTargetStatus === 'readonly' ? 'border-amber-500/40 text-amber-700 dark:text-amber-300' : 'text-muted-foreground'">
+ <Loader2 v-if="agentTargetStatus === 'verifying'" class="mr-1 h-3 w-3 animate-spin" /><ServerCog v-else class="mr-1 h-3 w-3" />{{
+ agentTargetStatus === "verifying" ? t("consul.ui.agentTargetVerifying") : t("consul.ui.agentTarget", { target: canAgentWrite && agentTarget ? `${agentTarget.node} (${agentTarget.address})` : t("consul.ui.unknownWritesDisabled") })
+ }}
+ </Badge>
+ </div>
+ </div>
+ <div class="flex shrink-0 items-center gap-2">
+ <span v-if="watchEnabled" class="hidden text-xs text-muted-foreground lg:inline">{{ watchPaused ? t("consul.ui.watchPaused") : t("consul.ui.watchingIndex", { index: watchIndex || "1" }) }}</span>
+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :title="watchEnabled && !watchPaused ? t('consul.ui.pauseWatch') : t('consul.ui.startWatch')" @click="watchEnabled && !watchPaused ? pauseWatches() : startWatches()"
+ ><Pause v-if="watchEnabled && !watchPaused" class="h-3.5 w-3.5" /><Radio v-else class="h-3.5 w-3.5" />{{ watchEnabled && !watchPaused ? t("consul.ui.pauseWatch") : t("consul.ui.startWatch") }}</Button
+ >
+ <Button size="sm" class="h-8 gap-1.5" :disabled="!canAgentWrite" :title="canAgentWrite ? undefined : t('consul.ui.unknownWritesDisabled')" @click="editorOpen = !editorOpen"><Plus class="h-3.5 w-3.5" />{{ t("consul.ui.register") }}</Button>
+ </div>
+ </header>
+
+ <div v-if="Object.keys(errors).length" class="mb-3 rounded-md border border-amber-300 bg-amber-50 p-2 text-xs text-amber-800 dark:bg-amber-950/30 dark:text-amber-200">
+ <div v-for="(error, name) in errors" :key="name">
+ <strong>{{ name }}:</strong> {{ error }}
+ </div>
+ </div>
+
+ <section v-if="editorOpen" class="mb-4 rounded-lg border bg-muted/10 p-4 sm:p-5">
+ <p class="mb-4 text-xs leading-5 text-amber-700 dark:text-amber-300">{{ t("consul.ui.registrationHint") }}</p>
+ <div class="grid gap-x-5 gap-y-4 md:grid-cols-2">
+ <div class="space-y-1.5">
+ <Label class="block text-xs font-medium">{{ t("consul.ui.name") }}</Label
+ ><Input v-model="form.name" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="block text-xs font-medium">{{ t("consul.ui.id") }}</Label
+ ><Input v-model="form.id" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="block text-xs font-medium">{{ t("consul.ui.address") }}</Label
+ ><Input v-model="form.address" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="block text-xs font-medium">{{ t("consul.ui.port") }}</Label
+ ><Input v-model.number="form.port" class="h-9" type="number" min="0" max="65535" />
+ </div>
+ <div class="space-y-1.5 md:col-span-2">
+ <Label class="block text-xs font-medium">{{ t("consul.ui.tags") }}</Label
+ ><Input v-model="form.tags" class="h-9" />
+ </div>
+ </div>
+ <div class="mt-5 flex justify-end gap-2 border-t pt-4">
+ <Button variant="outline" size="sm" @click="editorOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button size="sm" :disabled="saving || !canAgentWrite || !form.name.trim()" @click="registerService"><Loader2 v-if="saving" class="mr-1 h-3.5 w-3.5 animate-spin" />{{ t("consul.ui.registerOn", { node: agentTarget?.node || t("consul.ui.targetAgent") }) }}</Button>
+ </div>
+ </section>
+
+ <section class="mb-4 overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between gap-3 border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <span>{{ browseMode === "service" ? t("consul.ui.catalogInstances") : t("consul.ui.nodeServices") }}</span
+ ><Badge variant="secondary">{{ browseMode === "service" ? instances.length : nodeServiceItems.length }}</Badge>
+ </div>
+ <ConsulListPagination v-if="browseMode === 'service'" :total="instances.length" :page="catalogInstancePage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="updateCatalogInstancePage" />
+ <ConsulListPagination v-else :total="nodeServiceItems.length" :page="nodeServicePage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="updateNodeServicePage" />
+ </div>
+ <div v-if="browseMode === 'service'" class="overflow-x-auto">
+ <table class="w-full table-fixed text-xs">
+ <thead>
+ <tr class="border-b bg-muted/10 text-left text-muted-foreground">
+ <th class="w-[24%] px-3 py-2.5 font-medium">{{ t("consul.ui.node") }}</th>
+ <th class="w-[17%] px-3 py-2.5 font-medium">{{ t("consul.ui.serviceId") }}</th>
+ <th class="w-[18%] px-3 py-2.5 font-medium">{{ t("consul.ui.address") }}</th>
+ <th class="w-[18%] px-3 py-2.5 font-medium">{{ t("consul.ui.tags") }}</th>
+ <th class="w-[23%] px-3 py-2.5 font-medium">{{ t("consul.ui.metadata") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <template v-for="item in pagedCatalogInstances" :key="catalogInstanceKey(item)">
+ <tr
+ role="button"
+ tabindex="0"
+ class="cursor-pointer border-b outline-none hover:bg-muted/20 focus-visible:bg-muted/30"
+ :class="selectedCatalogInstanceKey === catalogInstanceKey(item) && 'bg-muted/20'"
+ :aria-expanded="selectedCatalogInstanceKey === catalogInstanceKey(item)"
+ @click="toggleCatalogInstance(item)"
+ @keydown.enter.prevent="toggleCatalogInstance(item)"
+ @keydown.space.prevent="toggleCatalogInstance(item)"
+ >
+ <td class="px-3 py-3">
+ <div class="truncate font-medium">{{ item.Node }}</div>
+ <div
+ class="mt-0.5 truncate text-muted-foreground"
+ :title="
+ Object.entries(item.NodeMeta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(', ')
+ "
+ >
+ {{ item.Datacenter }} · {{ Object.keys(item.NodeMeta).length }} {{ t("consul.ui.metadata") }}
+ </div>
+ </td>
+ <td class="px-3 py-3 font-mono text-muted-foreground">
+ <span class="block truncate" :title="item.ServiceID">{{ item.ServiceID || "-" }}</span>
+ </td>
+ <td class="px-3 py-3 font-mono">
+ <span class="block truncate">{{ item.ServiceAddress || item.Address }}:{{ item.ServicePort }}</span>
+ </td>
+ <td class="px-3 py-3">
+ <div v-if="item.ServiceTags.length" class="flex flex-wrap gap-1">
+ <Badge v-for="tag in item.ServiceTags" :key="tag" variant="outline" class="h-5 px-1.5 text-[10px]">{{ tag }}</Badge>
+ </div>
+ <span v-else class="text-muted-foreground">-</span>
+ </td>
+ <td class="px-3 py-3">
+ <span
+ class="block truncate text-muted-foreground"
+ :title="
+ Object.entries(item.ServiceMeta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(', ')
+ "
+ >{{
+ Object.entries(item.ServiceMeta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(", ") || "-"
+ }}</span
+ >
+ </td>
+ </tr>
+ <tr v-if="selectedCatalogInstanceKey === catalogInstanceKey(item)" class="border-b bg-muted/10">
+ <td colspan="5" class="px-3 py-3">
+ <div class="grid overflow-hidden rounded-md border bg-background sm:grid-cols-4">
+ <div class="border-b px-3 py-2 sm:border-r">
+ <div class="text-muted-foreground">{{ t("consul.ui.serviceKind") }}</div>
+ <div class="mt-1 font-medium">{{ item.ServiceKind || t("consul.ui.standard") }}</div>
+ </div>
+ <div class="border-b px-3 py-2 sm:border-r">
+ <div class="text-muted-foreground">{{ t("consul.ui.indexes") }}</div>
+ <div class="mt-1 font-mono">{{ item.CreateIndex }} / {{ item.ModifyIndex }}</div>
+ </div>
+ <div class="border-b px-3 py-2 sm:border-r">
+ <div class="text-muted-foreground">{{ t("consul.ui.serviceWeights") }}</div>
+ <div class="mt-1 font-mono">{{ item.ServiceWeights.Passing }} / {{ item.ServiceWeights.Warning }}</div>
+ </div>
+ <div class="border-b px-3 py-2">
+ <div class="text-muted-foreground">{{ t("consul.ui.nodeId") }}</div>
+ <div class="mt-1 truncate font-mono" :title="item.ID">{{ item.ID || "-" }}</div>
+ </div>
+ <div class="border-b px-3 py-2 sm:col-span-4">
+ <div class="text-muted-foreground">{{ t("consul.ui.nodeMeta") }}</div>
+ <div class="mt-1 flex flex-wrap gap-1.5">
+ <code v-for="[key, value] in Object.entries(item.NodeMeta)" :key="key" class="rounded bg-muted px-1.5 py-0.5">{{ key }}={{ value }}</code
+ ><span v-if="!Object.keys(item.NodeMeta).length">-</span>
+ </div>
+ </div>
+ <div class="px-3 py-2 sm:col-span-4">
+ <div class="text-muted-foreground">{{ t("consul.ui.serviceMeta") }}</div>
+ <div class="mt-1 flex flex-wrap gap-1.5">
+ <code v-for="[key, value] in Object.entries(item.ServiceMeta)" :key="key" class="rounded bg-muted px-1.5 py-0.5">{{ key }}={{ value }}</code
+ ><span v-if="!Object.keys(item.ServiceMeta).length">-</span>
+ </div>
+ </div>
+ </div>
+ </td>
+ </tr>
+ </template>
+ <tr v-if="!instances.length && !loading">
+ <td colspan="5" class="px-3 py-8 text-center text-muted-foreground">{{ t("consul.ui.noVisibleServices") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div v-else class="p-3 text-xs">
+ <div class="mb-3 flex flex-wrap gap-2 text-muted-foreground">
+ <Badge variant="outline">{{ nodeServices?.Node.Address || "-" }}</Badge
+ ><Badge variant="outline">{{ nodeServices?.Node.Datacenter || "-" }}</Badge>
+ </div>
+ <div
+ class="mb-3 rounded-md bg-muted/30 px-2.5 py-2 text-muted-foreground"
+ :title="
+ Object.entries(nodeServices?.Node.NodeMeta || {})
+ .map(([key, value]) => `${key}=${value}`)
+ .join(', ')
+ "
+ >
+ {{ t("consul.ui.nodeMeta") }} ·
+ {{
+ Object.entries(nodeServices?.Node.NodeMeta || {})
+ .map(([key, value]) => `${key}=${value}`)
+ .join(", ") || "-"
+ }}
+ </div>
+ <div v-for="service in pagedNodeServices" :key="service.ID" class="border-t first:border-t-0">
+ <button type="button" class="w-full px-1 py-2.5 text-left outline-none hover:bg-muted/20 focus-visible:bg-muted/30" :class="selectedNodeServiceId === service.ID && 'bg-muted/20'" :aria-expanded="selectedNodeServiceId === service.ID" @click="toggleNodeService(service.ID)">
+ <span class="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1"
+ ><span class="font-medium">{{ service.Service }}</span
+ ><code class="text-muted-foreground">{{ service.ID }}</code
+ ><span class="font-mono text-muted-foreground">{{ service.Address || nodeServices?.Node.Address }}:{{ service.Port }}</span></span
+ >
+ <span
+ class="mt-1 block truncate text-muted-foreground"
+ :title="
+ Object.entries(service.Meta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(', ')
+ "
+ >{{ t("consul.ui.serviceMeta") }} ·
+ {{
+ Object.entries(service.Meta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(", ") || "-"
+ }}</span
+ >
+ </button>
+ <div v-if="selectedNodeServiceId === service.ID" class="pb-3">
+ <div class="grid overflow-hidden rounded-md border bg-background sm:grid-cols-2">
+ <div class="border-b px-3 py-2 sm:border-r">
+ <div class="text-muted-foreground">{{ t("consul.ui.serviceWeights") }}</div>
+ <div class="mt-1 font-mono">{{ service.Weights.Passing }} / {{ service.Weights.Warning }}</div>
+ </div>
+ <div class="border-b px-3 py-2">
+ <div class="text-muted-foreground">{{ t("consul.ui.tags") }}</div>
+ <div class="mt-1 flex flex-wrap gap-1">
+ <Badge v-for="tag in service.Tags" :key="tag" variant="outline" class="h-5 px-1.5 text-[10px]">{{ tag }}</Badge
+ ><span v-if="!service.Tags.length">-</span>
+ </div>
+ </div>
+ <div class="border-b px-3 py-2 sm:col-span-2">
+ <div class="text-muted-foreground">{{ t("consul.ui.serviceMeta") }}</div>
+ <div class="mt-1 flex flex-wrap gap-1.5">
+ <code v-for="[key, value] in Object.entries(service.Meta)" :key="key" class="rounded bg-muted px-1.5 py-0.5">{{ key }}={{ value }}</code
+ ><span v-if="!Object.keys(service.Meta).length">-</span>
+ </div>
+ </div>
+ <div class="px-3 py-2 sm:col-span-2">
+ <div class="text-muted-foreground">{{ t("consul.ui.taggedAddresses") }}</div>
+ <div class="mt-1 flex flex-wrap gap-1.5">
+ <code v-for="[key, value] in Object.entries(service.TaggedAddresses)" :key="key" class="rounded bg-muted px-1.5 py-0.5">{{ key }}={{ value.Address }}:{{ value.Port }}</code
+ ><span v-if="!Object.keys(service.TaggedAddresses).length">-</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-if="!Object.keys(nodeServices?.Services || {}).length && !loading" class="py-6 text-center text-muted-foreground">{{ t("consul.ui.noVisibleServices") }}</div>
+ </div>
+ </section>
+
+ <section class="overflow-hidden rounded-lg border">
+ <div class="flex flex-wrap items-center gap-3 border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex shrink-0 items-center gap-2 text-sm font-medium">
+ <span>{{ t("consul.ui.localAgentServices") }}</span
+ ><Badge variant="secondary">{{ localServiceFilter.trim() ? `${filteredLocalServiceItems.length} / ${localServiceItems.length}` : localServiceItems.length }}</Badge>
+ </div>
+ <div class="relative min-w-52 flex-1 sm:max-w-md">
+ <Search class="pointer-events-none absolute left-2.5 top-2 h-3.5 w-3.5 text-muted-foreground" />
+ <Input v-model="localServiceFilter" class="h-7 pl-8 text-xs" :placeholder="t('consul.ui.searchLocalServices')" />
+ </div>
+ <div class="ml-auto flex shrink-0 items-center gap-3">
+ <ConsulListPagination :total="filteredLocalServiceItems.length" :page="localServicePage" :page-size="CONSUL_LIST_PAGE_SIZE" @update:page="updateLocalServicePage" />
+ <Badge :variant="agentTargetStatus === 'writable' ? 'secondary' : 'outline'" :class="agentTargetStatus === 'writable' ? 'text-emerald-700 dark:text-emerald-300' : 'text-muted-foreground'"
+ ><Loader2 v-if="agentTargetStatus === 'verifying'" class="mr-1 h-3 w-3 animate-spin" /><CircleCheck v-else-if="agentTargetStatus === 'writable'" class="mr-1 h-3 w-3" /><LockKeyhole v-else class="mr-1 h-3 w-3" />{{
+ agentTargetStatus === "verifying" ? t("consul.ui.agentTargetVerifying") : agentTargetStatus === "writable" ? t("consul.ui.agentWriteReady") : t("consul.ui.agentReadOnly")
+ }}</Badge
+ >
+ </div>
+ </div>
+ <div v-if="!canAgentWrite && (identity || !agentLoading)" class="flex items-start gap-2 border-b border-amber-300/70 bg-amber-50/70 px-3 py-2 text-xs text-amber-800 dark:bg-amber-950/20 dark:text-amber-200">
+ <LockKeyhole class="mt-0.5 h-3.5 w-3.5 shrink-0" /><span>{{ t("consul.ui.agentWriteDisabledHint", { target: identity ? `${identity.node} (${identity.address})` : t("consul.ui.unknownWritesDisabled") }) }}</span>
+ </div>
+ <div v-for="service in pagedLocalServices" :key="service.ID" class="border-b last:border-0" :class="selectedLocalService?.ID === service.ID && 'bg-muted/20'">
+ <div class="grid gap-3 px-3 py-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center">
+ <button type="button" class="flex min-w-0 items-start gap-3 text-left" :aria-expanded="selectedLocalService?.ID === service.ID" @click="openLocalService(service.ID)">
+ <span class="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted"><ServerCog class="h-4 w-4 text-muted-foreground" /></span
+ ><span class="min-w-0 flex-1"
+ ><span class="flex min-w-0 flex-wrap items-center gap-2"
+ ><span class="truncate font-medium">{{ service.Service }}</span
+ ><code class="rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">{{ service.ID }}</code
+ ><Badge v-if="isServiceInMaintenance(service.ID)" variant="outline" class="h-5 border-amber-500/50 px-1.5 text-[10px] text-amber-700 dark:text-amber-300"><Wrench class="mr-1 h-3 w-3" />{{ t("consul.ui.maintenance") }}</Badge></span
+ ><span class="mt-1 flex min-w-0 flex-wrap items-center gap-1.5 text-xs text-muted-foreground"
+ ><span class="font-mono">{{ service.Address || identity?.address }}:{{ service.Port }}</span
+ ><Badge v-for="tag in service.Tags" :key="tag" variant="outline" class="h-5 px-1.5 text-[10px]">{{ tag }}</Badge></span
+ ></span
+ >
+ </button>
+ <div v-if="canAgentWrite" class="flex shrink-0 items-center gap-1 lg:border-l lg:pl-3">
+ <Button v-if="!isServiceInMaintenance(service.ID)" size="sm" variant="ghost" class="h-7 gap-1 px-2 text-xs" :disabled="maintenancePendingId === service.ID" :title="t('consul.ui.enableMaintenance')" @click.stop="maintenance(service.ID, true)"
+ ><Loader2 v-if="maintenancePendingId === service.ID" class="h-3.5 w-3.5 animate-spin" /><Wrench v-else class="h-3.5 w-3.5" />{{ t("consul.ui.enableMaintenance") }}</Button
+ ><Button v-else size="sm" variant="ghost" class="h-7 gap-1 px-2 text-xs text-amber-700 hover:text-amber-700 dark:text-amber-300" :disabled="maintenancePendingId === service.ID" :title="t('consul.ui.disableMaintenance')" @click.stop="maintenance(service.ID, false)"
+ ><Loader2 v-if="maintenancePendingId === service.ID" class="h-3.5 w-3.5 animate-spin" /><CircleCheck v-else class="h-3.5 w-3.5" />{{ t("consul.ui.disableMaintenance") }}</Button
+ ><Button size="sm" variant="ghost" class="h-7 gap-1 px-2 text-xs text-destructive hover:text-destructive" :title="t('consul.ui.deregister')" @click.stop="deregister(service.ID)"><Trash2 class="h-3.5 w-3.5" />{{ t("consul.ui.deregister") }}</Button>
+ </div>
+ </div>
+ <div v-if="selectedLocalService?.ID === service.ID" class="border-t bg-background px-4 py-3 text-xs">
+ <dl class="grid overflow-hidden rounded-md border sm:grid-cols-4">
+ <div class="border-b px-3 py-2 sm:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.kind") }}</dt>
+ <dd class="mt-1 font-medium">{{ selectedLocalService.Kind || t("consul.ui.standard") }}</dd>
+ </div>
+ <div class="border-b px-3 py-2 sm:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.datacenter") }}</dt>
+ <dd class="mt-1 font-medium">{{ selectedLocalService.Datacenter || "-" }}</dd>
+ </div>
+ <div class="border-b px-3 py-2 sm:border-r">
+ <dt class="text-muted-foreground">{{ t("consul.ui.enableTagOverride") }}</dt>
+ <dd class="mt-1 font-mono">{{ selectedLocalService.EnableTagOverride }}</dd>
+ </div>
+ <div class="border-b px-3 py-2">
+ <dt class="text-muted-foreground">{{ t("consul.ui.serviceWeights") }}</dt>
+ <dd class="mt-1 font-mono">{{ selectedLocalService.Weights.Passing }} / {{ selectedLocalService.Weights.Warning }}</dd>
+ </div>
+ <div class="px-3 py-2 sm:col-span-4">
+ <dt class="text-muted-foreground">{{ t("consul.ui.metadata") }}</dt>
+ <dd class="mt-1 break-words font-mono">
+ {{
+ Object.entries(selectedLocalService.Meta)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(", ") || "-"
+ }}
+ </dd>
+ </div>
+ </dl>
+ </div>
+ </div>
+ <div v-if="!localServiceItems.length && agentLoading" class="px-3 py-8 text-center text-xs text-muted-foreground">{{ t("consul.ui.loading") }}</div>
+ <div v-else-if="!localServiceItems.length" class="flex flex-col items-center gap-2 px-3 py-8 text-center text-xs text-muted-foreground">
+ <span>{{ t("consul.ui.noResources") }}</span
+ ><Button size="sm" variant="outline" class="h-7" @click="loadAgentData()"><RefreshCcw class="mr-1 h-3.5 w-3.5" />{{ t("consul.ui.refresh") }}</Button>
+ </div>
+ <div v-else-if="!filteredLocalServiceItems.length" class="px-3 py-8 text-center text-xs text-muted-foreground">{{ t("consul.ui.noMatchingServices") }}</div>
+ </section>
+ </main>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulSessions.vue b/apps/desktop/src/components/consul/ConsulSessions.vue
new file mode 100644
index 0000000000..c621c0f161
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulSessions.vue
@@ -0,0 +1,648 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from "vue";
+import { AlertTriangle, ChevronDown, ChevronUp, Clock3, KeyRound, Loader2, Plus, RefreshCcw, RotateCw, Search, ShieldCheck, Trash2 } from "@lucide/vue";
+import ConsulListPagination from "@/components/consul/ConsulListPagination.vue";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import * as api from "@/lib/backend/api";
+import { clampConsulPage, CONSUL_LIST_PAGE_SIZE, paginateConsulItems } from "@/lib/consul/pagination";
+import { consulSessionRenewDelayMs, parseConsulDurationMs } from "@/lib/consul/sessionRenew";
+import { normalizeConsulSession } from "@/lib/consul/sessionModel";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useConsulStore } from "@/stores/consulStore";
+import { useI18n } from "vue-i18n";
+import type { ConsulResponseMetadata, ConsulSession, ConsulSessionKeysResponse, ConsulSessionServiceCheck } from "@/types/consul";
+
+const props = defineProps<{ connectionId: string }>();
+const { t } = useI18n();
+const store = useConnectionStore();
+const consulStore = useConsulStore();
+const readOnly = computed(() => Boolean(store.getConfig(props.connectionId)?.read_only));
+function behaviorLabel(behavior: string) {
+ if (behavior === "delete") return t("consul.ui.behaviorDelete");
+ if (behavior === "release") return t("consul.ui.behaviorRelease");
+ return behavior || t("consul.ui.unknown");
+}
+const connectionActive = computed(() => store.connectedIds.has(props.connectionId));
+
+const sessions = ref<ConsulSession[]>([]);
+const responseMetadata = ref<ConsulResponseMetadata | null>(null);
+const loading = ref(false);
+const saving = ref(false);
+const error = ref("");
+const createOpen = ref(false);
+const lockOpen = ref(false);
+const expandedSessionId = ref("");
+const heldKeys = ref<Record<string, ConsulSessionKeysResponse>>({});
+const heldKeysLoading = ref("");
+
+const search = ref("");
+const ttlFilter = ref<"any" | "ttl" | "persistent">("any");
+const behaviorFilter = ref<"any" | "release" | "delete">("any");
+const page = ref(1);
+
+const createForm = ref({
+ name: "",
+ node: "",
+ ttl: "30s",
+ lockDelay: "15s",
+ behavior: "release" as "release" | "delete",
+ nodeChecks: "serfHealth",
+ serviceChecks: "",
+});
+const lockForm = ref({ key: "", session: "", value: "" });
+const lockInspection = ref<{ inspected: boolean; found: boolean; modifyIndex: string; owner: string; flags: string }>({ inspected: false, found: false, modifyIndex: "0", owner: "", flags: "0" });
+const lockInspecting = ref(false);
+
+const autoRenewId = ref("");
+let renewTimer: ReturnType<typeof setTimeout> | undefined;
+let renewContext = "";
+let sequence = 0;
+
+const filteredSessions = computed(() => {
+ const keyword = search.value.trim().toLocaleLowerCase();
+ return sessions.value.filter((session) => {
+ if (ttlFilter.value === "ttl" && !session.TTL.trim()) return false;
+ if (ttlFilter.value === "persistent" && session.TTL.trim()) return false;
+ if (behaviorFilter.value !== "any" && session.Behavior !== behaviorFilter.value) return false;
+ if (!keyword) return true;
+ const checks = [...session.NodeChecks, ...session.ServiceChecks.flatMap((check) => [check.ID, check.Namespace])];
+ return [session.Name, session.ID, session.Node, session.TTL, session.Behavior, ...checks].join("\n").toLocaleLowerCase().includes(keyword);
+ });
+});
+const pagedSessions = computed(() => paginateConsulItems(filteredSessions.value, page.value));
+const hasFilters = computed(() => Boolean(search.value.trim()) || ttlFilter.value !== "any" || behaviorFilter.value !== "any");
+
+function message(value: unknown) {
+ return value instanceof Error ? value.message : String(value);
+}
+
+async function withUiTimeout<T>(operation: Promise<T>, milliseconds = 15_000): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ operation,
+ new Promise<T>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(t("consul.ui.sessionRequestTimedOut"))), milliseconds);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
+function currentScopeKey() {
+ const external = store.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ return [config.datacenter || config.consulDatacenter || config.consul_datacenter, config.namespace || config.consulNamespace || config.consul_namespace, config.partition || config.consulPartition || config.consul_partition].map((value) => String(value || "")).join("\u0000");
+}
+
+function currentRenewContext() {
+ return `${props.connectionId}\u0000${consulStore.generation}\u0000${currentScopeKey()}`;
+}
+
+function isTtlSession(session: ConsulSession) {
+ return Boolean(session.TTL.trim());
+}
+
+function formatLockDelay(value: number) {
+ const seconds = value / 1_000_000_000;
+ return Number.isInteger(seconds) ? `${seconds}s` : `${seconds.toFixed(3).replace(/0+$/, "").replace(/\.$/, "")}s`;
+}
+
+function sessionChecks(session: ConsulSession) {
+ const nodeChecks = session.NodeChecks.map((check) => `${t("consul.ui.nodeCheckShort")}: ${check}`);
+ const serviceChecks = session.ServiceChecks.map((check) => `${t("consul.ui.serviceCheckShort")}: ${check.ID}${check.Namespace ? ` @ ${check.Namespace}` : ""}`);
+ return [...nodeChecks, ...serviceChecks];
+}
+
+function parseServiceChecks(value: string): ConsulSessionServiceCheck[] {
+ return value
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean)
+ .map((part) => {
+ const [id, namespace = ""] = part.split("@", 2).map((item) => item.trim());
+ return { ID: id, Namespace: namespace };
+ });
+}
+
+function validateCreateForm() {
+ const ttl = createForm.value.ttl.trim();
+ const ttlMs = ttl ? parseConsulDurationMs(ttl) : null;
+ if (ttl && (ttlMs === null || ttlMs < 10_000 || ttlMs > 86_400_000)) {
+ return t("consul.ui.invalidSessionTtl");
+ }
+ const delay = createForm.value.lockDelay.trim();
+ const delayMs = delay ? parseConsulDurationMs(delay) : null;
+ if (delay && (delayMs === null || delayMs < 0 || delayMs > 60_000)) {
+ return t("consul.ui.invalidLockDelay");
+ }
+ return "";
+}
+
+async function load() {
+ const current = ++sequence;
+ loading.value = true;
+ error.value = "";
+ try {
+ const value = await withUiTimeout(api.consulSessions(props.connectionId));
+ if (current !== sequence) return;
+ sessions.value = value.items.map(normalizeConsulSession);
+ responseMetadata.value = value.metadata;
+ page.value = clampConsulPage(page.value, filteredSessions.value.length);
+ if (autoRenewId.value && !sessions.value.some((session) => session.ID === autoRenewId.value)) stopAutoRenew();
+ if (!lockForm.value.session && sessions.value.length) lockForm.value.session = sessions.value[0].ID;
+ } catch (value) {
+ if (current === sequence) error.value = message(value);
+ } finally {
+ if (current === sequence) loading.value = false;
+ }
+}
+
+async function createSession() {
+ if (readOnly.value) return;
+ const validation = validateCreateForm();
+ if (validation) {
+ error.value = validation;
+ return;
+ }
+ if (createForm.value.behavior === "delete" && !window.confirm(t("consul.ui.deleteBehaviorWarning"))) return;
+ saving.value = true;
+ error.value = "";
+ try {
+ const created = await api.consulCreateSession(props.connectionId, {
+ name: createForm.value.name,
+ node: createForm.value.node,
+ ttl: createForm.value.ttl.trim() || null,
+ lockDelay: createForm.value.lockDelay.trim() || null,
+ behavior: createForm.value.behavior,
+ nodeChecks: createForm.value.nodeChecks
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean),
+ serviceChecks: parseServiceChecks(createForm.value.serviceChecks),
+ });
+ createOpen.value = false;
+ await load();
+ expandedSessionId.value = created.ID;
+ } catch (value) {
+ error.value = message(value);
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function renew(id: string) {
+ const session = sessions.value.find((item) => item.ID === id);
+ if (!session || !isTtlSession(session)) {
+ error.value = t("consul.ui.noRenewRequired");
+ stopAutoRenew();
+ return false;
+ }
+ if (readOnly.value || !connectionActive.value) {
+ stopAutoRenew();
+ return false;
+ }
+ try {
+ const renewed = await api.consulRenewSession(props.connectionId, id);
+ const index = sessions.value.findIndex((item) => item.ID === id);
+ if (index >= 0) sessions.value[index] = renewed;
+ return true;
+ } catch (value) {
+ error.value = message(value);
+ stopAutoRenew();
+ return false;
+ }
+}
+
+async function destroy(id: string) {
+ if (readOnly.value) return;
+ try {
+ const impact = await api.consulSessionDestroyImpact(props.connectionId, id);
+ if (!impact.complete) {
+ error.value = t("consul.ui.sessionImpactIncomplete");
+ return;
+ }
+ const keys = impact.heldKeys.map((item) => item.key).join(", ") || t("consul.ui.noHeldKeys");
+ if (
+ !window.confirm(
+ t("consul.ui.destroySessionImpact", {
+ id,
+ behavior: impact.session.Behavior,
+ count: impact.heldKeys.length,
+ keys,
+ }),
+ )
+ )
+ return;
+ await api.consulDestroySession(props.connectionId, {
+ id,
+ expectedBehavior: impact.session.Behavior,
+ expectedHeldKeys: impact.heldKeys,
+ });
+ if (autoRenewId.value === id) stopAutoRenew();
+ delete heldKeys.value[id];
+ if (expandedSessionId.value === id) expandedSessionId.value = "";
+ await load();
+ } catch (value) {
+ error.value = message(value);
+ }
+}
+
+function toggleDetails(id: string) {
+ expandedSessionId.value = expandedSessionId.value === id ? "" : id;
+}
+
+async function toggleHeldKeys(id: string) {
+ if (expandedSessionId.value === id && heldKeys.value[id]) {
+ expandedSessionId.value = "";
+ return;
+ }
+ expandedSessionId.value = id;
+ heldKeysLoading.value = id;
+ try {
+ heldKeys.value[id] = await api.consulSessionKeys(props.connectionId, id);
+ } catch (value) {
+ error.value = message(value);
+ } finally {
+ if (heldKeysLoading.value === id) heldKeysLoading.value = "";
+ }
+}
+
+function scheduleAutoRenew(id: string) {
+ const session = sessions.value.find((item) => item.ID === id);
+ if (!session || !isTtlSession(session) || readOnly.value || !connectionActive.value || renewContext !== currentRenewContext()) {
+ stopAutoRenew();
+ return;
+ }
+ renewTimer = setTimeout(async () => {
+ renewTimer = undefined;
+ if (autoRenewId.value !== id || renewContext !== currentRenewContext()) {
+ stopAutoRenew();
+ return;
+ }
+ if (await renew(id)) scheduleAutoRenew(id);
+ }, consulSessionRenewDelayMs(session.TTL));
+}
+
+function startAutoRenew(id: string) {
+ stopAutoRenew();
+ const session = sessions.value.find((item) => item.ID === id);
+ if (!session || !isTtlSession(session) || !connectionActive.value) return;
+ autoRenewId.value = id;
+ renewContext = currentRenewContext();
+ scheduleAutoRenew(id);
+}
+
+function stopAutoRenew() {
+ if (renewTimer) clearTimeout(renewTimer);
+ renewTimer = undefined;
+ renewContext = "";
+ autoRenewId.value = "";
+}
+
+function resetLockInspection() {
+ lockInspection.value = { inspected: false, found: false, modifyIndex: "0", owner: "", flags: "0" };
+}
+
+async function inspectLockKey() {
+ const key = lockForm.value.key.trim();
+ if (!key) {
+ resetLockInspection();
+ return false;
+ }
+ lockInspecting.value = true;
+ error.value = "";
+ try {
+ const result = await api.consulGet(props.connectionId, key);
+ lockInspection.value = {
+ inspected: true,
+ found: result.found,
+ modifyIndex: String(result.metadata?.modRevision ?? 0),
+ owner: String(result.metadata?.session ?? ""),
+ flags: String(result.metadata?.flags ?? 0),
+ };
+ return true;
+ } catch (value) {
+ error.value = message(value);
+ return false;
+ } finally {
+ lockInspecting.value = false;
+ }
+}
+
+async function acquire() {
+ if (readOnly.value || !lockForm.value.key.trim() || !lockForm.value.session) return;
+ saving.value = true;
+ try {
+ if (!(await inspectLockKey())) return;
+ if (lockInspection.value.owner && lockInspection.value.owner !== lockForm.value.session) {
+ error.value = t("consul.ui.keyHeldBy", { session: lockInspection.value.owner });
+ return;
+ }
+ await api.consulAcquireLock(props.connectionId, {
+ key: lockForm.value.key.trim(),
+ session: lockForm.value.session,
+ value: { encoding: "utf8", data: lockForm.value.value },
+ flags: null,
+ expectedModifyIndex: lockInspection.value.modifyIndex,
+ });
+ await inspectLockKey();
+ delete heldKeys.value[lockForm.value.session];
+ expandedSessionId.value = "";
+ await toggleHeldKeys(lockForm.value.session);
+ await load();
+ } catch (value) {
+ error.value = message(value);
+ } finally {
+ saving.value = false;
+ }
+}
+
+async function release() {
+ if (readOnly.value || !lockForm.value.key.trim() || !lockForm.value.session) return;
+ saving.value = true;
+ try {
+ if (!(await inspectLockKey())) return;
+ if (!lockInspection.value.found) {
+ error.value = t("consul.ui.keyNotFound");
+ return;
+ }
+ if (lockInspection.value.owner !== lockForm.value.session) {
+ error.value = lockInspection.value.owner ? t("consul.ui.keyHeldBy", { session: lockInspection.value.owner }) : t("consul.ui.keyUnlocked");
+ return;
+ }
+ await api.consulReleaseLock(props.connectionId, lockForm.value.key.trim(), lockForm.value.session);
+ await inspectLockKey();
+ delete heldKeys.value[lockForm.value.session];
+ await load();
+ } catch (value) {
+ error.value = message(value);
+ } finally {
+ saving.value = false;
+ }
+}
+
+function clearFilters() {
+ search.value = "";
+ ttlFilter.value = "any";
+ behaviorFilter.value = "any";
+}
+
+watch(
+ () => props.connectionId,
+ () => {
+ stopAutoRenew();
+ expandedSessionId.value = "";
+ heldKeys.value = {};
+ resetLockInspection();
+ void load();
+ },
+);
+watch(
+ () => [consulStore.generation, currentScopeKey(), connectionActive.value, readOnly.value] as const,
+ () => stopAutoRenew(),
+);
+watch([search, ttlFilter, behaviorFilter], () => {
+ page.value = 1;
+});
+watch(() => lockForm.value.key, resetLockInspection);
+onMounted(load);
+onDeactivated(stopAutoRenew);
+onBeforeUnmount(stopAutoRenew);
+defineExpose({ refresh: () => (void load(), true) });
+</script>
+
+<template>
+ <div class="h-full overflow-auto p-4">
+ <header class="mb-4 flex flex-wrap items-start justify-between gap-3 border-b pb-4">
+ <div>
+ <h2 class="text-base font-semibold">{{ t("consul.ui.sessionsAndLocks") }}</h2>
+ <p class="mt-1 max-w-3xl text-xs leading-5 text-muted-foreground">{{ t("consul.ui.sessionDescription") }}</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button size="icon" variant="outline" class="h-8 w-8" :disabled="loading" :title="t('consul.ui.refresh')" @click="load">
+ <RefreshCcw class="h-3.5 w-3.5" :class="loading && 'animate-spin'" />
+ </Button>
+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="readOnly" @click="lockOpen = !lockOpen"> <KeyRound class="h-3.5 w-3.5" />{{ t("consul.ui.lock") }} </Button>
+ <Button size="sm" class="h-8 gap-1.5" :disabled="readOnly" @click="createOpen = !createOpen"> <Plus class="h-3.5 w-3.5" />{{ t("consul.ui.create") }} </Button>
+ </div>
+ </header>
+
+ <div v-if="error" class="mb-3 rounded-md border border-destructive/30 bg-destructive/5 p-2.5 text-xs text-destructive">{{ error }}</div>
+
+ <section v-if="createOpen" class="mb-4 overflow-hidden rounded-lg border">
+ <div class="border-b bg-muted/30 px-4 py-3 text-sm font-medium">{{ t("consul.ui.createSession") }}</div>
+ <div class="grid gap-x-4 gap-y-3 p-4 md:grid-cols-2 xl:grid-cols-3">
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.name") }}</Label
+ ><Input v-model="createForm.name" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.nodeOptional") }}</Label
+ ><Input v-model="createForm.node" class="h-9" />
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.ttlOptional") }}</Label
+ ><Input v-model="createForm.ttl" class="h-9" placeholder="30s" />
+ <p class="text-[11px] text-muted-foreground">{{ t("consul.ui.ttlRangeHint") }}</p>
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.lockDelay") }}</Label
+ ><Input v-model="createForm.lockDelay" class="h-9" placeholder="15s" />
+ <p class="text-[11px] text-muted-foreground">{{ t("consul.ui.lockDelayHint") }}</p>
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.behavior") }}</Label
+ ><select v-model="createForm.behavior" class="h-9 w-full rounded-md border bg-background px-2 text-sm">
+ <option value="release">{{ t("consul.ui.releaseLocks") }}</option>
+ <option value="delete">{{ t("consul.ui.deleteKeys") }}</option>
+ </select>
+ <p class="text-[11px] text-muted-foreground">{{ t("consul.ui.behaviorHint") }}</p>
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.nodeChecks") }}</Label
+ ><Input v-model="createForm.nodeChecks" class="h-9" placeholder="serfHealth" />
+ </div>
+ <div class="space-y-1.5 md:col-span-2 xl:col-span-3">
+ <Label class="text-xs">{{ t("consul.ui.serviceChecks") }}</Label
+ ><Input v-model="createForm.serviceChecks" class="h-9" :placeholder="t('consul.ui.serviceChecksPlaceholder')" />
+ <p class="text-[11px] text-muted-foreground">{{ t("consul.ui.serviceChecksHint") }}</p>
+ </div>
+ </div>
+ <div class="flex justify-end gap-2 border-t bg-muted/20 px-4 py-3">
+ <Button size="sm" variant="outline" @click="createOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button size="sm" :disabled="saving" @click="createSession"><Loader2 v-if="saving" class="mr-1 h-3.5 w-3.5 animate-spin" />{{ t("consul.ui.create") }}</Button>
+ </div>
+ </section>
+
+ <section v-if="lockOpen" class="mb-4 overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between border-b bg-muted/30 px-4 py-3">
+ <span class="text-sm font-medium">{{ t("consul.ui.lockManagement") }}</span
+ ><span class="text-xs text-muted-foreground">{{ t("consul.ui.lockHint") }}</span>
+ </div>
+ <div class="grid gap-x-4 gap-y-3 p-4 md:grid-cols-2">
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.key") }}</Label>
+ <div class="flex gap-2">
+ <Input v-model="lockForm.key" class="h-9" @keydown.enter="inspectLockKey" /><Button size="sm" variant="outline" class="h-9 shrink-0" :disabled="lockInspecting || !lockForm.key.trim()" @click="inspectLockKey"
+ ><Loader2 v-if="lockInspecting" class="mr-1 h-3.5 w-3.5 animate-spin" />{{ t("consul.ui.inspectKey") }}</Button
+ >
+ </div>
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("consul.ui.selectSession") }}</Label
+ ><select v-model="lockForm.session" class="h-9 w-full rounded-md border bg-background px-2 text-sm">
+ <option value="" disabled>{{ t("consul.ui.selectSession") }}</option>
+ <option v-for="session in sessions" :key="session.ID" :value="session.ID">{{ session.Name || t("consul.ui.unnamedSession") }} · {{ session.ID }}</option>
+ </select>
+ </div>
+ <div class="space-y-1.5 md:col-span-2">
+ <Label class="text-xs">{{ t("consul.ui.value") }}</Label
+ ><textarea v-model="lockForm.value" class="min-h-20 w-full resize-y rounded-md border bg-background px-3 py-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring" />
+ </div>
+ <div v-if="lockInspection.inspected" class="md:col-span-2 flex flex-wrap items-center gap-2 rounded-md border bg-muted/20 px-3 py-2 text-xs">
+ <Badge variant="secondary">{{ lockInspection.found ? t("consul.ui.keyExists") : t("consul.ui.keyNotFound") }}</Badge>
+ <span>{{ t("consul.ui.modifyIndexValue", { index: lockInspection.modifyIndex }) }}</span>
+ <span v-if="lockInspection.owner" class="text-amber-700 dark:text-amber-300">{{ t("consul.ui.keyHeldBy", { session: lockInspection.owner }) }}</span>
+ <span v-else-if="lockInspection.found" class="text-muted-foreground">{{ t("consul.ui.keyUnlocked") }}</span>
+ </div>
+ </div>
+ <div class="flex justify-end gap-2 border-t bg-muted/20 px-4 py-3">
+ <Button size="sm" variant="outline" @click="lockOpen = false">{{ t("consul.ui.close") }}</Button
+ ><Button size="sm" variant="outline" :disabled="saving || !lockForm.key.trim() || !lockForm.session" @click="release">{{ t("consul.ui.releaseMatchingSession") }}</Button
+ ><Button size="sm" :disabled="saving || !lockForm.key.trim() || !lockForm.session" @click="acquire">{{ t("consul.ui.acquire") }}</Button>
+ </div>
+ </section>
+
+ <section class="mb-4 rounded-lg border bg-muted/10 p-3">
+ <div class="flex flex-wrap items-center gap-2">
+ <div class="relative min-w-64 flex-1"><Search class="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /><Input v-model="search" class="h-9 pl-8" :placeholder="t('consul.ui.searchSessions')" /></div>
+ <select v-model="ttlFilter" class="h-9 rounded-md border bg-background px-2 text-xs">
+ <option value="any">{{ t("consul.ui.allSessionTypes") }}</option>
+ <option value="ttl">{{ t("consul.ui.ttlSessions") }}</option>
+ <option value="persistent">{{ t("consul.ui.persistentSessions") }}</option>
+ </select>
+ <select v-model="behaviorFilter" class="h-9 rounded-md border bg-background px-2 text-xs">
+ <option value="any">{{ t("consul.ui.allBehaviors") }}</option>
+ <option value="release">{{ t("consul.ui.behaviorRelease") }}</option>
+ <option value="delete">{{ t("consul.ui.behaviorDelete") }}</option>
+ </select>
+ <Button v-if="hasFilters" size="sm" variant="ghost" class="h-9" @click="clearFilters">{{ t("consul.ui.clearFilters") }}</Button>
+ </div>
+ <div class="mt-2 flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
+ <span>{{ t("consul.ui.sessionResultCount", { filtered: filteredSessions.length, total: sessions.length }) }}</span>
+ <span v-if="responseMetadata?.filteredByAcls" class="inline-flex items-center gap-1 text-amber-700 dark:text-amber-300"><AlertTriangle class="h-3.5 w-3.5" />{{ t("consul.ui.aclFilteredSessions") }}</span>
+ </div>
+ </section>
+
+ <section class="overflow-hidden rounded-lg border">
+ <div class="flex items-center justify-between border-b bg-muted/30 px-3 py-2.5">
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <span>{{ t("consul.ui.sessions") }}</span
+ ><Badge variant="secondary">{{ filteredSessions.length }}</Badge>
+ </div>
+ <ConsulListPagination
+ :total="filteredSessions.length"
+ :page="page"
+ :page-size="CONSUL_LIST_PAGE_SIZE"
+ @update:page="
+ page = $event;
+ expandedSessionId = '';
+ "
+ />
+ </div>
+
+ <div v-for="session in pagedSessions" :key="session.ID" class="border-b last:border-0">
+ <div class="grid cursor-pointer items-center gap-3 px-3 py-3 text-xs transition-colors hover:bg-muted/20 md:grid-cols-[minmax(0,1.4fr)_minmax(7rem,.7fr)_minmax(9rem,.8fr)_auto]" @click="toggleDetails(session.ID)">
+ <div class="flex min-w-0 items-center gap-2.5">
+ <Button size="icon" variant="ghost" class="h-7 w-7 shrink-0" tabindex="-1"><ChevronUp v-if="expandedSessionId === session.ID" class="h-3.5 w-3.5" /><ChevronDown v-else class="h-3.5 w-3.5" /></Button>
+ <div class="min-w-0">
+ <div class="truncate text-sm font-medium">{{ session.Name || t("consul.ui.unnamedSession") }}</div>
+ <div class="truncate font-mono text-[11px] text-muted-foreground">{{ session.ID }}</div>
+ </div>
+ </div>
+ <div class="min-w-0">
+ <div class="truncate font-medium">{{ session.Node || "—" }}</div>
+ <div class="truncate text-muted-foreground">{{ session.Namespace || t("consul.ui.default") }} / {{ session.Partition || t("consul.ui.default") }}</div>
+ </div>
+ <div class="flex flex-wrap items-center gap-1.5">
+ <Badge :variant="isTtlSession(session) ? 'default' : 'secondary'"><Clock3 class="mr-1 h-3 w-3" />{{ isTtlSession(session) ? session.TTL : t("consul.ui.noTtl") }}</Badge
+ ><Badge variant="outline">{{ behaviorLabel(session.Behavior) }}</Badge>
+ </div>
+ <div class="flex items-center justify-end gap-1" @click.stop>
+ <Button size="sm" variant="ghost" class="h-7 gap-1" :disabled="heldKeysLoading === session.ID" @click="toggleHeldKeys(session.ID)"
+ ><Loader2 v-if="heldKeysLoading === session.ID" class="h-3.5 w-3.5 animate-spin" /><KeyRound v-else class="h-3.5 w-3.5" />{{ t("consul.ui.heldKeys") }}</Button
+ >
+ <Button v-if="isTtlSession(session)" size="icon" variant="ghost" class="h-7 w-7" :disabled="readOnly || !connectionActive" :title="t('consul.ui.renewNow')" @click="renew(session.ID)"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ <Button v-if="isTtlSession(session)" size="sm" variant="ghost" class="h-7 gap-1" :disabled="readOnly || !connectionActive" :title="t('consul.ui.autoRenewPageHint')" @click="autoRenewId === session.ID ? stopAutoRenew() : startAutoRenew(session.ID)"
+ ><RotateCw class="h-3.5 w-3.5" :class="autoRenewId === session.ID && 'animate-spin'" />{{ autoRenewId === session.ID ? t("consul.ui.stop") : t("consul.ui.autoRenew") }}</Button
+ >
+ <span v-else class="px-2 text-[11px] text-muted-foreground">{{ t("consul.ui.noRenewRequired") }}</span>
+ <Button size="icon" variant="ghost" class="h-7 w-7 text-destructive" :disabled="readOnly" :title="t('consul.ui.destroy')" @click="destroy(session.ID)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+
+ <div v-if="expandedSessionId === session.ID" class="border-t bg-muted/10 p-3">
+ <dl class="grid overflow-hidden rounded-md border bg-background sm:grid-cols-2 lg:grid-cols-4">
+ <div class="border-b p-3 lg:border-r">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.node") }}</dt>
+ <dd class="mt-1 text-xs font-medium">{{ session.Node || "—" }}</dd>
+ </div>
+ <div class="border-b p-3 lg:border-r">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.lockDelay") }}</dt>
+ <dd class="mt-1 font-mono text-xs">{{ formatLockDelay(session.LockDelay) }}</dd>
+ </div>
+ <div class="border-b p-3 lg:border-r">
+ <dt class="text-[11px] text-muted-foreground">TTL</dt>
+ <dd class="mt-1 font-mono text-xs">{{ session.TTL || t("consul.ui.noTtl") }}</dd>
+ </div>
+ <div class="border-b p-3">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.behavior") }}</dt>
+ <dd class="mt-1 text-xs font-medium">{{ behaviorLabel(session.Behavior) }}</dd>
+ </div>
+ <div class="border-b p-3 lg:border-r">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.createIndex") }}</dt>
+ <dd class="mt-1 font-mono text-xs">{{ session.CreateIndex }}</dd>
+ </div>
+ <div class="border-b p-3 lg:border-r">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.modifyIndexLabel") }}</dt>
+ <dd class="mt-1 font-mono text-xs">{{ session.ModifyIndex }}</dd>
+ </div>
+ <div class="border-b p-3 lg:col-span-2">
+ <dt class="text-[11px] text-muted-foreground">{{ t("consul.ui.checks") }}</dt>
+ <dd class="mt-1 flex flex-wrap gap-1">
+ <Badge v-for="check in sessionChecks(session)" :key="check" variant="outline">{{ check }}</Badge
+ ><span v-if="!sessionChecks(session).length" class="text-xs text-muted-foreground">—</span>
+ </dd>
+ </div>
+ </dl>
+
+ <div v-if="heldKeys[session.ID] || heldKeysLoading === session.ID" class="mt-3 overflow-hidden rounded-md border bg-background">
+ <div class="flex items-center justify-between border-b bg-muted/20 px-3 py-2">
+ <div class="flex items-center gap-2 text-xs font-medium">
+ <KeyRound class="h-3.5 w-3.5" />{{ t("consul.ui.heldKeys") }}<Badge v-if="heldKeys[session.ID]" variant="secondary">{{ heldKeys[session.ID].items.length }}</Badge>
+ </div>
+ <span v-if="heldKeys[session.ID] && !heldKeys[session.ID].complete" class="inline-flex items-center gap-1 text-[11px] text-amber-700 dark:text-amber-300"><AlertTriangle class="h-3.5 w-3.5" />{{ t("consul.ui.heldKeysIncomplete") }}</span
+ ><span v-else-if="heldKeys[session.ID]?.complete" class="inline-flex items-center gap-1 text-[11px] text-emerald-700 dark:text-emerald-300"><ShieldCheck class="h-3.5 w-3.5" />{{ t("consul.ui.complete") }}</span>
+ </div>
+ <div v-if="heldKeysLoading === session.ID" class="flex items-center justify-center gap-2 p-4 text-xs text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ <template v-else
+ ><div v-for="item in heldKeys[session.ID]?.items || []" :key="item.key" class="flex items-center justify-between gap-3 border-b px-3 py-2 font-mono text-xs last:border-0">
+ <span class="min-w-0 break-all">{{ item.key }}</span
+ ><span class="shrink-0 text-muted-foreground">{{ t("consul.ui.lockIndex", { index: item.lockIndex }) }}</span>
+ </div>
+ <div v-if="!heldKeys[session.ID]?.items.length" class="p-3 text-xs text-muted-foreground">{{ t("consul.ui.noHeldKeys") }}</div></template
+ >
+ </div>
+ </div>
+ </div>
+
+ <div v-if="!pagedSessions.length && !loading" class="p-8 text-center text-xs text-muted-foreground">{{ hasFilters ? t("consul.ui.noMatchingSessions") : t("consul.ui.noVisibleSessions") }}</div>
+ <div v-if="loading && !sessions.length" class="flex items-center justify-center gap-2 p-8 text-xs text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("consul.ui.loading") }}</div>
+ </section>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulTools.vue b/apps/desktop/src/components/consul/ConsulTools.vue
new file mode 100644
index 0000000000..fc69c51777
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulTools.vue
@@ -0,0 +1,370 @@
+<script setup lang="ts">
+import { computed, onMounted, ref, watch } from "vue";
+import { FileSearch, Pencil, Play, Plus, RefreshCcw, Trash2, X } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import * as api from "@/lib/backend/api";
+import type { ConsulCapabilities, ConsulCoordinate, ConsulEvent, ConsulPreparedQuery, ConsulPreparedQueryExecuteResponse, ConsulPreparedQueryNode } from "@/types/consul";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useI18n } from "vue-i18n";
+
+type ToolTab = "queries" | "events" | "coordinates";
+
+const props = defineProps<{ connectionId: string; capabilities?: ConsulCapabilities | null }>();
+const { t } = useI18n();
+function capabilityLabel(value?: string) {
+ if (value === "supported") return t("consul.ui.capabilitySupported");
+ if (value === "unsupported") return t("consul.ui.capabilityUnsupported");
+ if (value === "disabled") return t("consul.ui.capabilityDisabled");
+ if (value === "forbidden") return t("consul.ui.capabilityForbidden");
+ return t("consul.ui.capabilityUnknown");
+}
+const connectionStore = useConnectionStore();
+const readOnly = computed(() => Boolean(connectionStore.getConfig(props.connectionId)?.read_only));
+const canWriteQueries = computed(() => !readOnly.value && props.capabilities?.preparedQueries === "supported");
+const canFireEvents = computed(() => !readOnly.value && props.capabilities?.events === "supported");
+const queryAvailable = computed(() => !["unsupported", "disabled", "forbidden"].includes(props.capabilities?.preparedQueries || ""));
+const eventAvailable = computed(() => !["unsupported", "disabled", "forbidden"].includes(props.capabilities?.events || ""));
+const coordinateAvailable = computed(() => !["unsupported", "disabled", "forbidden"].includes(props.capabilities?.coordinates || ""));
+
+const activeTab = ref<ToolTab>("queries");
+const queries = ref<ConsulPreparedQuery[]>([]);
+const events = ref<ConsulEvent[]>([]);
+const coordinates = ref<ConsulCoordinate[]>([]);
+const queryLoading = ref(false);
+const eventLoading = ref(false);
+const coordinateLoading = ref(false);
+const queryBusy = ref(false);
+const eventBusy = ref(false);
+const queryError = ref("");
+const eventError = ref("");
+const coordinateError = ref("");
+const activeLoading = computed(() => (activeTab.value === "queries" ? queryLoading.value : activeTab.value === "events" ? eventLoading.value : coordinateLoading.value));
+
+const queryName = ref("");
+const queryService = ref("");
+const queryResult = ref<ConsulPreparedQueryExecuteResponse | null>(null);
+const queryDetails = ref<unknown | null>(null);
+const editingQueryId = ref("");
+
+const eventName = ref("");
+const eventPayload = ref("");
+const eventNodeFilter = ref("");
+const eventServiceFilter = ref("");
+const eventTagFilter = ref("");
+const eventPayloadBytes = computed(() => new TextEncoder().encode(eventPayload.value).length);
+const eventValid = computed(() => {
+ const name = eventName.value.trim();
+ return Boolean(name && !name.startsWith("_") && new TextEncoder().encode(name).length <= 256 && eventPayloadBytes.value <= 100);
+});
+
+function errorMessage(error: unknown) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+async function loadQueries() {
+ if (!queryAvailable.value) return;
+ queryLoading.value = true;
+ queryError.value = "";
+ try {
+ queries.value = await api.consulPreparedQueryList(props.connectionId);
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryLoading.value = false;
+ }
+}
+
+async function loadEvents() {
+ if (!eventAvailable.value) return;
+ eventLoading.value = true;
+ eventError.value = "";
+ try {
+ events.value = await api.consulEventList(props.connectionId);
+ } catch (error) {
+ eventError.value = errorMessage(error);
+ } finally {
+ eventLoading.value = false;
+ }
+}
+
+async function loadCoordinates() {
+ if (!coordinateAvailable.value) return;
+ coordinateLoading.value = true;
+ coordinateError.value = "";
+ try {
+ coordinates.value = await api.consulCoordinateNodes(props.connectionId);
+ } catch (error) {
+ coordinateError.value = errorMessage(error);
+ } finally {
+ coordinateLoading.value = false;
+ }
+}
+
+async function refresh() {
+ if (activeTab.value === "queries") await loadQueries();
+ else if (activeTab.value === "events") await loadEvents();
+ else await loadCoordinates();
+}
+
+async function createQuery() {
+ if (!canWriteQueries.value || !queryName.value.trim() || !queryService.value.trim()) return;
+ queryBusy.value = true;
+ queryError.value = "";
+ try {
+ const input = {
+ name: queryName.value.trim(),
+ session: "",
+ service: { Service: queryService.value.trim(), Near: "", OnlyPassing: false, Tags: [] },
+ };
+ if (editingQueryId.value) await api.consulPreparedQueryUpdate(props.connectionId, editingQueryId.value, input);
+ else await api.consulPreparedQueryCreate(props.connectionId, input);
+ cancelQueryEdit();
+ await loadQueries();
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryBusy.value = false;
+ }
+}
+
+function cancelQueryEdit() {
+ editingQueryId.value = "";
+ queryName.value = "";
+ queryService.value = "";
+}
+
+async function editQuery(query: ConsulPreparedQuery) {
+ queryBusy.value = true;
+ queryError.value = "";
+ try {
+ const current = await api.consulPreparedQueryRead(props.connectionId, query.ID);
+ queryDetails.value = current;
+ editingQueryId.value = current.ID;
+ queryName.value = current.Name;
+ queryService.value = current.Service.Service;
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryBusy.value = false;
+ }
+}
+
+async function explainQuery(query: ConsulPreparedQuery) {
+ queryBusy.value = true;
+ queryError.value = "";
+ try {
+ queryDetails.value = await api.consulPreparedQueryExplain(props.connectionId, query.ID);
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryBusy.value = false;
+ }
+}
+
+async function deleteQuery(id: string) {
+ if (!canWriteQueries.value || !confirm(t("consul.ui.deletePreparedQuery", { id }))) return;
+ queryBusy.value = true;
+ queryError.value = "";
+ try {
+ await api.consulPreparedQueryDelete(props.connectionId, id);
+ if (editingQueryId.value === id) cancelQueryEdit();
+ await loadQueries();
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryBusy.value = false;
+ }
+}
+
+async function executeQuery(query: ConsulPreparedQuery) {
+ queryBusy.value = true;
+ queryError.value = "";
+ queryDetails.value = null;
+ try {
+ queryResult.value = await api.consulPreparedQueryExecute(props.connectionId, { query: query.ID, limit: 100, connect: false });
+ } catch (error) {
+ queryError.value = errorMessage(error);
+ } finally {
+ queryBusy.value = false;
+ }
+}
+
+function queryEndpoint(item: ConsulPreparedQueryNode) {
+ const address = item.Service.Address || item.Node.Address || "-";
+ return item.Service.Port ? `${address}:${item.Service.Port}` : address;
+}
+
+async function fireEvent() {
+ if (!canFireEvents.value || !eventValid.value) return;
+ eventBusy.value = true;
+ eventError.value = "";
+ try {
+ const bytes = new TextEncoder().encode(eventPayload.value);
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ await api.consulEventFire(props.connectionId, {
+ name: eventName.value.trim(),
+ payloadBase64: btoa(binary),
+ nodeFilter: eventNodeFilter.value.trim(),
+ serviceFilter: eventServiceFilter.value.trim(),
+ tagFilter: eventTagFilter.value.trim(),
+ });
+ eventPayload.value = "";
+ await loadEvents();
+ } catch (error) {
+ eventError.value = errorMessage(error);
+ } finally {
+ eventBusy.value = false;
+ }
+}
+
+function decodeEventPayload(payload: string | null) {
+ if (!payload) return "";
+ try {
+ const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+ } catch {
+ return payload;
+ }
+}
+
+watch(activeTab, () => {
+ void refresh();
+});
+watch(
+ () => props.connectionId,
+ () => {
+ queries.value = [];
+ events.value = [];
+ coordinates.value = [];
+ queryResult.value = null;
+ queryDetails.value = null;
+ cancelQueryEdit();
+ void refresh();
+ },
+);
+onMounted(() => {
+ void refresh();
+});
+defineExpose({ refresh });
+</script>
+
+<template>
+ <div class="flex h-full min-h-0 flex-col">
+ <div class="flex h-10 shrink-0 items-center justify-between border-b px-3">
+ <span class="text-sm font-medium">{{ t("consul.ui.tools") }}</span>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="activeLoading" :title="t('consul.ui.refresh')" @click="refresh">
+ <RefreshCcw class="h-3.5 w-3.5" :class="activeLoading ? 'animate-spin' : ''" />
+ </Button>
+ </div>
+ <Tabs v-model="activeTab" class="flex min-h-0 flex-1 flex-col">
+ <TabsList class="mx-3 mt-3 h-8 w-fit">
+ <TabsTrigger value="queries">{{ t("consul.ui.preparedQueries") }}</TabsTrigger>
+ <TabsTrigger value="events">{{ t("consul.ui.events") }}</TabsTrigger>
+ <TabsTrigger value="coordinates">{{ t("consul.ui.coordinates") }}</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="queries" class="m-0 min-h-0 flex-1 overflow-auto p-3">
+ <p class="mb-3 text-sm text-muted-foreground">{{ t("consul.ui.preparedQueriesDescription") }}</p>
+ <div v-if="capabilities && capabilities.preparedQueries !== 'supported'" class="mb-3 rounded-md border p-3 text-sm text-muted-foreground">{{ t("consul.ui.capability", { status: capabilityLabel(capabilities.preparedQueries) }) }}</div>
+ <div v-if="queryError" class="mb-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">{{ queryError }}</div>
+ <div v-if="canWriteQueries" class="mb-3 grid grid-cols-[minmax(12rem,1fr)_minmax(12rem,1fr)_auto_auto] gap-2">
+ <Input v-model="queryName" :placeholder="t('consul.ui.queryName')" />
+ <Input v-model="queryService" :placeholder="t('consul.ui.targetService')" />
+ <Button size="sm" :disabled="queryBusy || !queryName.trim() || !queryService.trim()" @click="createQuery"> <Pencil v-if="editingQueryId" class="mr-1 h-3.5 w-3.5" /><Plus v-else class="mr-1 h-3.5 w-3.5" />{{ editingQueryId ? t("consul.ui.update") : t("consul.ui.create") }} </Button>
+ <Button v-if="editingQueryId" variant="ghost" size="icon" class="h-8 w-8" :title="t('consul.ui.cancelEdit')" @click="cancelQueryEdit"><X class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div class="overflow-hidden rounded-md border">
+ <div v-for="query in queries" :key="query.ID" class="flex min-h-12 items-center gap-2 border-b px-3 py-2 text-sm last:border-b-0">
+ <div class="min-w-0 flex-1">
+ <div class="truncate font-medium">{{ query.Name || query.ID }}</div>
+ <div class="truncate text-xs text-muted-foreground">{{ t("consul.ui.targetServiceValue", { service: query.Service.Service }) }} · {{ t("consul.ui.id") }} {{ query.ID }}</div>
+ </div>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="queryBusy" :title="t('consul.ui.execute')" @click="executeQuery(query)"><Play class="h-3.5 w-3.5" /></Button>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :disabled="queryBusy" :title="t('consul.ui.explain')" @click="explainQuery(query)"><FileSearch class="h-3.5 w-3.5" /></Button>
+ <Button v-if="canWriteQueries" variant="ghost" size="icon" class="h-7 w-7" :disabled="queryBusy" :title="t('consul.ui.edit')" @click="editQuery(query)"><Pencil class="h-3.5 w-3.5" /></Button>
+ <Button v-if="canWriteQueries" variant="ghost" size="icon" class="h-7 w-7 text-destructive" :disabled="queryBusy" :title="t('consul.ui.delete')" @click="deleteQuery(query.ID)"><Trash2 class="h-3.5 w-3.5" /></Button>
+ </div>
+ <div v-if="!queryLoading && queryAvailable && queries.length === 0" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.noPreparedQueries") }}</div>
+ <div v-if="queryLoading" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.loading") }}</div>
+ </div>
+ <div v-if="queryResult" class="mt-3 overflow-hidden rounded-md border">
+ <div class="border-b bg-muted/20 px-3 py-2 text-sm font-medium">
+ {{ t("consul.ui.queryExecutionResult", { count: queryResult.Nodes.length, datacenter: queryResult.Datacenter || "-" }) }}<span v-if="queryResult.DNS?.TTL" class="ml-2 text-xs font-normal text-muted-foreground">DNS TTL {{ queryResult.DNS.TTL }}</span>
+ </div>
+ <div v-for="item in queryResult.Nodes" :key="`${item.Node.Node}:${item.Service.ID}`" class="grid grid-cols-[minmax(8rem,1fr)_minmax(8rem,1fr)_minmax(8rem,1fr)] gap-3 border-b px-3 py-2 text-sm last:border-b-0">
+ <span class="truncate">{{ item.Node.Node }}</span
+ ><span class="truncate font-mono text-xs">{{ item.Service.ID }}</span
+ ><span class="truncate font-mono text-xs">{{ queryEndpoint(item) }}</span>
+ </div>
+ <div v-if="queryResult.Nodes.length === 0" class="px-3 py-6 text-center text-sm text-muted-foreground">{{ t("consul.ui.noQueryNodes") }}</div>
+ </div>
+ <div v-if="queryDetails" class="mt-3">
+ <div class="mb-1 text-xs font-medium text-muted-foreground">{{ t("consul.ui.queryExplanation") }}</div>
+ <pre class="max-h-64 overflow-auto rounded-md border bg-muted/20 p-3 text-xs">{{ JSON.stringify(queryDetails, null, 2) }}</pre>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="events" class="m-0 min-h-0 flex-1 overflow-auto p-3">
+ <p class="mb-3 text-sm text-muted-foreground">{{ t("consul.ui.eventsDescription") }}</p>
+ <div v-if="capabilities && capabilities.events !== 'supported'" class="mb-3 rounded-md border p-3 text-sm text-muted-foreground">{{ t("consul.ui.capability", { status: capabilityLabel(capabilities.events) }) }}</div>
+ <div v-if="eventError" class="mb-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">{{ eventError }}</div>
+ <div v-if="canFireEvents" class="mb-3 rounded-md border p-3">
+ <div class="grid grid-cols-[minmax(10rem,1fr)_minmax(12rem,2fr)_auto] gap-2">
+ <Input v-model="eventName" :placeholder="t('consul.ui.eventName')" />
+ <Input v-model="eventPayload" :placeholder="t('consul.ui.payload')" />
+ <Button size="sm" :disabled="eventBusy || !eventValid" @click="fireEvent"><Play class="mr-1 h-3.5 w-3.5" />{{ t("consul.ui.fire") }}</Button>
+ </div>
+ <div class="mt-2 grid grid-cols-3 gap-2">
+ <Input v-model="eventNodeFilter" :placeholder="t('consul.ui.eventNodeFilter')" />
+ <Input v-model="eventServiceFilter" :placeholder="t('consul.ui.eventServiceFilter')" />
+ <Input v-model="eventTagFilter" :placeholder="t('consul.ui.eventTagFilter')" />
+ </div>
+ <div class="mt-2 text-xs" :class="eventPayloadBytes > 100 ? 'text-destructive' : 'text-muted-foreground'">{{ t("consul.ui.eventPayloadBytes", { count: eventPayloadBytes }) }}</div>
+ </div>
+ <div class="overflow-hidden rounded-md border">
+ <div v-for="event in events" :key="event.ID" class="border-b px-3 py-2 last:border-b-0">
+ <div class="flex items-center gap-2">
+ <span class="text-sm font-medium">{{ event.Name }}</span
+ ><span class="text-xs text-muted-foreground">LTime {{ event.LTime }}</span>
+ </div>
+ <div class="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
+ <span v-if="event.NodeFilter">{{ t("consul.ui.node") }}: {{ event.NodeFilter }}</span
+ ><span v-if="event.ServiceFilter">{{ t("consul.ui.service") }}: {{ event.ServiceFilter }}</span
+ ><span v-if="event.TagFilter">{{ t("consul.ui.tags") }}: {{ event.TagFilter }}</span>
+ </div>
+ <div v-if="event.Payload" class="mt-1 break-all rounded bg-muted/30 px-2 py-1 font-mono text-xs">{{ decodeEventPayload(event.Payload) }}</div>
+ </div>
+ <div v-if="!eventLoading && eventAvailable && events.length === 0" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.noEvents") }}</div>
+ <div v-if="eventLoading" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.loading") }}</div>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="coordinates" class="m-0 min-h-0 flex-1 overflow-auto p-3">
+ <p class="mb-3 text-sm text-muted-foreground">{{ t("consul.ui.coordinatesDescription") }}</p>
+ <div v-if="capabilities && capabilities.coordinates !== 'supported'" class="mb-3 rounded-md border p-3 text-sm text-muted-foreground">{{ t("consul.ui.capability", { status: capabilityLabel(capabilities.coordinates) }) }}</div>
+ <div v-if="coordinateError" class="mb-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">{{ coordinateError }}</div>
+ <div class="overflow-hidden rounded-md border">
+ <div v-if="coordinates.length" class="grid grid-cols-[minmax(10rem,1.5fr)_minmax(7rem,1fr)_repeat(3,minmax(6rem,1fr))] gap-3 border-b bg-muted/20 px-3 py-2 text-xs font-medium text-muted-foreground">
+ <span>{{ t("consul.ui.node") }}</span
+ ><span>{{ t("consul.ui.segment") }}</span
+ ><span>{{ t("consul.ui.error") }}</span
+ ><span>{{ t("consul.ui.adjustment") }}</span
+ ><span>{{ t("consul.ui.height") }}</span>
+ </div>
+ <div v-for="item in coordinates" :key="`${item.Node}:${item.Segment}`" class="grid grid-cols-[minmax(10rem,1.5fr)_minmax(7rem,1fr)_repeat(3,minmax(6rem,1fr))] gap-3 border-b px-3 py-2 text-sm last:border-b-0">
+ <span class="truncate font-medium">{{ item.Node }}</span
+ ><span class="truncate text-muted-foreground">{{ item.Segment || t("consul.ui.default") }}</span
+ ><span class="font-mono text-xs">{{ item.Coord.Error }}</span
+ ><span class="font-mono text-xs">{{ item.Coord.Adjustment }}</span
+ ><span class="font-mono text-xs">{{ item.Coord.Height }}</span>
+ </div>
+ <div v-if="!coordinateLoading && coordinateAvailable && coordinates.length === 0" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.noCoordinates") }}</div>
+ <div v-if="coordinateLoading" class="px-3 py-8 text-center text-sm text-muted-foreground">{{ t("consul.ui.loading") }}</div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/consul/ConsulWorkspace.vue b/apps/desktop/src/components/consul/ConsulWorkspace.vue
new file mode 100644
index 0000000000..f849b20a3d
--- /dev/null
+++ b/apps/desktop/src/components/consul/ConsulWorkspace.vue
@@ -0,0 +1,236 @@
+<script setup lang="ts">
+import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { Activity, Boxes, KeyRound, Layers3, Network, RefreshCcw, ShieldCheck, Timer, Wrench, Gauge } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import * as api from "@/lib/backend/api";
+import type { ConsulCapabilities } from "@/types/consul";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useConsulStore } from "@/stores/consulStore";
+import { consulMeshWorkspaceVisible } from "@/lib/consul/meshVisibility";
+import { useI18n } from "vue-i18n";
+
+const ConsulKeyBrowser = defineAsyncComponent(() => import("@/components/consul/ConsulKeyBrowser.vue"));
+const ConsulServices = defineAsyncComponent(() => import("@/components/consul/ConsulServices.vue"));
+const ConsulHealth = defineAsyncComponent(() => import("@/components/consul/ConsulHealth.vue"));
+const ConsulSessions = defineAsyncComponent(() => import("@/components/consul/ConsulSessions.vue"));
+const ConsulAcl = defineAsyncComponent(() => import("@/components/consul/ConsulAcl.vue"));
+const ConsulScope = defineAsyncComponent(() => import("@/components/consul/ConsulScope.vue"));
+const ConsulMesh = defineAsyncComponent(() => import("@/components/consul/ConsulMesh.vue"));
+const ConsulTools = defineAsyncComponent(() => import("@/components/consul/ConsulTools.vue"));
+const ConsulOperator = defineAsyncComponent(() => import("@/components/consul/ConsulOperator.vue"));
+
+type WorkspaceTab = "kv" | "services" | "health" | "sessions" | "acl" | "scope" | "mesh" | "tools" | "operator";
+type Refreshable = { refresh?: () => boolean | Promise<unknown>; focusSearch?: () => boolean };
+const props = defineProps<{ connectionId: string }>();
+const connectionStore = useConnectionStore();
+const consulStore = useConsulStore();
+const { t } = useI18n();
+const activeTab = ref<WorkspaceTab>("kv");
+const keyRef = ref<Refreshable>();
+const servicesRef = ref<Refreshable>();
+const healthRef = ref<Refreshable>();
+const sessionsRef = ref<Refreshable>();
+const aclRef = ref<Refreshable>();
+const scopeRef = ref<Refreshable>();
+const meshRef = ref<Refreshable>();
+const toolsRef = ref<Refreshable>();
+const operatorRef = ref<Refreshable>();
+const capabilities = ref<ConsulCapabilities | null>(null);
+const discoveredDatacenters = ref<string[]>([]);
+const scopeRevision = ref(0);
+const scopeOpen = ref(false);
+const scopeSaving = ref(false);
+const scopeError = ref("");
+const scopeDraft = ref({ datacenter: "", partition: "", namespace: "" });
+const pendingSearchFocus = ref(false);
+let contextSequence = 0;
+const activeScope = computed(() => {
+ const external = connectionStore.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ return {
+ datacenter: String(config.datacenter || config.consulDatacenter || config.consul_datacenter || ""),
+ partition: String(config.partition || config.consulPartition || config.consul_partition || ""),
+ namespace: String(config.namespace || config.consulNamespace || config.consul_namespace || ""),
+ };
+});
+const datacenterOptions = computed(() => [...new Set([activeScope.value.datacenter, capabilities.value?.datacenter || "", ...discoveredDatacenters.value].map((value) => value.trim()).filter(Boolean))]);
+const resolvedDatacenter = computed(() => activeScope.value.datacenter || capabilities.value?.datacenter || datacenterOptions.value[0] || "-");
+const enterpriseScopeAvailable = computed(() => capabilities.value?.namespaces === "supported" || capabilities.value?.partitions === "supported");
+const aclVisible = computed(() => capabilities.value?.acl !== "disabled");
+const scopeTabVisible = computed(() => enterpriseScopeAvailable.value);
+const meshVisible = computed(() => consulMeshWorkspaceVisible(connectionStore.getConfig(props.connectionId)?.external_config));
+const canChangeScope = computed(() => enterpriseScopeAvailable.value || datacenterOptions.value.length > 1);
+const scopeLabel = computed(() => (enterpriseScopeAvailable.value ? `${resolvedDatacenter.value} / ${activeScope.value.partition || t("consul.ui.default")} / ${activeScope.value.namespace || t("consul.ui.default")}` : resolvedDatacenter.value));
+const operatorVisible = computed(() => {
+ const external = connectionStore.getConfig(props.connectionId)?.external_config;
+ const config = external && typeof external === "object" && !Array.isArray(external) ? (external as Record<string, unknown>) : {};
+ const capability = capabilities.value;
+ const available = capability && [capability.operatorAutopilot, capability.operatorRaft, capability.operatorKeyring, capability.operatorUsage, capability.operatorLicense, capability.audit].some((status) => status === "supported");
+ return Boolean(config.consulOperatorVisible) && Boolean(available);
+});
+function activeHandle() {
+ return { kv: keyRef.value, services: servicesRef.value, health: healthRef.value, sessions: sessionsRef.value, acl: aclRef.value, scope: scopeRef.value, mesh: meshRef.value, tools: toolsRef.value, operator: operatorRef.value }[activeTab.value];
+}
+async function loadWorkspaceContext() {
+ const sequence = ++contextSequence;
+ const connectionId = props.connectionId;
+ const [capabilityResult, datacenterResult] = await Promise.allSettled([api.consulCapabilities(connectionId), api.consulCatalogDatacenters(connectionId)]);
+ if (sequence !== contextSequence || connectionId !== props.connectionId) return;
+ capabilities.value = capabilityResult.status === "fulfilled" ? capabilityResult.value : null;
+ discoveredDatacenters.value = datacenterResult.status === "fulfilled" ? [...new Set(datacenterResult.value.map((value) => value.trim()).filter(Boolean))] : [];
+}
+function openScopeSwitcher() {
+ scopeDraft.value = {
+ datacenter: resolvedDatacenter.value === "-" ? "" : resolvedDatacenter.value,
+ partition: activeScope.value.partition,
+ namespace: activeScope.value.namespace,
+ };
+ scopeError.value = "";
+ scopeOpen.value = true;
+}
+async function applyScope() {
+ const config = connectionStore.getConfig(props.connectionId);
+ if (!config) return;
+ scopeSaving.value = true;
+ scopeError.value = "";
+ const nextScope = {
+ datacenter: scopeDraft.value.datacenter.trim(),
+ partition: scopeDraft.value.partition.trim(),
+ namespace: scopeDraft.value.namespace.trim(),
+ };
+ try {
+ consulStore.bindConnection(props.connectionId, activeScope.value);
+ consulStore.switchScope(nextScope);
+ const currentExternal = config.external_config;
+ const external = currentExternal && typeof currentExternal === "object" && !Array.isArray(currentExternal) ? ({ ...currentExternal } as Record<string, unknown>) : {};
+ external.datacenter = nextScope.datacenter || undefined;
+ external.partition = nextScope.partition || undefined;
+ external.namespace = nextScope.namespace || undefined;
+ await connectionStore.updateConnection({ ...config, external_config: external });
+ scopeRevision.value += 1;
+ scopeOpen.value = false;
+ await loadWorkspaceContext();
+ } catch (error) {
+ scopeError.value = error instanceof Error ? error.message : String(error);
+ } finally {
+ scopeSaving.value = false;
+ }
+}
+function focusSearch() {
+ activeTab.value = "kv";
+ pendingSearchFocus.value = true;
+ void nextTick(() => {
+ pendingSearchFocus.value = false;
+ keyRef.value?.focusSearch?.();
+ });
+ return true;
+}
+function refresh() {
+ const handle = activeHandle();
+ if (!handle?.refresh) return false;
+ void handle.refresh();
+ return true;
+}
+watch(keyRef, (value) => {
+ if (value && pendingSearchFocus.value)
+ void nextTick(() => {
+ pendingSearchFocus.value = false;
+ value.focusSearch?.();
+ });
+});
+watch([aclVisible, scopeTabVisible, meshVisible], () => {
+ if (activeTab.value === "acl" && !aclVisible.value) activeTab.value = "kv";
+ if (activeTab.value === "scope" && !scopeTabVisible.value) activeTab.value = "kv";
+ if (activeTab.value === "mesh" && !meshVisible.value) activeTab.value = "kv";
+});
+watch(
+ () => props.connectionId,
+ () => {
+ consulStore.bindConnection(props.connectionId, activeScope.value);
+ void loadWorkspaceContext();
+ },
+);
+onMounted(() => {
+ consulStore.bindConnection(props.connectionId, activeScope.value);
+ void loadWorkspaceContext();
+});
+onBeforeUnmount(() => {
+ contextSequence += 1;
+});
+defineExpose({ focusSearch, refresh });
+</script>
+
+<template>
+ <Tabs v-model="activeTab" class="flex h-full min-h-0 flex-col bg-background">
+ <div class="flex h-11 shrink-0 items-center gap-2 border-b px-3">
+ <div class="min-w-0 flex-1 overflow-x-auto overflow-y-hidden">
+ <TabsList class="h-8 w-max min-w-max justify-start bg-muted/60 p-0.5">
+ <TabsTrigger value="kv" class="h-7 flex-none gap-1.5 px-3 text-xs"><KeyRound class="h-3.5 w-3.5" />{{ t("consul.workspace.kv") }}</TabsTrigger>
+ <TabsTrigger value="services" class="h-7 flex-none gap-1.5 px-3 text-xs"><Boxes class="h-3.5 w-3.5" />{{ t("consul.workspace.services") }}</TabsTrigger>
+ <TabsTrigger value="health" class="h-7 flex-none gap-1.5 px-3 text-xs"><Activity class="h-3.5 w-3.5" />{{ t("consul.workspace.health") }}</TabsTrigger>
+ <TabsTrigger value="sessions" class="h-7 flex-none gap-1.5 px-3 text-xs"><Timer class="h-3.5 w-3.5" />{{ t("consul.workspace.sessions") }}</TabsTrigger>
+ <TabsTrigger v-if="aclVisible" value="acl" class="h-7 flex-none gap-1.5 px-3 text-xs"><ShieldCheck class="h-3.5 w-3.5" />{{ t("consul.workspace.acl") }}</TabsTrigger>
+ <TabsTrigger v-if="scopeTabVisible" value="scope" class="h-7 flex-none gap-1.5 px-3 text-xs"><Layers3 class="h-3.5 w-3.5" />{{ t("consul.workspace.scope") }}</TabsTrigger>
+ <TabsTrigger v-if="meshVisible" value="mesh" class="h-7 flex-none gap-1.5 px-3 text-xs"><Network class="h-3.5 w-3.5" />{{ t("consul.workspace.mesh") }}</TabsTrigger>
+ <TabsTrigger value="tools" class="h-7 flex-none gap-1.5 px-3 text-xs"><Wrench class="h-3.5 w-3.5" />{{ t("consul.workspace.tools") }}</TabsTrigger>
+ <TabsTrigger v-if="operatorVisible" value="operator" class="h-7 flex-none gap-1.5 px-3 text-xs"><Gauge class="h-3.5 w-3.5" />{{ t("consul.workspace.operator") }}</TabsTrigger>
+ </TabsList>
+ </div>
+ <div class="flex shrink-0 items-center gap-1">
+ <Button v-if="canChangeScope" variant="ghost" size="sm" class="h-7 max-w-64 truncate px-2 font-mono text-[11px]" :title="t('consul.ui.scope')" @click="openScopeSwitcher">{{ scopeLabel }}</Button>
+ <span v-else class="max-w-64 truncate px-2 font-mono text-[11px]" :title="t('consul.ui.datacenter')">{{ scopeLabel }}</span>
+ <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('consul.ui.refresh')" @click="refresh"><RefreshCcw class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+ <div :key="`${props.connectionId}:${scopeRevision}`" class="contents">
+ <TabsContent value="kv" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulKeyBrowser ref="keyRef" :connection-id="props.connectionId" /></TabsContent>
+ <TabsContent value="services" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulServices ref="servicesRef" :connection-id="props.connectionId" /></TabsContent>
+ <TabsContent value="health" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulHealth ref="healthRef" :connection-id="props.connectionId" /></TabsContent>
+ <TabsContent value="sessions" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulSessions ref="sessionsRef" :connection-id="props.connectionId" /></TabsContent>
+ <TabsContent v-if="aclVisible" value="acl" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulAcl ref="aclRef" :connection-id="props.connectionId" :capabilities="capabilities" /></TabsContent>
+ <TabsContent v-if="scopeTabVisible" value="scope" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulScope ref="scopeRef" :connection-id="props.connectionId" :capabilities="capabilities" /></TabsContent>
+ <TabsContent v-if="meshVisible" value="mesh" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulMesh ref="meshRef" :connection-id="props.connectionId" :capabilities="capabilities" /></TabsContent>
+ <TabsContent value="tools" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulTools ref="toolsRef" :connection-id="props.connectionId" :capabilities="capabilities" /></TabsContent>
+ <TabsContent v-if="operatorVisible" value="operator" class="m-0 min-h-0 flex-1 overflow-hidden"><ConsulOperator ref="operatorRef" :connection-id="props.connectionId" :capabilities="capabilities" /></TabsContent>
+ </div>
+ </Tabs>
+ <Dialog v-model:open="scopeOpen">
+ <DialogContent class="sm:max-w-lg">
+ <DialogHeader
+ ><DialogTitle>{{ t("consul.ui.scope") }}</DialogTitle></DialogHeader
+ >
+ <div class="grid gap-3 py-2">
+ <div class="grid gap-1.5">
+ <Label>{{ t("consul.ui.datacenter") }}</Label>
+ <Select v-if="datacenterOptions.length > 1" v-model="scopeDraft.datacenter"
+ ><SelectTrigger><SelectValue /></SelectTrigger
+ ><SelectContent
+ ><SelectItem v-for="datacenter in datacenterOptions" :key="datacenter" :value="datacenter">{{ datacenter }}</SelectItem></SelectContent
+ ></Select
+ >
+ <Input v-else v-model="scopeDraft.datacenter" readonly />
+ </div>
+ <template v-if="enterpriseScopeAvailable">
+ <div class="grid gap-1.5">
+ <Label>{{ t("consul.ui.adminPartition") }}</Label
+ ><Input v-model="scopeDraft.partition" :placeholder="t('consul.ui.default')" />
+ </div>
+ <div class="grid gap-1.5">
+ <Label>{{ t("consul.ui.namespace") }}</Label
+ ><Input v-model="scopeDraft.namespace" :placeholder="t('consul.ui.default')" />
+ </div>
+ </template>
+ <p v-if="scopeError" class="text-sm text-destructive">{{ scopeError }}</p>
+ </div>
+ <DialogFooter
+ ><Button variant="outline" :disabled="scopeSaving" @click="scopeOpen = false">{{ t("consul.ui.cancel") }}</Button
+ ><Button :disabled="scopeSaving" @click="applyScope">{{ t("consul.ui.applyScope") }}</Button></DialogFooter
+ >
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulAclInteraction.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulAclInteraction.spec.ts
new file mode 100644
index 0000000000..119a8c2131
--- /dev/null
+++ b/apps/desktop/src/components/consul/__tests__/ConsulAclInteraction.spec.ts
@@ -0,0 +1,127 @@
+/** @vitest-environment happy-dom */
+
+import { createApp, nextTick } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+type ListResult = { items: Array<Record<string, unknown>> };
+type PendingList = {
+ kind: string;
+ resolve: (value: ListResult) => void;
+ reject: (reason: unknown) => void;
+};
+
+const mocks = vi.hoisted(() => ({
+ pendingLists: [] as PendingList[],
+ referencesError: "",
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ consulAclList: vi.fn(
+ (_connectionId: string, kind: string) =>
+ new Promise<ListResult>((resolve, reject) => {
+ mocks.pendingLists.push({ kind, resolve, reject });
+ }),
+ ),
+ consulAclReferences: vi.fn(async () => {
+ if (mocks.referencesError) throw new Error(mocks.referencesError);
+ return { tokenAccessorIds: [], roleIds: [], bindingRuleIds: [], complete: true };
+ }),
+ consulAclGet: vi.fn(),
+ consulAclApply: vi.fn(),
+ consulAclTokenClone: vi.fn(),
+ consulAclDelete: vi.fn(),
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({ getConfig: () => ({ read_only: false }) }),
+}));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+
+import ConsulAcl from "../ConsulAcl.vue";
+
+const capabilities = {
+ acl: "supported",
+ authMethods: "supported",
+ bindingRules: "supported",
+ templatedPolicies: "supported",
+};
+const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
+
+async function settle() {
+ for (let index = 0; index < 6; index += 1) {
+ await Promise.resolve();
+ await nextTick();
+ }
+}
+
+function resolveList(kind: string, items: Array<Record<string, unknown>>) {
+ const index = mocks.pendingLists.findIndex((request) => request.kind === kind);
+ expect(index).toBeGreaterThanOrEqual(0);
+ const [request] = mocks.pendingLists.splice(index, 1);
+ request.resolve({ items });
+}
+
+function clickButton(host: HTMLElement, label: string) {
+ const button = Array.from(host.querySelectorAll("button")).find((candidate) => candidate.textContent?.trim() === label);
+ expect(button).toBeTruthy();
+ button!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
+}
+
+afterEach(() => {
+ for (const { unmount, host } of mountedApps.splice(0)) {
+ unmount();
+ host.remove();
+ }
+ mocks.pendingLists.splice(0);
+ mocks.referencesError = "";
+ vi.clearAllMocks();
+});
+
+describe("ConsulAcl interactions", () => {
+ it("ignores a stale ACL list response after switching resource kinds", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulAcl, { connectionId: "connection-1", capabilities });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ resolveList("token", []);
+ await settle();
+ clickButton(host, "consul.ui.policies");
+ await settle();
+ clickButton(host, "consul.ui.roles");
+ await settle();
+
+ resolveList("role", [{ ID: "role-1", Name: "current-role" }]);
+ await settle();
+ expect(host.textContent).toContain("current-role");
+
+ resolveList("policy", [{ ID: "policy-1", Name: "stale-policy" }]);
+ await settle();
+ expect(host.textContent).toContain("current-role");
+ expect(host.textContent).not.toContain("stale-policy");
+ });
+
+ it("shows an ACL operation error instead of failing silently", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulAcl, { connectionId: "connection-1", capabilities });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ resolveList("token", [{ AccessorID: "token-1", Description: "test-token" }]);
+ await settle();
+ mocks.referencesError = "reference lookup failed";
+ const deleteButton = host.querySelector('button[title="consul.ui.deleteAndInspectReferences"]');
+ expect(deleteButton).toBeTruthy();
+ deleteButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(host.textContent).toContain("reference lookup failed");
+ });
+});
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulScopeInteraction.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulScopeInteraction.spec.ts
new file mode 100644
index 0000000000..9c1f79e4fa
--- /dev/null
+++ b/apps/desktop/src/components/consul/__tests__/ConsulScopeInteraction.spec.ts
@@ -0,0 +1,96 @@
+/** @vitest-environment happy-dom */
+
+import { createApp, nextTick } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+type PendingList = {
+ kind: string;
+ resolve: (value: { items: Array<Record<string, unknown>> }) => void;
+};
+
+const mocks = vi.hoisted(() => ({ pendingLists: [] as PendingList[] }));
+
+vi.mock("@/lib/backend/api", () => ({
+ consulEnterpriseList: vi.fn(
+ (_connectionId: string, kind: string) =>
+ new Promise((resolve) => {
+ mocks.pendingLists.push({ kind, resolve });
+ }),
+ ),
+ consulEnterpriseApply: vi.fn(),
+ consulEnterpriseImpact: vi.fn(),
+ consulEnterpriseDelete: vi.fn(),
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ getConfig: () => ({ read_only: false, external_config: { datacenter: "dc1" } }),
+ }),
+}));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+
+import ConsulScope from "../ConsulScope.vue";
+
+const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
+
+async function settle() {
+ for (let index = 0; index < 6; index += 1) {
+ await Promise.resolve();
+ await nextTick();
+ }
+}
+
+function resolveList(kind: string, items: Array<Record<string, unknown>>) {
+ const index = mocks.pendingLists.findIndex((request) => request.kind === kind);
+ expect(index).toBeGreaterThanOrEqual(0);
+ const [request] = mocks.pendingLists.splice(index, 1);
+ request.resolve({ items });
+}
+
+function activateTab(host: HTMLElement, label: string) {
+ const button = Array.from(host.querySelectorAll("button")).find((candidate) => candidate.textContent?.trim() === label);
+ expect(button).toBeTruthy();
+ button!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
+}
+
+afterEach(() => {
+ for (const { unmount, host } of mountedApps.splice(0)) {
+ unmount();
+ host.remove();
+ }
+ mocks.pendingLists.splice(0);
+ vi.clearAllMocks();
+});
+
+describe("ConsulScope interactions", () => {
+ it("does not let a stale partition request overwrite the active namespace list", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulScope, {
+ connectionId: "connection-1",
+ capabilities: { namespaces: "supported", partitions: "supported" },
+ });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ resolveList("namespace", []);
+ await settle();
+ activateTab(host, "consul.workspace.partitions");
+ await settle();
+ activateTab(host, "consul.ui.namespaces");
+ await settle();
+
+ resolveList("namespace", [{ Name: "current-namespace" }]);
+ await settle();
+ expect(host.textContent).toContain("current-namespace");
+
+ resolveList("partition", [{ Name: "stale-partition" }]);
+ await settle();
+ expect(host.textContent).toContain("current-namespace");
+ expect(host.textContent).not.toContain("stale-partition");
+ });
+});
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulServicesInteraction.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulServicesInteraction.spec.ts
new file mode 100644
index 0000000000..9ea28e6589
--- /dev/null
+++ b/apps/desktop/src/components/consul/__tests__/ConsulServicesInteraction.spec.ts
@@ -0,0 +1,290 @@
+/** @vitest-environment happy-dom */
+
+import { createApp, nextTick } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ const agentChecks: Record<string, Record<string, unknown>> = {};
+ return {
+ connectionConfig: { base_url: "http://127.0.0.1:8500", external_config: {} } as Record<string, unknown>,
+ agentChecks,
+ serviceMaintenance: vi.fn(async (_connectionId: string, id: string, enable: boolean) => {
+ const checkId = `_service_maintenance:${id}`;
+ if (enable) {
+ agentChecks[checkId] = {
+ Node: "node-1",
+ CheckID: checkId,
+ Name: "Service Maintenance Mode",
+ Status: "critical",
+ Notes: "test",
+ Output: "",
+ ServiceID: id,
+ ServiceName: "dbx-demo-api",
+ ServiceTags: ["demo"],
+ Type: "maintenance",
+ ExposedPort: 0,
+ Definition: {},
+ CreateIndex: 0,
+ ModifyIndex: 0,
+ Maintenance: true,
+ };
+ } else {
+ delete agentChecks[checkId];
+ }
+ return { target: { node: "node-1", address: "127.0.0.1" } };
+ }),
+ catalogServiceNodes: vi.fn(async (_connectionId: string, service: string) => ({
+ items: [
+ {
+ ID: "node-1",
+ Node: "node-1",
+ Address: "127.0.0.1",
+ Datacenter: "dc1",
+ TaggedAddresses: {},
+ NodeMeta: { zone: "demo-zone" },
+ ServiceKind: "",
+ ServiceID: `${service}-1`,
+ ServiceName: service,
+ ServiceTags: ["demo"],
+ ServiceAddress: "127.0.0.1",
+ ServicePort: 19080,
+ ServiceMeta: { owner: "DBX" },
+ ServiceTaggedAddresses: {},
+ ServiceWeights: { Passing: 1, Warning: 1 },
+ CreateIndex: 1,
+ ModifyIndex: 1,
+ },
+ ],
+ metadata: { index: "1", knownLeader: true, lastContact: 0, queryBackend: null },
+ })),
+ };
+});
+
+vi.mock("@/lib/backend/api", () => ({
+ consulCatalogServices: vi.fn(async () => ({
+ items: { consul: [], "dbx-demo-api": ["v1", "demo", "api"] },
+ metadata: { index: "1", knownLeader: true, lastContact: 0, queryBackend: null },
+ })),
+ consulCatalogNodes: vi.fn(async () => ({
+ items: [{ ID: "node-1", Node: "node-1", Address: "127.0.0.1", Datacenter: "dc1", TaggedAddresses: {}, NodeMeta: {}, CreateIndex: 1, ModifyIndex: 1 }],
+ metadata: { index: "1", knownLeader: true, lastContact: 0, queryBackend: null },
+ })),
+ consulCatalogServiceNodes: mocks.catalogServiceNodes,
+ consulCatalogNodeServices: vi.fn(async () => ({
+ items: {
+ Node: { ID: "node-1", Node: "node-1", Address: "127.0.0.1", Datacenter: "dc1", TaggedAddresses: {}, NodeMeta: {}, CreateIndex: 1, ModifyIndex: 1 },
+ Services: {
+ "dbx-demo-node-service-1": {
+ ID: "dbx-demo-node-service-1",
+ Service: "dbx-demo-node-service",
+ Tags: ["demo", "node"],
+ Address: "127.0.0.1",
+ TaggedAddresses: { lan: { Address: "127.0.0.1", Port: 19090 } },
+ Meta: { owner: "DBX" },
+ Port: 19090,
+ Weights: { Passing: 2, Warning: 1 },
+ },
+ },
+ },
+ metadata: { index: "1", knownLeader: true, lastContact: 0, queryBackend: null },
+ })),
+ consulAgentSelf: vi.fn(async () => ({ node: "node-1", address: "127.0.0.1", datacenter: "dc1", version: "2.0.2", server: true, revision: null, segment: null })),
+ consulAgentServices: vi.fn(async () => ({
+ "dbx-demo-api-1": { Kind: "", ID: "dbx-demo-api-1", Service: "dbx-demo-api", Tags: ["demo"], Meta: {}, Port: 19080, Address: "127.0.0.1", TaggedAddresses: {}, Weights: { Passing: 1, Warning: 1 }, EnableTagOverride: false, Datacenter: "dc1" },
+ })),
+ consulAgentChecks: vi.fn(async () => ({ ...mocks.agentChecks })),
+ consulAgentService: vi.fn(async (_connectionId: string, id: string) => ({
+ Kind: "",
+ ID: id,
+ Service: "dbx-demo-api",
+ Tags: ["demo"],
+ Meta: { owner: "DBX" },
+ Port: 19080,
+ Address: "127.0.0.1",
+ TaggedAddresses: {},
+ Weights: { Passing: 1, Warning: 1 },
+ EnableTagOverride: false,
+ Datacenter: "dc1",
+ })),
+ consulAgentRegisterService: vi.fn(),
+ consulAgentDeregisterService: vi.fn(),
+ consulAgentServiceMaintenance: mocks.serviceMaintenance,
+ consulDomainWatch: vi.fn(),
+ consulCancelBlocking: vi.fn(async () => true),
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ getConfig: () => mocks.connectionConfig,
+ }),
+}));
+
+vi.mock("@/stores/consulStore", () => ({
+ useConsulStore: () => ({
+ generation: 1,
+ bindConnection: vi.fn(),
+ registerOperation: vi.fn(),
+ completeOperation: vi.fn(),
+ }),
+}));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+
+import ConsulServices from "../ConsulServices.vue";
+
+const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
+
+async function settle() {
+ for (let index = 0; index < 6; index += 1) {
+ await Promise.resolve();
+ await nextTick();
+ }
+}
+
+afterEach(() => {
+ for (const { unmount, host } of mountedApps.splice(0)) {
+ unmount();
+ host.remove();
+ }
+ vi.clearAllMocks();
+ mocks.connectionConfig = { base_url: "http://127.0.0.1:8500", external_config: {} };
+ for (const key of Object.keys(mocks.agentChecks)) delete mocks.agentChecks[key];
+});
+
+describe("ConsulServices interactions", () => {
+ it("uses a neutral verification state before the Agent identity resolves", () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulServices, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+
+ expect(host.textContent).toContain("consul.ui.agentTargetVerifying");
+ expect(host.textContent).not.toContain("consul.ui.agentReadOnly");
+ });
+
+ it("selects a Catalog service and renders its instances on click", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulServices, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ const serviceButton = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.includes("dbx-demo-api"));
+ expect(serviceButton).toBeTruthy();
+ expect(serviceButton!.textContent).toBe("dbx-demo-api");
+ serviceButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(host.querySelector("h2")?.textContent).toContain("dbx-demo-api");
+ expect(host.textContent).toContain("dbx-demo-api-1");
+ expect(mocks.catalogServiceNodes).toHaveBeenLastCalledWith("connection-1", "dbx-demo-api");
+
+ const catalogRow = host.querySelector('tr[role="button"]');
+ expect(catalogRow).toBeTruthy();
+ catalogRow!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+ expect(host.textContent).toContain("consul.ui.nodeMeta");
+ expect(host.textContent).toContain("zone=demo-zone");
+ expect(host.textContent).toContain("consul.ui.serviceMeta");
+ expect(catalogRow!.getAttribute("aria-expanded")).toBe("true");
+
+ catalogRow!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+ expect(host.textContent).not.toContain("zone=demo-zone");
+ expect(catalogRow!.getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("keeps local service cards interactive while explaining read-only Agent actions", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulServices, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ expect(host.textContent).toContain("consul.ui.agentReadOnly");
+ expect(host.textContent).toContain("consul.ui.agentWriteDisabledHint");
+ expect(host.textContent).not.toContain("consul.ui.enableMaintenance");
+
+ const localServiceButton = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.includes("dbx-demo-api-1"));
+ expect(localServiceButton).toBeTruthy();
+ expect(localServiceButton!.hasAttribute("disabled")).toBe(false);
+ localServiceButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(host.textContent).toContain("consul.ui.enableTagOverride");
+ expect(host.textContent).toContain("consul.ui.serviceWeights");
+ expect(localServiceButton!.getAttribute("aria-expanded")).toBe("true");
+
+ localServiceButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(host.textContent).not.toContain("consul.ui.enableTagOverride");
+ expect(host.textContent).not.toContain("consul.ui.serviceWeights");
+ expect(localServiceButton!.getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("shows and toggles the current service maintenance state", async () => {
+ mocks.connectionConfig = {
+ base_url: "http://127.0.0.1:8500",
+ external_config: {
+ serverAddr: "http://127.0.0.1:8500",
+ agentTarget: { node: "node-1", address: "127.0.0.1" },
+ },
+ };
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulServices, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ const enableButton = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.includes("consul.ui.enableMaintenance"));
+ expect(enableButton).toBeTruthy();
+ enableButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(mocks.serviceMaintenance).toHaveBeenLastCalledWith("connection-1", "dbx-demo-api-1", true, "consul.ui.maintenanceReason");
+ expect(host.textContent).toContain("consul.ui.maintenance");
+ const disableButton = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.includes("consul.ui.disableMaintenance"));
+ expect(disableButton).toBeTruthy();
+ disableButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(mocks.serviceMaintenance).toHaveBeenLastCalledWith("connection-1", "dbx-demo-api-1", false, "consul.ui.maintenanceReason");
+ expect(host.textContent).not.toContain("consul.ui.maintenance");
+ expect(host.textContent).toContain("consul.ui.enableMaintenance");
+ });
+
+ it("expands and collapses full service details in Catalog node view", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulServices, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ const nodeTab = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.trim() === "consul.ui.node");
+ expect(nodeTab).toBeTruthy();
+ nodeTab!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ const nodeServiceButton = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.includes("dbx-demo-node-service-1"));
+ expect(nodeServiceButton).toBeTruthy();
+ nodeServiceButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+ expect(host.textContent).toContain("owner=DBX");
+ expect(host.textContent).toContain("consul.ui.serviceWeights");
+ expect(host.textContent).toContain("lan=127.0.0.1:19090");
+ expect(nodeServiceButton!.getAttribute("aria-expanded")).toBe("true");
+
+ nodeServiceButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+ expect(host.textContent).not.toContain("lan=127.0.0.1:19090");
+ expect(nodeServiceButton!.getAttribute("aria-expanded")).toBe("false");
+ });
+});
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts
new file mode 100644
index 0000000000..14aed97166
--- /dev/null
+++ b/apps/desktop/src/components/consul/__tests__/ConsulWatchViews.spec.ts
@@ -0,0 +1,267 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const services = readFileSync(new URL("../ConsulServices.vue", import.meta.url), "utf8");
+const health = readFileSync(new URL("../ConsulHealth.vue", import.meta.url), "utf8");
+const overview = readFileSync(new URL("../ConsulOverview.vue", import.meta.url), "utf8");
+const sessions = readFileSync(new URL("../ConsulSessions.vue", import.meta.url), "utf8");
+const scope = readFileSync(new URL("../ConsulScope.vue", import.meta.url), "utf8");
+const keyBrowser = readFileSync(new URL("../ConsulKeyBrowser.vue", import.meta.url), "utf8");
+const mesh = readFileSync(new URL("../ConsulMesh.vue", import.meta.url), "utf8");
+const tools = readFileSync(new URL("../ConsulTools.vue", import.meta.url), "utf8");
+const operator = readFileSync(new URL("../ConsulOperator.vue", import.meta.url), "utf8");
+const workspace = readFileSync(new URL("../ConsulWorkspace.vue", import.meta.url), "utf8");
+const kvBrowser = readFileSync(new URL("../../kv/KvKeyBrowser.vue", import.meta.url), "utf8");
+
+describe("Consul Catalog and Health watch views", () => {
+ it("watches both service and node Catalog resources and cancels them on teardown", () => {
+ for (const target of ["catalogServices", "catalogServiceNodes", "catalogNodes", "catalogNodeServices"]) {
+ expect(services).toContain(`kind: "${target}"`);
+ }
+ expect(services).toMatch(/onBeforeUnmount\(\(\) => \{\s*void stopWatches\(\);\s*\}\);/);
+ expect(services).toContain("switchBrowseMode");
+ });
+
+ it("supports state, node, and service Health resources with a scoped watch", () => {
+ for (const target of ["healthState", "healthNode", "healthServiceInstances"]) {
+ expect(health).toContain(`kind: "${target}"`);
+ }
+ expect(health).toContain('browseMode = ref<"state" | "node" | "service">');
+ expect(health).toMatch(/onBeforeUnmount\(\(\) => \{\s*void stopWatch\(\);\s*\}\);/);
+ expect(health).toContain("selectedCheck");
+ expect(health).toContain("selectedCheck.Definition");
+ });
+
+ it("filters and paginates Health results without querying on every target keystroke", () => {
+ for (const state of ["browseNameDraft", "keywordFilter", "statusFilter", "typeFilter"]) {
+ expect(health).toContain(`const ${state} = ref(`);
+ }
+ for (const collection of ["filteredChecks", "filteredLocalChecks", "pagedChecks", "pagedLocalChecks", "pagedServiceInstances"]) {
+ expect(health).toContain(`const ${collection} = computed(`);
+ }
+ expect(health).toContain('v-model="browseNameDraft"');
+ expect(health).toContain('@keydown.enter="applyBrowseTarget"');
+ expect(health).toContain("t('consul.ui.searchHealthChecks')");
+ expect(health).toContain("<ConsulListPagination");
+ expect(health).not.toContain("watch([state, browseMode, browseName]");
+ });
+
+ it("shows Catalog metadata and independent Overview probe states", () => {
+ expect(services).toContain("item.NodeMeta");
+ expect(services).toContain("item.ServiceMeta");
+ expect(services).toContain("nodeServices?.Node.NodeMeta");
+ for (const state of ["loading", "ready", "forbidden", "unsupported", "error"]) {
+ expect(overview).toContain(`"${state}"`);
+ }
+ expect(overview).toContain("probeStates[key]");
+ });
+
+ it("binds Session renew to connection and scope lifecycle and exposes lock indexes", () => {
+ expect(sessions).toContain("connectionActive");
+ expect(sessions).toContain("consulStore.generation");
+ expect(sessions).toContain("currentScopeKey()");
+ expect(sessions).toContain("clearTimeout(renewTimer)");
+ expect(sessions).toContain("item.lockIndex");
+ expect(sessions).toContain("session.NodeChecks");
+ expect(sessions).toContain("session.ServiceChecks");
+ expect(sessions).toContain("!isTtlSession(session)");
+ expect(sessions).toContain("ConsulListPagination");
+ expect(sessions).toContain("filteredSessions");
+ expect(sessions).toContain("await inspectLockKey()");
+ expect(sessions).toContain("expectedModifyIndex: lockInspection.value.modifyIndex");
+ expect(sessions).toContain("heldKeys[session.ID].complete");
+ expect(sessions).toContain("value.items.map(normalizeConsulSession)");
+ expect(sessions).toContain("withUiTimeout(api.consulSessions(props.connectionId))");
+ });
+
+ it("renders the complete Enterprise delete impact inventory", () => {
+ for (const resource of ["kvKeys", "healthChecks", "sessions", "intentions", "peerings", "aclTokens", "aclPolicies", "aclRoles", "aclAuthMethods", "aclBindingRules"]) {
+ expect(scope).toContain(`value.${resource}`);
+ }
+ expect(scope).toContain("impact.filteredByAcls");
+ expect(scope).toContain("impact.unavailableResources");
+ });
+
+ it("offers both Agent service maintenance transitions", () => {
+ expect(services).toContain("maintenance(service.ID, true)");
+ expect(services).toContain("maintenance(service.ID, false)");
+ expect(services).toContain('t("consul.ui.enableMaintenance")');
+ expect(services).toContain('t("consul.ui.disableMaintenance")');
+ expect(services).toContain('v-if="canAgentWrite"');
+ expect(services).toContain('t("consul.ui.agentWriteDisabledHint"');
+ });
+
+ it("keeps Catalog browsing searchable and separates readable Catalog data from Agent actions", () => {
+ expect(services).toContain('const browseFilter = ref("");');
+ expect(services).toContain("const filteredServiceNames");
+ expect(services).toContain("const filteredNodeNames");
+ expect(services).toContain("const localServiceItems");
+ expect(services).toContain("const filteredLocalServiceItems");
+ expect(services).toContain("<Search class=");
+ expect(services).toContain("selectedLocalService?.ID === service.ID");
+ expect(services).toContain('<Button v-for="name in pagedServiceNames"');
+ expect(services).not.toContain("services[name]?.join(', ')");
+ expect(services).toContain('@click="selectService(name)"');
+ expect(services).toContain('@click="selectNode(name)"');
+ expect(services).toContain("Catalog browsing must remain responsive even when an Agent endpoint is slow or unavailable.");
+ expect(services).toContain("void loadAgentData(current);");
+ expect(services).toContain("t('consul.ui.searchAllServices')");
+ expect(services).toContain("t('consul.ui.searchLocalServices')");
+ });
+
+ it("loads Consul tools independently and exposes complete event and result details", () => {
+ expect(tools).toContain('const activeTab = ref<ToolTab>("queries")');
+ for (const loader of ["loadQueries", "loadEvents", "loadCoordinates"]) {
+ expect(tools).toContain(`async function ${loader}()`);
+ }
+ for (const errorState of ["queryError", "eventError", "coordinateError"]) {
+ expect(tools).toContain(`const ${errorState} = ref("")`);
+ }
+ expect(tools).not.toContain("Promise.allSettled");
+ expect(tools).toContain('v-model="eventNodeFilter"');
+ expect(tools).toContain('v-model="eventServiceFilter"');
+ expect(tools).toContain('v-model="eventTagFilter"');
+ expect(tools).toContain("queryResult.Nodes");
+ expect(tools).toContain("item.Coord.Adjustment");
+ expect(tools).toContain("item.Coord.Height");
+ });
+
+ it("paginates every potentially large service collection before rendering", () => {
+ for (const collection of ["pagedServiceNames", "pagedNodeNames", "pagedCatalogInstances", "pagedNodeServices", "pagedLocalServices"]) {
+ expect(services).toContain(`const ${collection} = computed(() => paginateConsulItems(`);
+ expect(services).toContain(`v-for="${collection === "pagedCatalogInstances" ? "item" : collection.includes("Names") ? "name" : "service"} in ${collection}"`);
+ }
+ expect(services).toContain("<ConsulListPagination");
+ expect(services).toContain(':page-size="CONSUL_LIST_PAGE_SIZE"');
+ });
+
+ it("gates Agent writes on an explicit target that matches the Agent node", () => {
+ for (const source of [services, health]) {
+ expect(source).toContain("config.agentTarget || config.agent_target");
+ expect(source).toContain("consulAgentWriteTargetSafe(store.getConfig(props.connectionId), identity.value?.node)");
+ expect(source).toContain(':disabled="!canAgentWrite"');
+ }
+ });
+
+ it("supports exact-Key and prefix KV watches and exposes batch atomicity", () => {
+ expect(keyBrowser).toContain('watchMode = ref<"key" | "prefix">("prefix")');
+ expect(keyBrowser).toContain('prefix: watchMode.value === "prefix"');
+ expect(keyBrowser).toContain(':on-watch-key="watchSelectedKey"');
+ expect(keyBrowser).toContain("transferReport.atomic");
+ expect(keyBrowser).toContain("deleteReport.atomic");
+ expect(keyBrowser).toContain("row.opIndex");
+ });
+
+ it("keeps the Key prefix search first and groups enhanced Consul KV actions after a divider", () => {
+ expect(keyBrowser).toContain("<template #toolbar-trailing>");
+ expect(keyBrowser).not.toContain('v-model="watchPrefix" class="h-7 w-52 text-xs"');
+ expect(kvBrowser).toContain('<slot name="toolbar-trailing" />');
+ expect(kvBrowser).toContain('class="mx-1 h-6 w-px shrink-0 bg-border"');
+ });
+
+ it("keeps exact-Key watch start and stop beside the selected Key", () => {
+ expect(keyBrowser).toContain(":watch-active-key=\"watchRunning && watchMode === 'key' ? watchPrefix : null\"");
+ expect(keyBrowser).toContain('watchMode.value === "key" && watchPrefix.value === route.key');
+ expect(keyBrowser).toContain("await stopWatch();\n return;");
+ });
+
+ it("serializes search progress polling and invalidates stale pollers", () => {
+ expect(keyBrowser).toContain("searchProgressSequence");
+ expect(keyBrowser).toContain("searchProgressTimer = setTimeout");
+ expect(keyBrowser).toContain("sequence === searchProgressSequence");
+ expect(keyBrowser).not.toContain("searchProgressTimer = setInterval");
+ });
+
+ it("uses a compact Session-protection card and a metadata grid for Consul KV details", () => {
+ expect(kvBrowser).toContain('labels.sessionProtected || "Session protected"');
+ expect(kvBrowser).toContain('labels.sessionProtectedHint || "Editing and deletion are disabled to protect this distributed lock."');
+ expect(kvBrowser).toContain("copyText(selectedMetadata?.session)");
+ expect(kvBrowser).toContain('<dl class="grid grid-cols-2 divide-x divide-y sm:grid-cols-3">');
+ expect(kvBrowser).not.toContain('["Session", metadata?.session]');
+ });
+
+ it("exports the current Consul full-text search result set", () => {
+ expect(keyBrowser).toContain("async function exportSearchResults()");
+ expect(keyBrowser).toContain('format: "dbx-consul-kv-search-results"');
+ expect(keyBrowser).toContain('t("consul.tools.exportSearchResults")');
+ });
+
+ it("carries full-text match metadata into the selected Consul KV detail", () => {
+ expect(keyBrowser).toContain("const searchHighlight = ref<{");
+ expect(keyBrowser).toContain("matchesKey: result.matchesKey");
+ expect(keyBrowser).toContain(':search-highlight="searchHighlight"');
+ });
+
+ it("offers the same server-backed prefix completion for export, migration, and prefix deletion", () => {
+ expect(keyBrowser).toContain('type PrefixSuggestionTarget = "export" | "migration" | "delete"');
+ expect(keyBrowser).toContain("const prefixSuggestionDebounceMs = 300;");
+ expect(keyBrowser).toContain("function schedulePrefixSuggestions(target: PrefixSuggestionTarget, value: string)");
+ expect(keyBrowser).toContain("schedulePrefixSuggestions(target, suggestion.key);");
+ expect(keyBrowser).toContain('event.key !== "Enter" && event.key !== "Tab"');
+ expect(keyBrowser).toContain("prefixSuggestionIndex.value >= 0 ? prefixSuggestionIndex.value : 0");
+ expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('export'");
+ expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('migration'");
+ expect(keyBrowser).toContain("@input=\"schedulePrefixSuggestions('delete'");
+ expect(keyBrowser).toContain("@keydown=\"onPrefixSuggestionKeydown('migration', $event)\"");
+ expect(keyBrowser).toContain("@keydown=\"onPrefixSuggestionKeydown('delete', $event)\"");
+ expect(keyBrowser).toContain('<PopoverContent align="start" side="bottom" :collision-padding="12"');
+ expect(keyBrowser).toContain("max-h-[var(--reka-popover-content-available-height)]");
+ });
+
+ it("marks the specific locked Key and Session in a prefix-delete preview", () => {
+ expect(keyBrowser).toContain("'session' in row && row.session ? 'bg-destructive/5' : ''");
+ expect(keyBrowser).toContain('v-if="\'session\' in row && row.session" variant="destructive"');
+ expect(keyBrowser).toContain('t("consul.ui.sessionValue", { id: row.session })');
+ });
+
+ it("shows the server-provided reason when a prefix-delete operation fails", () => {
+ expect(keyBrowser).toContain("'message' in row && row.message");
+ expect(keyBrowser).toContain(':title="row.message"');
+ });
+
+ it("opens the safe prefix-delete preview from a Consul directory context menu", () => {
+ expect(keyBrowser).toContain(':on-delete-prefix="openDeletePrefix"');
+ expect(keyBrowser).toContain('function openDeletePrefix(prefix = "")');
+ expect(keyBrowser).not.toContain('@click="openDeletePrefix"');
+ expect(kvBrowser).toContain("if (nodeIsExpandable(node) && props.onDeletePrefix)");
+ expect(kvBrowser).toContain("action: () => props.onDeletePrefix?.(nodePath(node))");
+ });
+
+ it("preserves Exported Services CAS state and capability-gates advanced writes", () => {
+ expect(mesh).toContain('consulMeshConfigList(props.connectionId, "exported-services")');
+ expect(mesh).toContain("editingExported.value?.modifyIndex || 0");
+ expect(tools).toContain("canWriteQueries");
+ expect(tools).toContain("canFireEvents");
+ expect(operator).toContain("keyringWriteVisible");
+ expect(operator).toContain("props.capabilities?.operatorKeyring");
+ });
+
+ it("keeps workspace actions fixed while only the tab strip scrolls horizontally", () => {
+ expect(workspace).toContain("min-w-0 flex-1 overflow-x-auto overflow-y-hidden");
+ expect(workspace).toContain("h-8 w-max min-w-max justify-start");
+ expect(workspace).toContain('class="h-7 flex-none gap-1.5 px-3 text-xs"');
+ expect(workspace).toContain("flex h-11 shrink-0 items-center gap-2 border-b px-3");
+ expect(workspace).toContain('class="flex shrink-0 items-center gap-1"');
+ });
+
+ it("starts with KV and keeps the cluster overview as a sidebar surface", () => {
+ expect(workspace).toContain('const activeTab = ref<WorkspaceTab>("kv");');
+ expect(workspace).not.toContain('<TabsTrigger value="overview"');
+ expect(workspace).not.toContain('<TabsContent value="overview"');
+ });
+
+ it("shows the real datacenter by default and gates advanced scope controls by capability", () => {
+ expect(workspace).toContain("const resolvedDatacenter = computed(() => activeScope.value.datacenter || capabilities.value?.datacenter");
+ expect(workspace).toContain('const enterpriseScopeAvailable = computed(() => capabilities.value?.namespaces === "supported" || capabilities.value?.partitions === "supported");');
+ expect(workspace).toContain('v-if="enterpriseScopeAvailable"');
+ expect(workspace).toContain('v-if="datacenterOptions.length > 1" v-model="scopeDraft.datacenter"');
+ });
+
+ it("hides only disabled ACLs and Enterprise-only scope tabs", () => {
+ expect(workspace).toContain('const aclVisible = computed(() => capabilities.value?.acl !== "disabled");');
+ expect(workspace).toContain("const scopeTabVisible = computed(() => enterpriseScopeAvailable.value);");
+ expect(workspace).toContain('v-if="aclVisible" value="acl"');
+ expect(workspace).toContain('v-if="scopeTabVisible" value="scope"');
+ expect(workspace).toContain('if (activeTab.value === "acl" && !aclVisible.value) activeTab.value = "kv";');
+ });
+});
diff --git a/apps/desktop/src/components/consul/__tests__/ConsulWorkspaceInteraction.spec.ts b/apps/desktop/src/components/consul/__tests__/ConsulWorkspaceInteraction.spec.ts
new file mode 100644
index 0000000000..70cf74d9c3
--- /dev/null
+++ b/apps/desktop/src/components/consul/__tests__/ConsulWorkspaceInteraction.spec.ts
@@ -0,0 +1,136 @@
+/** @vitest-environment happy-dom */
+
+import { createApp, nextTick } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ listQueries: vi.fn(async () => []),
+ updateConnection: vi.fn(async () => undefined),
+}));
+
+function mockWorkspaceChild(refresh = vi.fn(() => true)) {
+ return {
+ __esModule: true,
+ default: {
+ setup(_props: unknown, { expose }: { expose: (value: { refresh: () => boolean }) => void }) {
+ expose({ refresh });
+ return () => "mock-consul-child";
+ },
+ },
+ };
+}
+
+vi.mock("@/components/consul/ConsulKeyBrowser.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulServices.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulHealth.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulSessions.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulAcl.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulScope.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulMesh.vue", () => mockWorkspaceChild());
+vi.mock("@/components/consul/ConsulOperator.vue", () => mockWorkspaceChild());
+
+vi.mock("@/lib/backend/api", () => ({
+ consulCapabilities: vi.fn(async () => ({
+ acl: "supported",
+ authMethods: "supported",
+ bindingRules: "supported",
+ templatedPolicies: "supported",
+ namespaces: "supported",
+ partitions: "supported",
+ configEntries: "supported",
+ intentions: "supported",
+ peering: "supported",
+ exportedServices: "supported",
+ preparedQueries: "supported",
+ events: "supported",
+ coordinates: "supported",
+ operatorAutopilot: "supported",
+ operatorRaft: "supported",
+ operatorKeyring: "supported",
+ operatorUsage: "supported",
+ operatorLicense: "supported",
+ audit: "supported",
+ datacenter: "dc1",
+ })),
+ consulCatalogDatacenters: vi.fn(async () => ["dc1", "dc2"]),
+ consulPreparedQueryList: mocks.listQueries,
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ getConfig: () => ({
+ id: "connection-1",
+ external_config: { datacenter: "dc1", consulMeshVisible: true, consulOperatorVisible: true },
+ }),
+ updateConnection: mocks.updateConnection,
+ }),
+}));
+
+vi.mock("@/stores/consulStore", () => ({
+ useConsulStore: () => ({ bindConnection: vi.fn(), switchScope: vi.fn() }),
+}));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+
+import ConsulWorkspace from "../ConsulWorkspace.vue";
+
+const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];
+
+async function settle() {
+ for (let index = 0; index < 8; index += 1) {
+ await Promise.resolve();
+ await nextTick();
+ }
+}
+
+afterEach(() => {
+ for (const { unmount, host } of mountedApps.splice(0)) {
+ unmount();
+ host.remove();
+ }
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+describe("ConsulWorkspace interactions", () => {
+ it("renders a working datacenter selector when multiple datacenters are available", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulWorkspace, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ const scopeButton = Array.from(host.querySelectorAll("button")).find((button) => button.title === "consul.ui.scope");
+ expect(scopeButton).toBeTruthy();
+ scopeButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await settle();
+
+ expect(document.body.querySelector('[role="combobox"]')).toBeTruthy();
+ expect(document.body.textContent).toContain("dc1");
+ });
+
+ it("routes the global refresh action to the active tools tab", async () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(ConsulWorkspace, { connectionId: "connection-1" });
+ app.mount(host);
+ mountedApps.push({ unmount: () => app.unmount(), host });
+ await settle();
+
+ const toolsTab = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.trim() === "consul.workspace.tools");
+ expect(toolsTab).toBeTruthy();
+ toolsTab!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
+ await settle();
+ expect(toolsTab!.getAttribute("aria-selected")).toBe("true");
+ await vi.waitFor(() => expect(mocks.listQueries).toHaveBeenCalled());
+ mocks.listQueries.mockClear();
+
+ const refreshButton = Array.from(host.querySelectorAll("button")).find((button) => button.title === "consul.ui.refresh");
+ expect(refreshButton).toBeTruthy();
+ refreshButton!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await vi.waitFor(() => expect(mocks.listQueries).toHaveBeenCalledTimes(1));
+ });
+});
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index 9c8009c3fb..990f0a7663 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -118,7 +118,7 @@ const showModified = ref(true);
let syncPlanRequestId = 0;
-const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(connection.db_type)));
+const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(connection.db_type)));
const selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
const filteredSourceTables = computed(() => {
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
index 7779d3adb9..db6430f477 100644
--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
@@ -58,7 +58,7 @@ const targetSchemas = ref<string[]>([]);
const sourceDbVersion = ref<string | null>(null);
const targetDbVersion = ref<string | null>(null);
-const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "etcd", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
const sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
diff --git a/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue b/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
index 321825c5d1..97889663fb 100644
--- a/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
+++ b/apps/desktop/src/components/etcd/EtcdKeyBrowser.vue
@@ -295,6 +295,7 @@ const labels = computed(() => ({
editKey: t("etcd.editKey"),
delete: t("etcd.delete"),
deleteTitle: t("etcd.deleteTitle"),
+ keyLabel: t("etcd.key"),
keyPlaceholder: t("etcd.keyPlaceholder"),
keyRequired: t("etcd.keyRequired"),
saved: t("etcd.saved"),
@@ -303,6 +304,9 @@ const labels = computed(() => ({
rename: t("etcd.rename"),
clone: t("etcd.clone"),
copyKey: t("etcd.copyKey"),
+ copy: t("grid.copy"),
+ copied: t("grid.copied"),
+ copyFailed: t("grid.copyFailed"),
export: t("etcd.export"),
history: t("etcd.history"),
restore: t("etcd.restore"),
@@ -1077,6 +1081,9 @@ defineExpose({ focusSearch, refresh });
:read-only="readOnly"
:enable-multi-select="true"
:on-watch-key="openWatchForKey"
+ export-format="dbx-etcd-bundle"
+ export-file-extension=".dbx-etcd.json"
+ export-fallback-name="etcd-key"
:lease-options="leaseOptions"
:on-lease-options-requested="refreshLeaseOptions"
@refresh-requested="refreshTtlCapability"
diff --git a/apps/desktop/src/components/export/DatabaseExportDialog.vue b/apps/desktop/src/components/export/DatabaseExportDialog.vue
index 15645ccb25..f2a919f4e0 100644
--- a/apps/desktop/src/components/export/DatabaseExportDialog.vue
+++ b/apps/desktop/src/components/export/DatabaseExportDialog.vue
@@ -103,7 +103,7 @@ const exportElapsedText = computed(() => {
return formatDataTransferDuration((exportFinishedAt.value ?? currentTime.value) - exportStartedAt.value);
});
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
const canExport = computed(() => {
const hasContent = includeStructure.value || includeData.value || includeObjects.value;
diff --git a/apps/desktop/src/components/icons/DatabaseIcon.vue b/apps/desktop/src/components/icons/DatabaseIcon.vue
index 6810d1987f..d5f56ca62a 100644
--- a/apps/desktop/src/components/icons/DatabaseIcon.vue
+++ b/apps/desktop/src/components/icons/DatabaseIcon.vue
@@ -99,6 +99,7 @@ const assetIcons: Record<string, string> = {
rocketmq: "rocketmq",
rabbitmq: "rabbitmq",
nacos: "nacos.png",
+ consul: "consul",
iris: "iris",
influxdb: "influxdb",
victoriametrics: "victoriametrics.png",
diff --git a/apps/desktop/src/components/kv/KvKeyBrowser.vue b/apps/desktop/src/components/kv/KvKeyBrowser.vue
index e96164d56a..9eecbccd45 100644
--- a/apps/desktop/src/components/kv/KvKeyBrowser.vue
+++ b/apps/desktop/src/components/kv/KvKeyBrowser.vue
@@ -1,15 +1,16 @@
<script setup lang="ts">
-import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
+import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Pane, Splitpanes } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useConnectionStore } from "@/stores/connectionStore";
-import { Activity, Check, ChevronDown, ChevronRight, Clock3, Copy, Download, FolderClosed, FolderOpen, KeyRound, Loader2, Pencil, Plus, RefreshCw, Search, Trash2 } from "@lucide/vue";
+import { Activity, Check, ChevronDown, ChevronRight, Clock3, Copy, Download, FolderClosed, FolderOpen, KeyRound, Loader2, LockKeyhole, Pencil, Plus, RefreshCw, Search, Square, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
@@ -26,20 +27,24 @@ import { formatZooKeeperMetadataRows, formatZooKeeperSummaryBadges, prettyPrintJ
import { formatTtl } from "@/lib/common/ttlFormat";
import {
createLazyKvKeyTreeState,
- createZooKeeperChildPathDraft,
+ createLazyKvChildPathDraft,
flattenLazyKvKeyTree,
+ lazyKvRootPath,
lazyExpandedKeyFromId,
- normalizeZooKeeperPath,
- parentZooKeeperPath,
+ normalizeLazyKvPath,
+ parentLazyKvPath,
replaceLazyKvChildren,
replaceLazyKvFocusedRoot,
resetLazyKvKeyTree,
type LazyKvKeyTreeNode,
type LazyKvKeyTreeRow,
-} from "@/lib/zookeeper/zookeeperLazyKeyTree";
+ type LazyKvKeySummary,
+ type LazyKvPathStyle,
+} from "@/lib/kv/slashPrefixLazyKeyTree";
import { useToast } from "@/composables/useToast";
import { detectKvValueFormat, validateKvValue, type KvValueFormat } from "@/lib/kv/kvValueFormat";
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
+import { copyToClipboard } from "@/lib/common/clipboard";
interface KvKeyBrowserLabels {
prefixPlaceholder: string;
@@ -54,6 +59,7 @@ interface KvKeyBrowserLabels {
editKey: string;
delete: string;
deleteTitle: string;
+ keyLabel?: string;
keyPlaceholder: string;
keyRequired: string;
rootReadonly?: string;
@@ -97,11 +103,22 @@ interface KvKeyBrowserLabels {
summaryLease?: string;
summarySize?: string;
watch?: string;
+ stopWatching?: string;
selectExistingLease?: string;
enterLeaseId?: string;
leasePickerHint?: string;
noLeasePickerHint?: string;
registryWarning?: string;
+ aclFiltered?: string;
+ locked?: string;
+ sessionProtected?: string;
+ sessionProtectedHint?: string;
+ sessionId?: string;
+ copy?: string;
+ copied?: string;
+ copyFailed?: string;
+ valueTooLarge?: string;
+ deletePrefix?: string;
selectAll?: string;
deselectAll?: string;
}
@@ -111,13 +128,22 @@ interface KvCreateModeOption {
label: string;
}
+interface KvSearchHighlight {
+ key: string;
+ query: string;
+ caseSensitive: boolean;
+ matchesKey: boolean;
+ matchesValue: boolean;
+}
+
interface KvKeyBrowserApi {
- listPrefix: (connectionId: string, prefix: string, limit: number, continuation?: string | null, options?: KvListPrefixOptions | null) => Promise<{ keys: KvKeySummary[]; continuation?: string | null; revision?: string | number | null }>;
+ listPrefix: (connectionId: string, prefix: string, limit: number, continuation?: string | null, options?: KvListPrefixOptions | null) => Promise<{ keys: KvKeySummary[]; continuation?: string | null; revision?: string | number | null; filteredByAcls?: boolean | null }>;
get: (connectionId: string, key: string, options?: KvGetOptions | null) => Promise<KvGetResponse>;
getMetadata?: (connectionId: string, key: string, options?: KvGetOptions | null) => Promise<KvGetResponse>;
put: (connectionId: string, key: string, value: KvValue, options?: KvPutOptions | null) => Promise<KvPutResponse>;
deleteKey: (connectionId: string, key: string, options?: KvDeleteOptions | null) => Promise<{ deleted: number }>;
rename?: (connectionId: string, request: { key: string; keyBytes?: KvValue | null; newKey: string; expectedModRevision?: KvInt64 | null }) => Promise<{ renamed: boolean }>;
+ copy?: (connectionId: string, request: { key: string; keyBytes?: KvValue | null; newKey: string; expectedModRevision?: KvInt64 | null }) => Promise<{ copied: boolean }>;
history?: (connectionId: string, request: { key: string; keyBytes?: KvValue | null; startRevision?: KvInt64 | null; endRevision?: KvInt64 | null; limit: number }) => Promise<KvHistoryResponse>;
exportScope?: (connectionId: string, request: KvExportScopeRequest) => Promise<void>;
}
@@ -158,16 +184,25 @@ const props = withDefaults(
supportsCreateModes?: boolean;
supportsTtl?: boolean;
supportsLeaseBinding?: boolean;
+ supportsFlags?: boolean;
ttlCapabilityKnown?: boolean;
createModeOptions?: KvCreateModeOption[];
enableNodeActions?: boolean;
- metadataStyle?: "default" | "zookeeper";
+ metadataStyle?: "default" | "zookeeper" | "consul";
lazyHierarchy?: boolean;
+ lazyPathStyle?: LazyKvPathStyle;
safeWrite?: boolean;
+ maxValueBytes?: number;
allowBinaryEdit?: boolean;
readOnly?: boolean;
+ exportFormat?: string;
+ exportFileExtension?: string;
+ exportFallbackName?: string;
enableMultiSelect?: boolean;
onWatchKey?: (route: KvKeyRoute) => void;
+ onDeletePrefix?: (prefix: string) => void;
+ watchActiveKey?: string | null;
+ searchHighlight?: KvSearchHighlight | null;
leaseOptions?: Array<{ id: KvInt64; ttl: number; grantedTtl?: number }>;
onLeaseOptionsRequested?: () => void;
}>(),
@@ -175,14 +210,21 @@ const props = withDefaults(
supportsCreateModes: false,
supportsTtl: false,
supportsLeaseBinding: false,
+ supportsFlags: false,
ttlCapabilityKnown: true,
createModeOptions: () => [],
enableNodeActions: false,
metadataStyle: "default",
lazyHierarchy: false,
+ lazyPathStyle: "absolute",
safeWrite: false,
+ maxValueBytes: 0,
allowBinaryEdit: false,
readOnly: false,
+ exportFormat: "dbx-kv-bundle",
+ exportFileExtension: ".dbx-kv.json",
+ exportFallbackName: "kv-key",
+ searchHighlight: null,
enableMultiSelect: false,
leaseOptions: () => [],
},
@@ -199,9 +241,11 @@ const searchInputRef = ref<HTMLInputElement>();
const prefix = ref("");
const keySuggestionOpen = ref(false);
const keySuggestionIndex = ref(-1);
+const remoteKeySuggestions = ref<KvKeySummary[]>([]);
const keys = ref<KvKeySummary[]>([]);
const continuation = ref<string | null>(null);
const listRevision = ref<KvInt64 | null>(null);
+const listFilteredByAcls = ref(false);
const loading = ref(false);
const loadingMore = ref(false);
const expandedGroupIds = ref<Set<string>>(new Set());
@@ -216,6 +260,7 @@ const isCreating = ref(false);
const editKey = ref("");
const editValue = ref("");
const editTtl = ref<string | number>("");
+const editFlags = ref("0");
const editExpiryMode = ref<KvExpiryMode>("permanent");
const editLeaseId = ref("");
const editFormat = ref<KvValueFormat>("text");
@@ -223,6 +268,7 @@ const editEncoding = ref<"utf8" | "base64">("utf8");
const editError = ref("");
const editErrorKind = ref<KvMutationErrorKind>("request");
const saving = ref(false);
+const refreshingEditConflict = ref(false);
const showSaveDiff = ref(false);
const pendingSave = ref<{ key: string; value: KvValue; options?: KvPutOptions } | null>(null);
const showDeleteConfirm = ref(false);
@@ -231,6 +277,7 @@ const showRenameDialog = ref(false);
const renameValue = ref("");
const renameError = ref("");
const renaming = ref(false);
+const renameMode = ref<"rename" | "copy">("rename");
const showHistoryDialog = ref(false);
const historyLoading = ref(false);
const historyError = ref("");
@@ -240,8 +287,9 @@ const showHistoryDiff = ref(false);
const restoring = ref(false);
const selectedCreateMode = ref<KvCreateMode>("persistent");
const selectedPrettyValue = ref<string | null>(null);
+const selectedValueCopied = ref(false);
+const lazyTreeState = reactive(createLazyKvKeyTreeState(lazyKvRootPath(props.lazyPathStyle), props.lazyPathStyle));
const multiSelectedKeys = ref<Map<string, KvMultiSelection>>(new Map());
-const lazyTreeState = reactive(createLazyKvKeyTreeState());
const pageSize = 200;
const metadataRefreshIntervalMs = 1000;
const keyListRefreshBaseIntervalMs = 2000;
@@ -258,10 +306,19 @@ let keyListRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let keyListRefreshGeneration = 0;
let keyListRefreshDelayMs = keyListRefreshBaseIntervalMs;
let initialLoadPromise: Promise<void> | null = null;
+const keySuggestionDebounceMs = 300;
+let keySuggestionTimer: ReturnType<typeof setTimeout> | null = null;
+let keySuggestionRequestId = 0;
+let selectedValueCopyTimer: ReturnType<typeof setTimeout> | null = null;
type LoadKeysOptions = {
preserveSelection?: boolean;
};
+type LazyLoadContext = {
+ generation: number;
+ connectionId: string;
+};
+
function summaryIdentity(summary: KvKeySummary): string {
return summary.keyIdentity ?? summary.key;
}
@@ -301,7 +358,8 @@ const keySuggestions = computed(() => {
const seen = new Set<string>();
const suggestions: KvKeySummary[] = [];
- for (const key of keys.value) {
+ const candidates = props.lazyHierarchy ? [...lazyTreeState.nodeByKey.values(), ...remoteKeySuggestions.value] : keys.value;
+ for (const key of candidates) {
if (key.key === query || !key.key.startsWith(query) || seen.has(summaryIdentity(key))) continue;
seen.add(summaryIdentity(key));
suggestions.push(key);
@@ -327,6 +385,9 @@ const selectedTextValue = computed(() => {
const displayedSelectedTextValue = computed(() => selectedPrettyValue.value ?? selectedTextValue.value);
const selectedValueIsBase64 = computed(() => selectedValue.value?.value?.encoding === "base64");
const selectedKeyBytes = computed(() => selectedValue.value?.keyBytes ?? selectedRouteKeyBytes.value ?? null);
+const selectedKeyLocked = computed(() => Boolean(String(selectedMetadata.value?.session ?? "").trim()));
+const isWatchingSelectedKey = computed(() => Boolean(selectedKey.value && props.watchActiveKey === selectedKey.value));
+const activeSearchHighlight = computed(() => (props.searchHighlight?.key === selectedKey.value ? props.searchHighlight : null));
const showExpiryControls = computed(() => props.supportsTtl || props.supportsLeaseBinding);
const showTtlUnavailable = computed(() => props.ttlCapabilityKnown && !props.supportsTtl && !!props.labels.ttlUnavailable);
const showCreateModeSelect = computed(() => props.supportsCreateModes && isCreating.value && props.createModeOptions.length > 0);
@@ -371,10 +432,43 @@ const editValueSize = computed(() => {
}
return new TextEncoder().encode(editValue.value).length;
});
-const canEditSelectedValue = computed(() => !props.readOnly && (!selectedValueIsBase64.value || props.allowBinaryEdit));
+const canEditSelectedValue = computed(() => !props.readOnly && !selectedKeyLocked.value && (!selectedValueIsBase64.value || props.allowBinaryEdit));
+const canDeleteSelectedValue = computed(() => !props.readOnly && !selectedKeyLocked.value);
+const consulMetadataRows = computed(() => {
+ const metadata = selectedMetadata.value;
+ return [
+ ["CreateIndex", metadata?.createRevision],
+ ["ModifyIndex", metadata?.modRevision],
+ ["LockIndex", metadata?.lockIndex],
+ ["Flags", metadata?.flags],
+ [props.labels.summarySize || "Size", metadata?.valueSize == null ? null : `${metadata.valueSize} B`],
+ ].filter((row) => row[1] != null && String(row[1]).length > 0) as Array<[string, string | number]>;
+});
const saveDiffBefore = computed(() => (isCreating.value ? "" : selectedTextValue.value));
const saveDiffAfter = computed(() => pendingSave.value?.value.data ?? editValue.value);
const historyRestoreValue = computed(() => selectedHistoryEvent.value?.value ?? selectedHistoryEvent.value?.previousValue ?? null);
+const selectedKeyHighlightSegments = computed(() => highlightText(selectedKey.value || "", activeSearchHighlight.value?.matchesKey ?? false));
+const selectedValueHighlightSegments = computed(() => highlightText(displayedSelectedTextValue.value, activeSearchHighlight.value?.matchesValue ?? false));
+
+function highlightText(value: string, enabled: boolean): Array<{ text: string; matched: boolean }> {
+ const highlight = activeSearchHighlight.value;
+ const query = highlight?.query.trim() || "";
+ if (!enabled || !query) return [{ text: value, matched: false }];
+
+ const haystack = highlight?.caseSensitive ? value : value.toLocaleLowerCase();
+ const needle = highlight?.caseSensitive ? query : query.toLocaleLowerCase();
+ const segments: Array<{ text: string; matched: boolean }> = [];
+ let cursor = 0;
+ let matchAt = haystack.indexOf(needle, cursor);
+ while (matchAt >= 0) {
+ if (matchAt > cursor) segments.push({ text: value.slice(cursor, matchAt), matched: false });
+ segments.push({ text: value.slice(matchAt, matchAt + query.length), matched: true });
+ cursor = matchAt + query.length;
+ matchAt = haystack.indexOf(needle, cursor);
+ }
+ if (cursor < value.length) segments.push({ text: value.slice(cursor), matched: false });
+ return segments.length ? segments : [{ text: value, matched: false }];
+}
const highRiskRegistryKey = computed(() => editKey.value === "/registry" || editKey.value.startsWith("/registry/"));
function preserveExpandedGroups(expandAll = false) {
@@ -386,11 +480,39 @@ function closeKeySuggestions() {
keySuggestionIndex.value = -1;
}
+function scheduleRemoteKeySuggestions(value: string) {
+ if (keySuggestionTimer) {
+ clearTimeout(keySuggestionTimer);
+ keySuggestionTimer = null;
+ }
+
+ const query = value.trim();
+ if (!props.lazyHierarchy || !query) {
+ remoteKeySuggestions.value = [];
+ return;
+ }
+
+ const requestId = ++keySuggestionRequestId;
+ const connectionId = props.connectionId;
+ keySuggestionTimer = setTimeout(() => {
+ void props.api
+ .listPrefix(connectionId, query, 8, null, { recursive: false })
+ .then((result) => {
+ if (requestId !== keySuggestionRequestId || connectionId !== props.connectionId || prefix.value.trim() !== query) return;
+ remoteKeySuggestions.value = result.keys;
+ })
+ .catch(() => {
+ if (requestId === keySuggestionRequestId) remoteKeySuggestions.value = [];
+ });
+ }, keySuggestionDebounceMs);
+}
+
function onPrefixInput(event: Event) {
const value = (event.target as HTMLInputElement).value;
clearMultiSelection();
keySuggestionOpen.value = Boolean(value.trim());
keySuggestionIndex.value = -1;
+ scheduleRemoteKeySuggestions(value);
}
function moveKeySuggestion(delta: number) {
@@ -404,7 +526,14 @@ function acceptKeySuggestion(index: number) {
if (!suggestion) return;
clearMultiSelection();
prefix.value = suggestion.key;
- closeKeySuggestions();
+ keySuggestionIndex.value = -1;
+ if (props.lazyHierarchy && suggestion.key.endsWith("/")) {
+ keySuggestionOpen.value = true;
+ remoteKeySuggestions.value = [];
+ scheduleRemoteKeySuggestions(suggestion.key);
+ } else {
+ closeKeySuggestions();
+ }
void loadKeys(true);
}
@@ -427,13 +556,17 @@ function onPrefixKeydown(event: KeyboardEvent) {
moveKeySuggestion(-1);
return;
}
- if (event.key !== "Enter") return;
+ if (event.key !== "Enter" && event.key !== "Tab") return;
- event.preventDefault();
- if (showKeySuggestions.value && keySuggestionIndex.value >= 0) {
- acceptKeySuggestion(keySuggestionIndex.value);
+ if (showKeySuggestions.value && keySuggestions.value.length > 0) {
+ event.preventDefault();
+ acceptKeySuggestion(keySuggestionIndex.value >= 0 ? keySuggestionIndex.value : 0);
return;
}
+
+ if (event.key === "Tab") return;
+
+ event.preventDefault();
closeKeySuggestions();
void loadKeys(true);
}
@@ -459,6 +592,7 @@ async function loadKeys(reset = true, options: LoadKeysOptions = {}) {
loading.value = true;
continuation.value = null;
listRevision.value = null;
+ listFilteredByAcls.value = false;
keys.value = [];
if (!options.preserveSelection) {
clearSelectedKey();
@@ -470,6 +604,7 @@ async function loadKeys(reset = true, options: LoadKeysOptions = {}) {
const result = await props.api.listPrefix(connectionId, searchQuery, pageSize, reset ? null : continuation.value, reset || !listRevision.value ? undefined : { revision: listRevision.value });
if (generation !== keyLoadGeneration || props.connectionId !== connectionId) return;
if (reset && result.revision != null) listRevision.value = String(result.revision);
+ if (result.filteredByAcls != null) listFilteredByAcls.value = Boolean(result.filteredByAcls);
const existing = new Set(keys.value.map(summaryIdentity));
const merged = reset ? result.keys : [...keys.value, ...result.keys.filter((key) => !existing.has(summaryIdentity(key)))];
keys.value = merged;
@@ -499,21 +634,46 @@ async function loadLazyRoot(reset = true, options: LoadKeysOptions = {}) {
return;
}
+ const context: LazyLoadContext = {
+ generation: ++keyLoadGeneration,
+ connectionId: props.connectionId,
+ };
const previousExpanded = new Set(expandedGroupIds.value);
loading.value = true;
loadingMore.value = false;
+ listFilteredByAcls.value = false;
if (!options.preserveSelection) {
clearSelectedKey();
}
try {
- const rootPath = normalizeZooKeeperPath(prefix.value);
- resetLazyKvKeyTree(lazyTreeState, rootPath);
- const result = await props.api.listPrefix(props.connectionId, rootPath, pageSize, null, { recursive: false });
- if (rootPath === "/") {
+ const requestedRootPath = normalizeLazyKvPath(prefix.value, props.lazyPathStyle);
+ resetLazyKvKeyTree(lazyTreeState, requestedRootPath);
+ let rootPath = requestedRootPath;
+ let result = await props.api.listPrefix(context.connectionId, rootPath, pageSize, null, { recursive: false });
+ if (!lazyLoadContextValid(context)) return;
+ listFilteredByAcls.value = Boolean(result.filteredByAcls);
+ let rootSummary = rootPath === lazyKvRootPath(props.lazyPathStyle) ? null : await loadLazyRootSummary(context.connectionId, rootPath, result.keys, result.continuation);
+ if (!lazyLoadContextValid(context)) return;
+ // Consul returns `prefix/` as the sole immediate result for a search such as
+ // `prefix`. Load that prefix's children, while preserving an exact `prefix`
+ // Key when it coexists with the virtual directory.
+ const focusedDirectory = props.lazyPathStyle === "relative" && rootPath && !rootPath.endsWith("/") ? result.keys.find((key) => key.key === `${rootPath}/`) : undefined;
+ if (focusedDirectory) {
+ const childResult = await props.api.listPrefix(context.connectionId, focusedDirectory.key, pageSize, null, { recursive: false });
+ if (!lazyLoadContextValid(context)) return;
+ listFilteredByAcls.value ||= Boolean(childResult.filteredByAcls);
+ result = childResult;
+ if (rootSummary?.hasValue !== true) {
+ rootPath = focusedDirectory.key;
+ resetLazyKvKeyTree(lazyTreeState, rootPath);
+ rootSummary = await loadLazyRootSummary(context.connectionId, rootPath, result.keys, result.continuation);
+ if (!lazyLoadContextValid(context)) return;
+ }
+ }
+ if (rootPath === lazyKvRootPath(props.lazyPathStyle)) {
replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation);
} else {
- const rootSummary = await loadLazyRootSummary(rootPath, result.keys, result.continuation);
if (rootSummary) {
replaceLazyKvFocusedRoot(lazyTreeState, rootSummary, result.keys, result.continuation);
} else {
@@ -522,7 +682,8 @@ async function loadLazyRoot(reset = true, options: LoadKeysOptions = {}) {
}
if (options.preserveSelection) {
- await restoreLazyExpandedBranches(previousExpanded);
+ await restoreLazyExpandedBranches(previousExpanded, context);
+ if (!lazyLoadContextValid(context)) return;
expandFocusedRoot(rootPath);
if (keyToRestore && lazyTreeState.nodeByKey.has(keyToRestore)) {
await loadSelectedKey(keyToRestore);
@@ -533,24 +694,39 @@ async function loadLazyRoot(reset = true, options: LoadKeysOptions = {}) {
expandedGroupIds.value = focusedRootExpansion(rootPath);
}
} finally {
- loading.value = false;
+ if (lazyLoadContextValid(context)) loading.value = false;
}
}
-async function loadLazyRootSummary(rootPath: string, children: KvKeySummary[], continuation?: string | null): Promise<KvKeySummary | null> {
+function lazyLoadContextValid(context: LazyLoadContext): boolean {
+ return context.generation === keyLoadGeneration && context.connectionId === props.connectionId;
+}
+
+function currentLazyLoadContext(): LazyLoadContext {
+ return { generation: keyLoadGeneration, connectionId: props.connectionId };
+}
+
+async function loadLazyRootSummary(connectionId: string, rootPath: string, children: KvKeySummary[], continuation?: string | null): Promise<LazyKvKeySummary | null> {
try {
- const rootValue = await props.api.get(props.connectionId, rootPath);
- if (rootValue.found) return { key: rootValue.key || rootPath, ...rootValue.metadata };
+ const rootValue = await props.api.get(connectionId, rootPath);
+ if (rootValue.found) {
+ return {
+ key: rootValue.key || rootPath,
+ ...rootValue.metadata,
+ numChildren: children.length + (continuation ? 1 : 0),
+ hasValue: true,
+ };
+ }
if (children.length === 0 && !continuation) return null;
} catch {
if (children.length === 0 && !continuation) return null;
}
- return { key: rootPath, numChildren: children.length + (continuation ? 1 : 0) };
+ return { key: rootPath, numChildren: children.length + (continuation ? 1 : 0), hasValue: false };
}
function focusedRootExpansion(rootPath: string): Set<string> {
- const normalized = normalizeZooKeeperPath(rootPath);
- if (normalized === "/") return new Set();
+ const normalized = normalizeLazyKvPath(rootPath, props.lazyPathStyle);
+ if (normalized === lazyKvRootPath(props.lazyPathStyle)) return new Set();
return new Set(
focusedPathKeys(normalized)
.filter((key) => lazyTreeState.nodeByKey.has(key))
@@ -563,11 +739,17 @@ function expandFocusedRoot(rootPath: string) {
}
function focusedPathKeys(rootPath: string): string[] {
- const segments = normalizeZooKeeperPath(rootPath).split("/").filter(Boolean);
- return segments.map((_, index) => `/${segments.slice(0, index + 1).join("/")}`);
+ const normalized = normalizeLazyKvPath(rootPath, props.lazyPathStyle);
+ const trailingSlash = props.lazyPathStyle === "relative" && normalized.endsWith("/");
+ const segments = normalized.split("/").filter(Boolean);
+ return segments.map((_, index) => {
+ const joined = segments.slice(0, index + 1).join("/");
+ const isLeaf = index === segments.length - 1;
+ return props.lazyPathStyle === "absolute" ? `/${joined}` : isLeaf && !trailingSlash ? joined : `${joined}/`;
+ });
}
-async function restoreLazyExpandedBranches(previousExpanded: ReadonlySet<string>) {
+async function restoreLazyExpandedBranches(previousExpanded: ReadonlySet<string>, context: LazyLoadContext) {
const restored = new Set<string>();
const keysToExpand = [...previousExpanded]
.map((id) => lazyExpandedKeyFromId(id))
@@ -575,26 +757,31 @@ async function restoreLazyExpandedBranches(previousExpanded: ReadonlySet<string>
.sort((a, b) => a.split("/").length - b.split("/").length);
for (const key of keysToExpand) {
+ if (!lazyLoadContextValid(context)) return;
const node = lazyTreeState.nodeByKey.get(key);
if (!node?.hasChildren) continue;
restored.add(node.id);
- await loadLazyChildren(key, true);
+ await loadLazyChildren(key, true, context);
}
- expandedGroupIds.value = restored;
+ if (lazyLoadContextValid(context)) expandedGroupIds.value = restored;
}
-async function loadLazyChildren(parentKey: string, reset = true) {
+async function loadLazyChildren(parentKey: string, reset = true, context = currentLazyLoadContext()) {
+ if (!lazyLoadContextValid(context)) return;
const node = lazyTreeState.nodeByKey.get(parentKey);
if (!node || node.loading) return;
node.loading = true;
try {
const continuationToUse = reset ? null : node.continuation;
- const result = await props.api.listPrefix(props.connectionId, parentKey, pageSize, continuationToUse, { recursive: false });
- replaceLazyKvChildren(lazyTreeState, parentKey, result.keys, result.continuation, { append: !reset });
+ const childPrefix = props.lazyPathStyle === "relative" && node.hasValue === true && !parentKey.endsWith("/") ? `${parentKey}/` : parentKey;
+ const result = await props.api.listPrefix(context.connectionId, childPrefix, pageSize, continuationToUse, { recursive: false });
+ if (!lazyLoadContextValid(context) || lazyTreeState.nodeByKey.get(parentKey) !== node) return;
+ if (result.filteredByAcls != null) listFilteredByAcls.value ||= Boolean(result.filteredByAcls);
+ replaceLazyKvChildren(lazyTreeState, parentKey, result.keys, result.continuation, { append: !reset, filteredByAcls: result.filteredByAcls });
} finally {
const latest = lazyTreeState.nodeByKey.get(parentKey);
- if (latest) latest.loading = false;
+ if (lazyLoadContextValid(context) && latest === node) latest.loading = false;
}
}
@@ -605,30 +792,40 @@ async function loadMoreLazyChildren(parentKey: string | null) {
}
if (loadingMore.value || !lazyTreeState.rootContinuation) return;
+ const context = currentLazyLoadContext();
+ const rootPath = lazyTreeState.rootPath;
+ const continuationToUse = lazyTreeState.rootContinuation;
loadingMore.value = true;
try {
- const result = await props.api.listPrefix(props.connectionId, lazyTreeState.rootPath, pageSize, lazyTreeState.rootContinuation, { recursive: false });
+ const result = await props.api.listPrefix(context.connectionId, rootPath, pageSize, continuationToUse, { recursive: false });
+ if (!lazyLoadContextValid(context) || lazyTreeState.rootPath !== rootPath || lazyTreeState.rootContinuation !== continuationToUse) return;
+ if (result.filteredByAcls != null) listFilteredByAcls.value ||= Boolean(result.filteredByAcls);
replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation, { append: true });
} finally {
- loadingMore.value = false;
+ if (lazyLoadContextValid(context) && lazyTreeState.rootPath === rootPath) loadingMore.value = false;
}
}
async function refreshLazyParent(parentPath: string) {
- const normalizedParent = normalizeZooKeeperPath(parentPath);
+ const context = currentLazyLoadContext();
+ const normalizedParent = normalizeLazyKvPath(parentPath, props.lazyPathStyle);
if (normalizedParent === lazyTreeState.rootPath) {
- if (lazyTreeState.rootPath === "/") {
- const result = await props.api.listPrefix(props.connectionId, lazyTreeState.rootPath, pageSize, null, { recursive: false });
+ if (lazyTreeState.rootPath === lazyKvRootPath(props.lazyPathStyle)) {
+ const rootPath = lazyTreeState.rootPath;
+ const result = await props.api.listPrefix(context.connectionId, rootPath, pageSize, null, { recursive: false });
+ if (!lazyLoadContextValid(context) || lazyTreeState.rootPath !== rootPath) return;
+ if (result.filteredByAcls != null) listFilteredByAcls.value ||= Boolean(result.filteredByAcls);
replaceLazyKvChildren(lazyTreeState, null, result.keys, result.continuation);
} else {
- await loadLazyChildren(lazyTreeState.rootPath, true);
+ await loadLazyChildren(lazyTreeState.rootPath, true, context);
+ if (!lazyLoadContextValid(context)) return;
expandFocusedRoot(lazyTreeState.rootPath);
}
return;
}
if (lazyTreeState.nodeByKey.has(normalizedParent)) {
- await loadLazyChildren(normalizedParent, true);
+ await loadLazyChildren(normalizedParent, true, context);
} else {
await loadLazyRoot(true, { preserveSelection: true });
}
@@ -638,6 +835,7 @@ async function loadSelectedKey(input: string | KvKeyRoute) {
const route = routeFromKey(input);
const key = route.key;
const keyIdentity = routeIdentity(route);
+ const connectionId = props.connectionId;
stopMetadataRefresh();
const requestId = ++detailRequestId;
selectedKey.value = key;
@@ -648,8 +846,13 @@ async function loadSelectedKey(input: string | KvKeyRoute) {
detailLoading.value = true;
detailError.value = "";
try {
- const result = await props.api.get(props.connectionId, key, route.keyBytes ? { keyBytes: route.keyBytes } : undefined);
- if (requestId !== detailRequestId || selectedKey.value !== key) return;
+ const result = await props.api.get(connectionId, key, route.keyBytes ? { keyBytes: route.keyBytes } : undefined);
+ if (requestId !== detailRequestId || selectedKey.value !== key || connectionId !== props.connectionId) return;
+ const lazyNode = lazyTreeState.nodeByKey.get(key);
+ if (lazyNode) {
+ lazyNode.hasValue = result.found;
+ if (result.found) Object.assign(lazyNode, result.metadata);
+ }
if (!result.found) {
removeExpiredSelectedKey(key);
return;
@@ -660,10 +863,10 @@ async function loadSelectedKey(input: string | KvKeyRoute) {
startMetadataRefresh(key);
startKeyListRefresh();
} catch (error) {
- if (requestId !== detailRequestId || selectedKey.value !== key) return;
+ if (requestId !== detailRequestId || selectedKey.value !== key || connectionId !== props.connectionId) return;
detailError.value = error instanceof Error ? error.message : String(error);
} finally {
- if (requestId === detailRequestId) detailLoading.value = false;
+ if (requestId === detailRequestId && connectionId === props.connectionId) detailLoading.value = false;
}
}
@@ -756,6 +959,21 @@ async function refreshKnownLeaseKeys(generation: number) {
}
function removeExpiredSelectedKey(key: string) {
+ if (props.lazyHierarchy) {
+ const lazyNode = lazyTreeState.nodeByKey.get(key);
+ if (lazyNode?.hasChildren) {
+ // A separator-based listing initially cannot tell whether `prefix/` is
+ // also a real Key. A failed exact GET only proves that it is a virtual
+ // directory; it must not clear the directory's expansion state.
+ lazyNode.hasValue = false;
+ } else {
+ // A known leaf disappeared. Refresh only its parent so the stale row is
+ // removed without rebuilding or collapsing the rest of the tree.
+ void refreshLazyParent(parentLazyKvPath(key, props.lazyPathStyle));
+ }
+ clearSelectedKey();
+ return;
+ }
keys.value = selectedKeyIdentity.value ? keys.value.filter((item) => summaryIdentity(item) !== selectedKeyIdentity.value) : removeMissingKvKey(keys.value, key);
preserveExpandedGroups();
clearSelectedKey();
@@ -893,7 +1111,7 @@ function onRowDoubleClick(node: BrowserTreeNode) {
}
function createKeyPrefix(parentPath?: string): string {
- if (props.lazyHierarchy) return createZooKeeperChildPathDraft(parentPath ?? prefix.value);
+ if (props.lazyHierarchy) return createLazyKvChildPathDraft(parentPath ?? prefix.value, props.lazyPathStyle);
const path = parentPath ?? prefix.value.trim();
if (!path) return "";
if (path === "/") return "/";
@@ -906,6 +1124,7 @@ function openCreateDialog(parentPath?: string) {
editKey.value = createKeyPrefix(parentPath);
editValue.value = "";
editTtl.value = "";
+ editFlags.value = "0";
editExpiryMode.value = "permanent";
editLeaseId.value = "";
editEncoding.value = "utf8";
@@ -932,6 +1151,7 @@ function openEditDialog() {
editExpiryMode.value = existingLease && existingLease !== "0" ? "lease" : "permanent";
editLeaseId.value = editExpiryMode.value === "lease" ? existingLease : "";
editTtl.value = "";
+ editFlags.value = String(selectedMetadata.value?.flags ?? "0");
editError.value = "";
editErrorKind.value = "request";
showEditDialog.value = true;
@@ -950,6 +1170,8 @@ function putOptions(): KvPutOptions | undefined {
options.keyBytes = selectedKeyBytes.value;
}
}
+ if (props.supportsFlags) options.flags = editFlags.value.trim();
+ else if (!isCreating.value && selectedMetadata.value?.flags != null) options.flags = String(selectedMetadata.value.flags);
if (props.supportsCreateModes) {
if (isCreating.value) {
options.writeMode = "create";
@@ -976,7 +1198,7 @@ async function saveKey() {
editError.value = props.labels.keyRequired;
return;
}
- if (props.lazyHierarchy && normalizeZooKeeperPath(rawKey) === "/") {
+ if (props.lazyHierarchy && normalizeLazyKvPath(rawKey, props.lazyPathStyle) === lazyKvRootPath(props.lazyPathStyle)) {
editError.value = props.labels.rootReadonly || props.labels.keyRequired;
return;
}
@@ -995,13 +1217,17 @@ async function saveKey() {
editError.value = props.labels.leaseInvalid || "Lease ID must be a positive 64-bit integer";
return;
}
- const key = props.lazyHierarchy ? normalizeZooKeeperPath(rawKey) : rawKey;
+ const key = props.lazyHierarchy ? normalizeLazyKvPath(rawKey, props.lazyPathStyle) : rawKey;
const validationError = validateKvValue(editValue.value, editFormat.value);
if (validationError) {
editError.value = validationError;
return;
}
const value: KvValue = { encoding: editEncoding.value, data: editValue.value.replace(editEncoding.value === "base64" ? /\s+/g : /$^/, "") };
+ if (props.maxValueBytes > 0 && editValueSize.value > props.maxValueBytes) {
+ editError.value = props.labels.valueTooLarge || `Value exceeds ${props.maxValueBytes} bytes`;
+ return;
+ }
pendingSave.value = { key, value, options: putOptions() };
showSaveDiff.value = true;
}
@@ -1019,7 +1245,7 @@ async function confirmSaveKey() {
showEditDialog.value = false;
pendingSave.value = null;
if (props.lazyHierarchy) {
- await refreshLazyParent(parentZooKeeperPath(keyToSelect));
+ await refreshLazyParent(parentLazyKvPath(keyToSelect, props.lazyPathStyle));
} else {
await loadKeys(true);
}
@@ -1038,9 +1264,26 @@ async function confirmSaveKey() {
}
}
+async function refreshAfterMutationConflict() {
+ const key = selectedKey.value;
+ if (!key || isCreating.value || refreshingEditConflict.value) return;
+ refreshingEditConflict.value = true;
+ try {
+ await loadSelectedKey(key);
+ if (selectedValue.value?.found) {
+ editError.value = "";
+ editErrorKind.value = "request";
+ } else {
+ editError.value = props.labels.notFound;
+ }
+ } finally {
+ refreshingEditConflict.value = false;
+ }
+}
+
async function deleteSelectedKey() {
- if (!selectedKey.value) return;
- const parentPath = parentZooKeeperPath(selectedKey.value);
+ if (!selectedKey.value || !selectedValue.value?.found || !canDeleteSelectedValue.value) return;
+ const parentPath = parentLazyKvPath(selectedKey.value, props.lazyPathStyle);
deleting.value = true;
try {
await props.api.deleteKey(
@@ -1070,6 +1313,9 @@ async function deleteSelectedKey() {
}
async function selectNodeForAction(node: BrowserTreeNode) {
+ if (node.kind === "lazy" && node.hasValue === null) {
+ await loadSelectedKey(routeFromNode(node));
+ }
if (!nodeHasValue(node)) return;
const route = routeFromNode(node);
if (selectedKeyIdentity.value !== routeIdentity(route)) await loadSelectedKey(route);
@@ -1083,6 +1329,7 @@ async function selectNodeForAction(node: BrowserTreeNode) {
async function openDeleteForNode(node: BrowserTreeNode) {
if (props.readOnly) return;
await selectNodeForAction(node);
+ if (!selectedKey.value || !selectedValue.value?.found || !canDeleteSelectedValue.value) return;
showDeleteConfirm.value = true;
}
@@ -1095,6 +1342,31 @@ async function copySelectedKey() {
await navigator.clipboard.writeText(selectedKey.value);
}
+async function copyText(value: string | number | null | undefined) {
+ const text = String(value ?? "").trim();
+ if (!text) return;
+ await navigator.clipboard.writeText(text);
+}
+
+async function copySelectedValue() {
+ if (!selectedValue.value?.found) return;
+ try {
+ await copyToClipboard(selectedTextValue.value);
+ selectedValueCopied.value = true;
+ toast(props.labels.copied || "Copied", 1500);
+ if (selectedValueCopyTimer) clearTimeout(selectedValueCopyTimer);
+ selectedValueCopyTimer = setTimeout(() => {
+ selectedValueCopied.value = false;
+ selectedValueCopyTimer = null;
+ }, 1500);
+ } catch (error) {
+ selectedValueCopied.value = false;
+ const message = error instanceof Error ? error.message : String(error);
+ const failureTemplate = props.labels.copyFailed || "Copy failed: {message}";
+ toast(failureTemplate.includes("{message}") ? failureTemplate.replace("{message}", message) : `${failureTemplate}: ${message}`, 3500);
+ }
+}
+
function watchSelectedKey() {
if (!selectedKey.value || !props.onWatchKey) return;
props.onWatchKey({
@@ -1116,10 +1388,10 @@ function downloadText(filename: string, content: string, type = "application/jso
function exportSelectedKey() {
if (!selectedKey.value || !selectedValue.value?.found) return;
downloadText(
- `${selectedKey.value.split("/").filter(Boolean).pop() || "etcd-key"}.dbx-etcd.json`,
+ `${selectedKey.value.split("/").filter(Boolean).pop() || props.exportFallbackName}${props.exportFileExtension}`,
JSON.stringify(
{
- format: "dbx-etcd-bundle",
+ format: props.exportFormat,
version: 1,
exportedAt: new Date().toISOString(),
prefix: selectedKey.value,
@@ -1156,6 +1428,13 @@ async function exportNode(node: BrowserTreeNode) {
async function openCloneDialog() {
if (!selectedKey.value || !selectedValue.value?.found || props.readOnly) return;
+ if (props.api.copy) {
+ renameMode.value = "copy";
+ renameValue.value = selectedKey.value;
+ renameError.value = "";
+ showRenameDialog.value = true;
+ return;
+ }
isCreating.value = true;
editKey.value = selectedKey.value;
editValue.value = selectedTextValue.value;
@@ -1164,6 +1443,7 @@ async function openCloneDialog() {
editExpiryMode.value = "permanent";
editLeaseId.value = "";
editTtl.value = "";
+ editFlags.value = String(selectedMetadata.value?.flags ?? "0");
editError.value = "";
editErrorKind.value = "request";
showEditDialog.value = true;
@@ -1180,13 +1460,16 @@ function onEditFormatChange(value: unknown) {
function openRenameDialog() {
if (!selectedKey.value || !props.api.rename || props.readOnly) return;
+ renameMode.value = "rename";
renameValue.value = selectedKey.value;
renameError.value = "";
showRenameDialog.value = true;
}
-async function renameSelectedKey() {
- if (!selectedKey.value || !props.api.rename) return;
+async function moveOrCopySelectedKey() {
+ if (!selectedKey.value) return;
+ const mutation = renameMode.value === "copy" ? props.api.copy : props.api.rename;
+ if (!mutation) return;
const next = renameValue.value.trim();
if (!next) {
renameError.value = props.labels.keyRequired;
@@ -1195,7 +1478,7 @@ async function renameSelectedKey() {
renaming.value = true;
renameError.value = "";
try {
- await props.api.rename(props.connectionId, {
+ await mutation(props.connectionId, {
key: selectedKey.value,
keyBytes: selectedKeyBytes.value,
newKey: next,
@@ -1277,12 +1560,6 @@ function nodeContextMenuItems(node: BrowserTreeNode): ContextMenuItem[] {
action: () => void loadSelectedKey(routeFromNode(node)).then(openEditDialog),
disabled: props.readOnly,
},
- {
- label: props.labels.rename || "Rename",
- icon: Pencil,
- action: () => void loadSelectedKey(routeFromNode(node)).then(openRenameDialog),
- disabled: props.readOnly || !props.api.rename,
- },
{
label: props.labels.clone || "Clone",
icon: Copy,
@@ -1294,13 +1571,22 @@ function nodeContextMenuItems(node: BrowserTreeNode): ContextMenuItem[] {
icon: Copy,
action: () => void copySelectedKey(),
},
- {
+ );
+ if (props.api.rename) {
+ items.splice(2, 0, {
+ label: props.labels.rename || "Rename",
+ icon: Pencil,
+ action: () => void loadSelectedKey(routeFromNode(node)).then(openRenameDialog),
+ disabled: props.readOnly,
+ });
+ }
+ if (props.api.history) {
+ items.push({
label: props.labels.history || "History",
icon: Clock3,
action: () => void loadSelectedKey(routeFromNode(node)).then(openHistory),
- disabled: !props.api.history,
- },
- );
+ });
+ }
}
if (props.api.exportScope || nodeHasValue(node)) {
items.push({
@@ -1309,19 +1595,30 @@ function nodeContextMenuItems(node: BrowserTreeNode): ContextMenuItem[] {
action: () => void exportNode(node),
});
}
- items.push({
- label: props.labels.delete,
- icon: Trash2,
- variant: "destructive",
- action: () => void openDeleteForNode(node),
- disabled: props.readOnly || !nodeHasValue(node),
- });
+ if (nodeIsExpandable(node) && props.onDeletePrefix) {
+ items.push({
+ label: props.labels.deletePrefix || props.labels.delete,
+ icon: Trash2,
+ variant: "destructive",
+ action: () => props.onDeletePrefix?.(nodePath(node)),
+ disabled: props.readOnly,
+ });
+ } else {
+ items.push({
+ label: props.labels.delete,
+ icon: Trash2,
+ variant: "destructive",
+ action: () => void openDeleteForNode(node),
+ disabled: props.readOnly || !nodeHasValue(node),
+ });
+ }
return items;
}
-function onRowContextMenu(event: MouseEvent, node: BrowserTreeNode, openContextMenu: (event: MouseEvent) => void) {
+async function onRowContextMenu(event: MouseEvent, node: BrowserTreeNode, openContextMenu: (event: MouseEvent) => void) {
if (!props.enableNodeActions) return;
- void selectNodeForAction(node);
+ await selectNodeForAction(node);
+ await nextTick();
openContextMenu(event);
}
@@ -1334,7 +1631,8 @@ function nodeIsExpandable(node: BrowserTreeNode): boolean {
}
function nodeHasValue(node: BrowserTreeNode): boolean {
- return node.kind === "leaf" || node.kind === "lazy" || Boolean(node.key);
+ if (node.kind === "lazy") return node.hasValue === true;
+ return node.kind === "leaf" || Boolean(node.key);
}
function nodeIsExpanded(node: BrowserTreeNode): boolean {
@@ -1404,6 +1702,8 @@ async function selectKeyFromNavigation(key: string | KvKeyRoute) {
watch(
() => props.connectionId,
async () => {
+ keySuggestionRequestId++;
+ remoteKeySuggestions.value = [];
stopKeyListRefresh();
clearSelectedKey();
clearMultiSelection();
@@ -1427,6 +1727,11 @@ watch(
watch(
() => selectedKey.value,
() => {
+ selectedValueCopied.value = false;
+ if (selectedValueCopyTimer) {
+ clearTimeout(selectedValueCopyTimer);
+ selectedValueCopyTimer = null;
+ }
startKeyListRefresh();
},
);
@@ -1463,6 +1768,9 @@ onMounted(() => {
});
onBeforeUnmount(() => {
+ keyLoadGeneration++;
+ if (keySuggestionTimer) clearTimeout(keySuggestionTimer);
+ if (selectedValueCopyTimer) clearTimeout(selectedValueCopyTimer);
clearSelectedKey();
clearMultiSelection();
stopKeyListRefresh();
@@ -1482,25 +1790,34 @@ defineExpose({
<template>
<div class="flex h-full min-h-0 flex-col bg-background">
- <div class="flex shrink-0 items-center gap-2 border-b px-3 py-2">
- <div class="relative min-w-0 flex-1">
- <Search class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- ref="searchInputRef"
- v-model="prefix"
- class="h-8 pl-8"
- role="combobox"
- aria-autocomplete="list"
- :aria-expanded="showKeySuggestions"
- aria-controls="kv-key-prefix-suggestions"
- :aria-activedescendant="keySuggestionIndex >= 0 ? `kv-key-prefix-suggestion-${keySuggestionIndex}` : undefined"
- :placeholder="labels.prefixPlaceholder"
- @input="onPrefixInput"
- @focus="keySuggestionOpen = Boolean(prefix.trim())"
- @blur="closeKeySuggestions"
- @keydown="onPrefixKeydown"
- />
- <div v-if="showKeySuggestions" id="kv-key-prefix-suggestions" role="listbox" class="absolute z-50 mt-1 max-h-64 w-full overflow-auto rounded-md border bg-popover py-1 text-popover-foreground shadow-lg">
+ <div class="flex shrink-0 items-center gap-2 border-b bg-muted/15 px-3 py-2.5 overflow-x-auto">
+ <div v-if="$slots['toolbar-actions']" class="flex shrink-0 items-center gap-1">
+ <slot name="toolbar-actions" />
+ </div>
+ <div v-if="$slots['toolbar-actions']" class="h-6 w-px shrink-0 bg-border" />
+ <Popover :open="showKeySuggestions">
+ <PopoverAnchor as-child>
+ <div class="relative min-w-64 flex-1">
+ <Search class="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ ref="searchInputRef"
+ v-model="prefix"
+ class="h-9 pl-8"
+ autocomplete="off"
+ role="combobox"
+ aria-autocomplete="list"
+ :aria-expanded="showKeySuggestions"
+ aria-controls="kv-key-prefix-suggestions"
+ :aria-activedescendant="keySuggestionIndex >= 0 ? `kv-key-prefix-suggestion-${keySuggestionIndex}` : undefined"
+ :placeholder="labels.prefixPlaceholder"
+ @input="onPrefixInput"
+ @focus="keySuggestionOpen = Boolean(prefix.trim())"
+ @blur="closeKeySuggestions"
+ @keydown="onPrefixKeydown"
+ />
+ </div>
+ </PopoverAnchor>
+ <PopoverContent v-if="showKeySuggestions" id="kv-key-prefix-suggestions" align="start" side="bottom" :collision-padding="12" class="z-[60] max-h-[var(--reka-popover-content-available-height)] w-[var(--reka-popover-trigger-width)] gap-0 overflow-y-auto p-1" @open-auto-focus.prevent>
<button
v-for="(suggestion, index) in keySuggestions"
:id="`kv-key-prefix-suggestion-${index}`"
@@ -1516,8 +1833,8 @@ defineExpose({
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span class="truncate">{{ suggestion.key }}</span>
</button>
- </div>
- </div>
+ </PopoverContent>
+ </Popover>
<div v-if="enableMultiSelect && multiSelectedKeys.size" class="flex shrink-0 items-center gap-1.5">
<Button size="sm" variant="outline" class="h-7 px-2 text-xs" @click="selectAllMultiSelection()">{{ labels.selectAll || "Select all" }}</Button>
<Button size="sm" variant="outline" class="h-7 px-2 text-xs" @click="clearMultiSelection()">{{ labels.deselectAll || "Clear" }}</Button>
@@ -1527,10 +1844,18 @@ defineExpose({
<RefreshCw v-else class="h-3.5 w-3.5" />
{{ t("grid.refresh") }}
</Button>
- <Button size="sm" class="h-8 gap-1.5" :disabled="readOnly" @click="openCreateDialog()">
+ <Button size="sm" class="h-9 gap-1.5" :disabled="readOnly" @click="openCreateDialog()">
<Plus class="h-3.5 w-3.5" />
{{ labels.newKey }}
</Button>
+ <div v-if="$slots['toolbar-trailing']" class="ml-1 flex shrink-0 items-center gap-1">
+ <div class="mx-1 h-6 w-px shrink-0 bg-border" />
+ <slot name="toolbar-trailing" />
+ </div>
+ </div>
+
+ <div v-if="listFilteredByAcls" class="shrink-0 border-b border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
+ {{ labels.aclFiltered || "Some Consul KV keys are hidden by ACL policies." }}
</div>
<Splitpanes class="kv-browser-splitpanes min-h-0 flex-1" @resized="handleKvBrowserSplitResized">
@@ -1547,9 +1872,10 @@ defineExpose({
<template v-for="row in visibleRows" :key="row.type === 'node' ? row.node.id : row.id">
<CustomContextMenu v-if="row.type === 'node'" :items="nodeContextMenuItems(row.node)" v-slot="{ onContextMenu }">
<div
- class="flex h-8 w-full items-center gap-1.5 pr-2 text-left transition-colors hover:bg-accent"
+ class="flex h-8 w-full select-none items-center gap-1.5 pr-2 text-left transition-colors hover:bg-accent"
:class="rowIsSelected(row.node) ? 'bg-primary/10 font-medium text-foreground shadow-[inset_3px_0_0_hsl(var(--primary))]' : ''"
:style="{ paddingLeft: `${8 + row.depth * 18}px` }"
+ @mousedown.right.prevent
@contextmenu="(event) => onRowContextMenu(event, row.node, onContextMenu)"
>
<button
@@ -1575,6 +1901,7 @@ defineExpose({
<ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
<FolderOpen v-if="nodeIsExpanded(row.node)" class="h-4 w-4 shrink-0 text-sky-500" />
<FolderClosed v-else class="h-4 w-4 shrink-0 text-sky-500" />
+ <KeyRound v-if="row.node.kind === 'lazy' && row.node.hasValue === true" class="h-3.5 w-3.5 shrink-0 text-sky-500" />
</template>
<template v-else>
<span class="w-3.5 shrink-0" />
@@ -1609,13 +1936,25 @@ defineExpose({
<div v-else class="flex min-h-full flex-col">
<div class="flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3">
<div class="min-w-0">
- <div class="truncate font-medium" :class="{ 'text-blue-600 dark:text-blue-400': metadataStyle === 'zookeeper' }">{{ selectedKey }}</div>
+ <div class="truncate font-medium" :class="{ 'text-blue-600 dark:text-blue-400': metadataStyle === 'zookeeper' }">
+ <template v-for="(segment, index) in selectedKeyHighlightSegments" :key="index">
+ <mark v-if="segment.matched" class="rounded-sm bg-amber-300/80 px-0.5 text-foreground dark:bg-amber-500/40">{{ segment.text }}</mark>
+ <span v-else>{{ segment.text }}</span>
+ </template>
+ </div>
<div class="mt-1 flex flex-wrap gap-1.5 text-xs text-muted-foreground">
<template v-if="metadataStyle === 'zookeeper'">
<Badge v-for="badge in zookeeperSummaryBadges" :key="badge.label" variant="outline" class="rounded-full">
{{ `${badge.label} ${badge.value}` }}
</Badge>
</template>
+ <template v-else-if="metadataStyle === 'consul'">
+ <Badge variant="secondary">ModifyIndex {{ metadataLabel(selectedMetadata?.modRevision) }}</Badge>
+ <Badge v-if="selectedKeyLocked" variant="outline" class="gap-1 border-amber-500/40 text-amber-700 dark:text-amber-300" :title="labels.locked || 'This key is held by a Consul session and cannot be edited or deleted.'">
+ <LockKeyhole class="h-3 w-3" />{{ labels.sessionProtected || "Session protected" }}
+ </Badge>
+ <Badge variant="outline">{{ metadataLabel(selectedMetadata?.valueSize) }} B</Badge>
+ </template>
<template v-else>
<Badge variant="secondary">rev {{ metadataLabel(selectedMetadata?.modRevision) }}</Badge>
<Badge variant="outline">ver {{ metadataLabel(selectedMetadata?.version) }}</Badge>
@@ -1627,8 +1966,9 @@ defineExpose({
</div>
<div class="flex shrink-0 gap-2">
<Button v-if="onWatchKey" size="sm" variant="outline" class="h-8 gap-1.5" @click="watchSelectedKey">
- <Activity class="h-3.5 w-3.5" />
- {{ labels.watch || "Watch" }}
+ <Square v-if="isWatchingSelectedKey" class="h-3.5 w-3.5" />
+ <Activity v-else class="h-3.5 w-3.5" />
+ {{ isWatchingSelectedKey ? labels.stopWatching || "Stop" : labels.watch || "Watch" }}
</Button>
<Button v-if="api.history" size="sm" variant="outline" class="h-8 gap-1.5" @click="openHistory">
<Clock3 class="h-3.5 w-3.5" />
@@ -1637,7 +1977,7 @@ defineExpose({
<Button size="sm" variant="outline" class="h-8" :disabled="!canEditSelectedValue" @click="openEditDialog">
{{ labels.edit }}
</Button>
- <Button size="sm" variant="destructive" class="h-8 gap-1.5" :disabled="readOnly" @click="showDeleteConfirm = true">
+ <Button size="sm" variant="destructive" class="h-8 gap-1.5" :disabled="!canDeleteSelectedValue" @click="showDeleteConfirm = true">
<Trash2 class="h-3.5 w-3.5" />
{{ labels.delete }}
</Button>
@@ -1652,9 +1992,41 @@ defineExpose({
{{ labels.notFound }}
</div>
<div v-else class="flex min-h-0 flex-1 flex-col gap-4 p-4">
+ <div v-if="selectedKeyLocked" class="flex flex-col gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-amber-800 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between">
+ <div class="flex min-w-0 items-start gap-2">
+ <LockKeyhole class="mt-0.5 h-4 w-4 shrink-0" />
+ <div class="min-w-0">
+ <div class="text-sm font-medium">{{ labels.sessionProtected || "Session protected" }}</div>
+ <div class="mt-0.5 text-xs text-amber-700 dark:text-amber-300">{{ labels.sessionProtectedHint || "Editing and deletion are disabled to protect this distributed lock." }}</div>
+ </div>
+ </div>
+ <div class="min-w-0 rounded-md border border-amber-500/30 bg-background/60 px-2.5 py-1.5 text-xs text-foreground sm:max-w-[22rem]">
+ <div class="mb-1 text-[11px] font-medium text-muted-foreground">{{ labels.sessionId || "Session ID" }}</div>
+ <div class="flex min-w-0 items-center gap-1.5">
+ <code class="min-w-0 flex-1 truncate font-mono" :title="String(selectedMetadata?.session || '')">{{ selectedMetadata?.session }}</code>
+ <Button size="icon" variant="ghost" class="h-6 w-6 shrink-0" :title="labels.copy || 'Copy'" @click="copyText(selectedMetadata?.session)"><Copy class="h-3.5 w-3.5" /></Button>
+ </div>
+ </div>
+ </div>
<div class="min-h-0">
<div v-if="metadataStyle === 'zookeeper'" class="mb-2 text-xs font-medium text-muted-foreground">{{ labels.value || "Value" }}</div>
- <pre class="dbx-editor-font-family m-0 max-h-[40vh] min-h-32 overflow-auto rounded-md border bg-muted/20 whitespace-pre-wrap break-words p-3 text-sm">{{ displayedSelectedTextValue }}</pre>
+ <div class="relative">
+ <Button
+ size="icon"
+ variant="ghost"
+ class="absolute right-2 top-2 z-10 h-8 w-8 border border-transparent bg-background/80 text-muted-foreground shadow-sm backdrop-blur-sm hover:border-border hover:bg-background hover:text-foreground"
+ :title="selectedValueCopied ? labels.copied || 'Copied' : labels.copy || 'Copy'"
+ :aria-label="selectedValueCopied ? labels.copied || 'Copied' : labels.copy || 'Copy'"
+ @click="copySelectedValue"
+ >
+ <Check v-if="selectedValueCopied" class="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
+ <Copy v-else class="h-4 w-4" />
+ </Button>
+ <pre
+ data-native-clipboard
+ class="dbx-editor-font-family m-0 max-h-[40vh] min-h-32 overflow-auto rounded-md border bg-muted/20 whitespace-pre-wrap break-words p-3 pr-12 text-sm"
+ ><template v-for="(segment, index) in selectedValueHighlightSegments" :key="index"><mark v-if="segment.matched" class="rounded-sm bg-amber-300/80 px-0.5 text-foreground dark:bg-amber-500/40">{{ segment.text }}</mark><span v-else>{{ segment.text }}</span></template></pre>
+ </div>
<div v-if="selectedValueCanPrettyJson" class="mt-2 flex justify-end">
<Button size="sm" variant="outline" class="h-8" @click="prettifySelectedJson">
{{ labels.prettyJson || "Pretty" }}
@@ -1670,6 +2042,17 @@ defineExpose({
</div>
</div>
</div>
+ <div v-else-if="metadataStyle === 'consul'" class="border-t pt-4">
+ <div class="overflow-hidden rounded-lg border bg-muted/20">
+ <div class="border-b bg-muted/30 px-3 py-2 text-xs font-medium text-muted-foreground">{{ labels.metadata || "Metadata" }}</div>
+ <dl class="grid grid-cols-2 divide-x divide-y sm:grid-cols-3">
+ <div v-for="row in consulMetadataRows" :key="row[0]" class="min-w-0 px-3 py-2.5">
+ <dt class="text-[11px] font-medium text-muted-foreground">{{ row[0] }}</dt>
+ <dd class="dbx-editor-font-family mt-1 truncate text-sm font-medium text-blue-600 dark:text-blue-400" :title="String(row[1])">{{ row[1] }}</dd>
+ </div>
+ </dl>
+ </div>
+ </div>
</div>
</div>
</div>
@@ -1683,7 +2066,7 @@ defineExpose({
</DialogHeader>
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
<div class="grid gap-2">
- <Label for="kv-edit-key">Key</Label>
+ <Label for="kv-edit-key">{{ labels.keyLabel || "Key" }}</Label>
<Input id="kv-edit-key" v-model="editKey" class="h-10 font-mono" :aria-invalid="editErrorKind === 'keyAlreadyExists'" :disabled="!isCreating" :placeholder="labels.keyPlaceholder" />
<div v-if="editError && editErrorKind === 'keyAlreadyExists'" class="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-700 dark:text-amber-300">
{{ editError }}
@@ -1779,7 +2162,14 @@ defineExpose({
</Button>
</div>
</section>
- <div v-if="editError && editErrorKind !== 'keyAlreadyExists'" class="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">{{ editError }}</div>
+ <div v-if="editError && editErrorKind !== 'keyAlreadyExists'" class="flex items-center justify-between gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
+ <span>{{ editError }}</span>
+ <Button v-if="editErrorKind === 'conflict' && !isCreating" size="sm" variant="outline" class="h-8 shrink-0 gap-1.5" :disabled="refreshingEditConflict" @click="refreshAfterMutationConflict">
+ <Loader2 v-if="refreshingEditConflict" class="h-3.5 w-3.5 animate-spin" />
+ <RefreshCw v-else class="h-3.5 w-3.5" />
+ {{ t("grid.refresh") }}
+ </Button>
+ </div>
</div>
<DialogFooter class="mx-0 mb-0 shrink-0 gap-3 border-t bg-muted/10 px-6 py-5">
<Button variant="outline" class="h-10 min-w-20" @click="showEditDialog = false">{{ t("common.cancel") }}</Button>
@@ -1796,17 +2186,17 @@ defineExpose({
<Dialog v-model:open="showRenameDialog">
<DialogContent class="sm:max-w-lg">
<DialogHeader>
- <DialogTitle>{{ labels.rename || "Rename key" }}</DialogTitle>
+ <DialogTitle>{{ renameMode === "copy" ? labels.clone || "Clone key" : labels.rename || "Rename key" }}</DialogTitle>
</DialogHeader>
<div class="grid gap-2 py-2">
- <Input v-model="renameValue" :placeholder="labels.keyPlaceholder" @keyup.enter="renameSelectedKey" />
+ <Input v-model="renameValue" :placeholder="labels.keyPlaceholder" @keyup.enter="moveOrCopySelectedKey" />
<div v-if="renameError" class="text-sm text-destructive">{{ renameError }}</div>
</div>
<DialogFooter>
<Button variant="outline" :disabled="renaming" @click="showRenameDialog = false">{{ t("common.cancel") }}</Button>
- <Button :disabled="renaming || readOnly" @click="renameSelectedKey">
+ <Button :disabled="renaming || readOnly" @click="moveOrCopySelectedKey">
<Loader2 v-if="renaming" class="mr-2 h-4 w-4 animate-spin" />
- {{ labels.rename || "Rename" }}
+ {{ renameMode === "copy" ? labels.clone || "Clone" : labels.rename || "Rename" }}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts
index c9dfe70eaf..8f8f547707 100644
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts
+++ b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserExport.spec.ts
@@ -5,6 +5,19 @@ const browserSource = readFileSync(new URL("../KvKeyBrowser.vue", import.meta.ur
const etcdBrowserSource = readFileSync(new URL("../../etcd/EtcdKeyBrowser.vue", import.meta.url), "utf8");
describe("KvKeyBrowser node export", () => {
+ it("keeps directory toggles out of the detail-loading path", () => {
+ expect(browserSource).toContain('if (node.kind === "lazy") return node.hasValue === true;');
+ expect(browserSource).toContain("if (props.enableNodeActions && nodeHasValue(node)) void loadSelectedKey(routeFromNode(node));");
+ expect(browserSource).not.toContain("function nodeMayHaveValue");
+ });
+
+ it("keeps an expanded virtual Consul directory open when its exact Key probe is absent", () => {
+ expect(browserSource).toContain("const lazyNode = lazyTreeState.nodeByKey.get(key);");
+ expect(browserSource).toContain("if (lazyNode?.hasChildren)");
+ expect(browserSource).toContain("lazyNode.hasValue = false;");
+ expect(browserSource).toContain("void refreshLazyParent(parentLazyKvPath(key, props.lazyPathStyle));");
+ });
+
it("shows export for both value keys and virtual directories", () => {
expect(browserSource).toContain("if (props.api.exportScope || nodeHasValue(node))");
expect(browserSource).toContain('kind: nodeIsExpandable(node) ? "prefix" : "key"');
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserLayout.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserLayout.spec.ts
index c5da44c36c..582ece1960 100644
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserLayout.spec.ts
+++ b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserLayout.spec.ts
@@ -20,4 +20,12 @@ describe("KvKeyBrowser edit dialog layout", () => {
expect(browserSource).toContain('<DialogFooter class="mx-0 mb-0 shrink-0 border-t px-6 py-5">');
expect(browserSource).toContain('class="h-10 min-w-20" @click="showHistoryDialog = false"');
});
+
+ it("keeps an accessible copy action in the upper-right corner of the value panel", () => {
+ expect(browserSource).toContain('class="absolute right-2 top-2 z-10 h-8 w-8');
+ expect(browserSource).toContain('@click="copySelectedValue"');
+ expect(browserSource).toContain('<Check v-if="selectedValueCopied"');
+ expect(browserSource).toContain('<Copy v-else class="h-4 w-4" />');
+ expect(browserSource).toMatch(/<pre\s+data-native-clipboard/);
+ });
});
diff --git a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts
index e7ad4bc39d..f395ccfc0d 100644
--- a/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts
+++ b/apps/desktop/src/components/kv/__tests__/KvKeyBrowserSearchAndSplit.spec.ts
@@ -10,6 +10,48 @@ describe("KvKeyBrowser search and split layout", () => {
expect(browserSource).not.toContain("filterKvKeysBySearch(result.keys, query)");
});
+ it("focuses a matching Consul directory instead of nesting it beneath itself", () => {
+ expect(browserSource).toContain('const focusedDirectory = props.lazyPathStyle === "relative" && rootPath && !rootPath.endsWith("/")');
+ expect(browserSource).toContain("key.key === `${rootPath}/`");
+ expect(browserSource).toContain("const childResult = await props.api.listPrefix(context.connectionId, focusedDirectory.key, pageSize, null, { recursive: false });");
+ expect(browserSource).toContain("if (rootSummary?.hasValue !== true)");
+ expect(browserSource).toContain("hasValue: true");
+ });
+
+ it("offers debounced, server-backed prefix completion for lazy Consul trees", () => {
+ expect(browserSource).toContain("const remoteKeySuggestions = ref<KvKeySummary[]>([]);");
+ expect(browserSource).toContain("const keySuggestionDebounceMs = 300;");
+ expect(browserSource).toContain("function scheduleRemoteKeySuggestions(value: string)");
+ expect(browserSource).toContain("listPrefix(connectionId, query, 8, null, { recursive: false })");
+ expect(browserSource).toContain("const candidates = props.lazyHierarchy ? [...lazyTreeState.nodeByKey.values(), ...remoteKeySuggestions.value] : keys.value;");
+ expect(browserSource).toContain('autocomplete="off"');
+ expect(browserSource).toContain('<Popover :open="showKeySuggestions">');
+ expect(browserSource).toContain('<PopoverContent v-if="showKeySuggestions" id="kv-key-prefix-suggestions"');
+ expect(browserSource).toContain('if (props.lazyHierarchy && suggestion.key.endsWith("/"))');
+ expect(browserSource).toContain("scheduleRemoteKeySuggestions(suggestion.key);");
+ expect(browserSource).toContain('event.key !== "Enter" && event.key !== "Tab"');
+ });
+
+ it("drops stale lazy tree responses after a connection or root generation changes", () => {
+ expect(browserSource).toContain("generation: ++keyLoadGeneration");
+ expect(browserSource).toContain("function lazyLoadContextValid(context: LazyLoadContext)");
+ expect(browserSource).toContain("context.connectionId === props.connectionId");
+ expect(browserSource).toContain("lazyTreeState.nodeByKey.get(parentKey) !== node");
+ expect(browserSource).toContain("keyLoadGeneration++;");
+ });
+
+ it("highlights the matching search query only for the selected search result", () => {
+ expect(browserSource).toContain("interface KvSearchHighlight");
+ expect(browserSource).toMatch(/const activeSearchHighlight = computed\(\(\) => \(?props\.searchHighlight\?\.key === selectedKey\.value/);
+ expect(browserSource).toContain("function highlightText(value: string, enabled: boolean)");
+ expect(browserSource).toContain("selectedValueHighlightSegments");
+ });
+
+ it("does not select Key text while opening its context menu", () => {
+ expect(browserSource).toContain("select-none items-center");
+ expect(browserSource).toContain("@mousedown.right.prevent");
+ });
+
it("uses a persisted draggable split between the Key tree and details", () => {
expect(browserSource).toContain('<Splitpanes class="kv-browser-splitpanes min-h-0 flex-1" @resized="handleKvBrowserSplitResized">');
expect(browserSource).toContain('<Pane :size="kvBrowserSplitSize" min-size="20" max-size="70">');
diff --git a/apps/desktop/src/components/layout/AppTabBar.vue b/apps/desktop/src/components/layout/AppTabBar.vue
index 4425f5dfd2..e67a8b57b1 100644
--- a/apps/desktop/src/components/layout/AppTabBar.vue
+++ b/apps/desktop/src/components/layout/AppTabBar.vue
@@ -525,7 +525,8 @@ function tabMenuIcon(tab: QueryTab) {
if (tab.externalSqlFileMissing) return AlertTriangle;
if (tab.mode === "data" || tab.mode === "mongo" || tab.mode === "redis" || tab.mode === "hbase") return Table2;
if (tab.mode === "vector") return TableProperties;
- if (tab.mode === "etcd" || tab.mode === "zookeeper") return KeyRound;
+ if (tab.mode === "etcd" || tab.mode === "zookeeper" || tab.mode === "consul") return KeyRound;
+ if (tab.mode === "consul-overview") return Gauge;
if (tab.mode === "etcd-dashboard") return Gauge;
if (tab.mode === "etcd-access-control") return ShieldCheck;
if (tab.mode === "nacos") return Network;
@@ -671,7 +672,8 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<Table2 v-else-if="tab.mode === 'data' || tab.mode === 'mongo' || tab.mode === 'redis' || tab.mode === 'hbase'" class="h-3.5 w-3.5" />
<DatabaseIcon v-else-if="tab.mode === 'mq'" :db-type="tabDatabaseIconType(tab)" class="h-3.5 w-3.5" />
<TableProperties v-else-if="tab.mode === 'vector'" class="h-3.5 w-3.5" />
- <KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper'" class="h-3.5 w-3.5" />
+ <KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper' || tab.mode === 'consul'" class="h-3.5 w-3.5" />
+ <Gauge v-else-if="tab.mode === 'consul-overview'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
@@ -867,7 +869,8 @@ function onOverflowItemKeydown(event: KeyboardEvent, tabId: string, kind: "regul
<Table2 v-else-if="tab.mode === 'data' || tab.mode === 'mongo' || tab.mode === 'redis' || tab.mode === 'hbase'" class="h-3.5 w-3.5" />
<DatabaseIcon v-else-if="tab.mode === 'mq'" :db-type="tabDatabaseIconType(tab)" class="h-3.5 w-3.5" />
<TableProperties v-else-if="tab.mode === 'vector'" class="h-3.5 w-3.5" />
- <KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper'" class="h-3.5 w-3.5" />
+ <KeyRound v-else-if="tab.mode === 'etcd' || tab.mode === 'zookeeper' || tab.mode === 'consul'" class="h-3.5 w-3.5" />
+ <Gauge v-else-if="tab.mode === 'consul-overview'" class="h-3.5 w-3.5" />
<Gauge v-else-if="tab.mode === 'etcd-dashboard'" class="h-3.5 w-3.5" />
<ShieldCheck v-else-if="tab.mode === 'etcd-access-control'" class="h-3.5 w-3.5" />
<Network v-else-if="tab.mode === 'nacos'" class="h-3.5 w-3.5" />
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 4d5f6ef1a1..6bb529f395 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -53,6 +53,8 @@ const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/Etcd
const EtcdDashboard = defineAsyncComponent(() => import("@/components/etcd/EtcdDashboard.vue"));
const EtcdAccessControl = defineAsyncComponent(() => import("@/components/etcd/EtcdAccessControl.vue"));
const ZooKeeperKeyBrowser = defineAsyncComponent(() => import("@/components/zookeeper/ZooKeeperKeyBrowser.vue"));
+const ConsulOverview = defineAsyncComponent(() => import("@/components/consul/ConsulOverview.vue"));
+const ConsulWorkspace = defineAsyncComponent(() => import("@/components/consul/ConsulWorkspace.vue"));
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
const MongoGridFsBrowser = defineAsyncComponent(() => import("@/components/document/MongoGridFsBrowser.vue"));
const MongoBucketBrowser = defineAsyncComponent(() => import("@/components/document/MongoBucketBrowser.vue"));
@@ -242,6 +244,8 @@ function openDataGridExtractorConfiguration() {
const etcdKeyBrowserRef = ref<SearchableBrowserHandle>();
const etcdDashboardRef = ref<{ refresh?: () => boolean }>();
const zookeeperKeyBrowserRef = ref<SearchableBrowserHandle>();
+const consulOverviewRef = ref<{ refresh?: () => boolean }>();
+const consulWorkspaceRef = ref<SearchableBrowserHandle>();
const objectBrowserRef = ref<SearchableBrowserHandle>();
const activeTableMeta = computed(() => props.activeTab.tableMeta);
const activeDataTabTableMeta = computed(() => tableMetaForDataTab(props.activeTab));
@@ -778,6 +782,7 @@ function focusSearch(): boolean {
if (props.activeTab.mode === "redis") return redisKeyBrowserRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "etcd") return etcdKeyBrowserRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.focusSearch() ?? false;
+ if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "objects") return objectBrowserRef.value?.focusSearch() ?? false;
if (props.activeTab.mode === "query") return queryEditorRef.value?.openSearch() ?? false;
return dataGridRef.value?.focusSearch() ?? false;
@@ -795,6 +800,8 @@ function refreshData(): boolean {
if (props.activeTab.mode === "etcd") return etcdKeyBrowserRef.value?.refresh?.() ?? false;
if (props.activeTab.mode === "etcd-dashboard") return etcdDashboardRef.value?.refresh?.() ?? false;
if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.refresh?.() ?? false;
+ if (props.activeTab.mode === "consul-overview") return consulOverviewRef.value?.refresh?.() ?? false;
+ if (props.activeTab.mode === "consul") return consulWorkspaceRef.value?.refresh?.() ?? false;
// Restored data tabs intentionally omit row data, so refresh must work before DataGrid mounts.
if (canReloadUnavailableDataTab(props.activeTab)) {
emit("reload");
@@ -1941,6 +1948,19 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
</div>
</template>
+ <template v-else-if="activeTab.mode === 'consul-overview'">
+ <div class="flex-1 min-h-0">
+ <ConsulOverview ref="consulOverviewRef" :key="activeTab.id" :connection-id="activeTab.connectionId" />
+ </div>
+ </template>
+
+ <!-- Consul management workspace -->
+ <template v-else-if="activeTab.mode === 'consul'">
+ <div class="flex-1 min-h-0">
+ <ConsulWorkspace ref="consulWorkspaceRef" :key="activeTab.id" :connection-id="activeTab.connectionId" />
+ </div>
+ </template>
+
<!-- Document mode: MongoDB collections and Elasticsearch indices -->
<template v-else-if="activeTab.mode === 'mongo'">
<div class="flex-1 min-h-0">
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 35cdc51010..833f76859d 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -109,6 +109,7 @@ const supportsExplain = computed(() => {
dbType !== "chromadb" &&
dbType !== "etcd" &&
dbType !== "zookeeper" &&
+ dbType !== "consul" &&
dbType !== "mq" &&
dbType !== "nacos" &&
dbType !== "victoriametrics"
@@ -490,6 +491,7 @@ async function changeCatalog(selectedCatalog: string) {
activeConnection?.db_type !== 'weaviate' &&
activeConnection?.db_type !== 'chromadb' &&
activeConnection?.db_type !== 'zookeeper' &&
+ activeConnection?.db_type !== 'consul' &&
!isSingleDb
"
class="flex items-center gap-1"
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index a49b3b39fe..877eb0934a 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -252,7 +252,7 @@ const isRootListPartial = computed(() => sidebarFilterGuards.value.isRootListPar
const SEARCH_SCOPE_TO_NODE_TYPES: Record<SearchScope, TreeNodeType[]> = {
connection: ["connection"],
- database: ["database", "redis-db", "mq-tenant", "nacos-namespace", "mongo-db"],
+ database: ["database", "redis-db", "mq-tenant", "nacos-namespace", "consul-root", "mongo-db"],
schema: ["schema"],
table: ["table", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index"],
view: ["view"],
@@ -1094,7 +1094,7 @@ function resolveLoadedLocateTarget(target: ActiveTabSidebarTarget, candidate: Qu
}
async function ensureTreeLoadedForTarget(target: ActiveTabSidebarTarget, opts?: { force?: boolean }) {
- if (target.type === "saved-sql-file" || target.type === "etcd-root" || target.type === "etcd-dashboard" || target.type === "etcd-access-control" || target.type === "zookeeper-root") return;
+ if (target.type === "saved-sql-file" || target.type === "etcd-root" || target.type === "etcd-dashboard" || target.type === "etcd-access-control" || target.type === "zookeeper-root" || target.type === "consul-root") return;
const connId = target.connectionId;
if (!connId) return;
@@ -1132,7 +1132,7 @@ async function ensureTreeLoadedForTarget(target: ActiveTabSidebarTarget, opts?:
}
}
- if (config.db_type === "mq" || config.db_type === "nacos") return;
+ if (config.db_type === "mq" || config.db_type === "nacos" || config.db_type === "consul") return;
if (!("database" in target) || !target.database) return;
// Find the database node
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 2733f9f89a..18582949b8 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -94,7 +94,7 @@ import {
usesTreeSchemaMode,
isSingleDatabase,
} from "@/lib/database/databaseCapabilities";
-import { copyNameForTreeNode, isDocumentBrowserTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/sidebar/treeNodeClick";
+import { copyNameForTreeNode, isDirectNavigationTreeNode, isDocumentBrowserTreeNode, objectSourceKindForTreeNode, shouldRunTreeNodeRowAction, treeNodeRowAction, treeNodeRowDoubleClickAction } from "@/lib/sidebar/treeNodeClick";
import { mongoCollectionTableTypeFromNode, mongoDropIndexFailureCount } from "@/lib/sidebar/mongoCollectionMutation";
import { dataTabOpenModeFromTreeClick, type DataTabOpenMode } from "@/lib/sidebar/dataTabOpenPolicy";
import { isCopySidebarSelectionShortcut, isEditSidebarConnectionShortcut, isPasteSidebarSelectionShortcut } from "@/lib/editor/keyboardShortcuts";
@@ -538,8 +538,31 @@ function isGroupLabel(node: TreeNode): boolean {
return groupTypes.has(node.type);
}
+async function openDirectNavigationNode(node: TreeNode) {
+ if (!node.connectionId) return;
+ await connectionStore.ensureConnected(node.connectionId);
+ const connectionName = connectionStore.getConfig(node.connectionId)?.name || "Consul";
+ if (node.type === "consul-root") {
+ queryStore.createTab(node.connectionId, "", `${connectionName}:keys`, "consul");
+ refreshActiveKvBrowserAfterOpen("consul", node.connectionId);
+ } else if (node.type === "consul-overview") {
+ queryStore.createTab(node.connectionId, "", `${connectionName}:${t("consul.ui.overview")}`, "consul-overview");
+ }
+}
+
async function toggle() {
const node = activeNode.value;
+ if (isDirectNavigationTreeNode(node.type)) {
+ try {
+ await openDirectNavigationNode(node);
+ } catch (e: any) {
+ const errMsg = e?.message || String(e);
+ if (errMsg.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
+ toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ openDriverStoreForInstallError(errMsg, node);
+ }
+ return;
+ }
if (node.isLoading) {
if (node.isExpanded) {
node.isExpanded = false;
@@ -607,6 +630,8 @@ async function toggle() {
await connectionStore.loadEtcdRoot(node.connectionId);
} else if (config?.db_type === "zookeeper") {
await connectionStore.loadZooKeeperRoot(node.connectionId);
+ } else if (config?.db_type === "consul") {
+ await connectionStore.loadConsulRoot(node.connectionId);
} else if (config?.db_type === "mongodb") {
await connectionStore.loadMongoDatabases(node.connectionId);
} else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch") {
@@ -779,7 +804,7 @@ function runRowClickAction(clickDetail: number) {
}
}
-function refreshActiveKvBrowserAfterOpen(mode: "etcd" | "zookeeper", connectionId: string) {
+function refreshActiveKvBrowserAfterOpen(mode: "etcd" | "zookeeper" | "consul", connectionId: string) {
void nextTick(() => {
window.dispatchEvent(new CustomEvent("dbx-refresh-active-kv-browser", { detail: { mode, connectionId } }));
});
@@ -3385,7 +3410,7 @@ const canOpenSqlFileExecution = computed(() => {
const canExportAllDatabases = computed(() => {
if (activeNode.value.type !== "connection" || !activeNode.value.connectionId) return false;
const dbType = connectionStore.getConfig(activeNode.value.connectionId)?.db_type;
- return !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(dbType || "");
+ return !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(dbType || "");
});
const canOpenDiagram = computed(() => {
@@ -4328,7 +4353,7 @@ function buildSpecialSidebarMenu(context: SidebarMenuFactoryContext): boolean {
return true;
}
- if (node.type === "etcd-root" || node.type === "etcd-dashboard" || node.type === "etcd-access-control" || node.type === "zookeeper-root") {
+ if (node.type === "etcd-root" || node.type === "etcd-dashboard" || node.type === "etcd-access-control" || node.type === "zookeeper-root" || node.type === "consul-root" || node.type === "consul-overview") {
items.push({ label: t("contextMenu.openConnection"), action: toggle, icon: Database });
return true;
}
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index 8004b9a78f..c3b8975f31 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -72,6 +72,7 @@ import { useDragSort } from "@/composables/useDragSort";
import { sidebarTreeRuntimeKey } from "@/lib/sidebar/sidebarTreeRuntime";
import { treeNodePinKey } from "@/lib/app/pinnedItems";
import { isTreeGroupNodeType } from "@/lib/sidebar/treeNodeGroup";
+import { shouldActivateTreeNodeOnSingleClick } from "@/lib/sidebar/treeNodeClick";
const { t } = useI18n();
@@ -265,7 +266,10 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {
case "etcd-access-control":
return { icon: ShieldCheck, colorClass: "text-sky-500" };
case "zookeeper-root":
+ case "consul-root":
return { icon: Database, colorClass: "text-blue-500" };
+ case "consul-overview":
+ return { icon: Gauge, colorClass: "text-blue-500" };
case "mongo-db":
return { icon: Database, colorClass: "text-yellow-500" };
case "mongo-gridfs":
@@ -1069,7 +1073,7 @@ function onClick(event: MouseEvent) {
}
selectSingleTreeNode(props.node);
rowRef.value?.focus({ preventScroll: true });
- if (settingsStore.editorSettings.sidebarActivation === "double" && props.node.type !== "load-more") return;
+ if (!shouldActivateTreeNodeOnSingleClick(props.node.type, settingsStore.editorSettings.sidebarActivation) && props.node.type !== "load-more") return;
treeRuntime.handleRowClick(props.node, event.detail);
}
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
index 667a45dccc..efc88781da 100644
--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
@@ -113,7 +113,7 @@ function resetPerFileState() {
currentFileName.value = "";
}
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
const selectedConnection = computed(() => sqlConnections.value.find((c) => c.id === connectionId.value));
diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts
index 1cf9d5e97b..0c417d849e 100644
--- a/apps/desktop/src/composables/useQuickOpen.ts
+++ b/apps/desktop/src/composables/useQuickOpen.ts
@@ -19,7 +19,7 @@ const QUICK_OPEN_MAX_RESULTS = 200;
const INITIAL_SQL_LIBRARY_LIMIT = 20;
const INITIAL_SQL_FILE_LIMIT = 20;
-const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos"]);
+const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos", "consul"]);
export interface QuickOpenItem {
id: string;
diff --git a/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts b/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts
new file mode 100644
index 0000000000..395b66a1a8
--- /dev/null
+++ b/apps/desktop/src/i18n/__tests__/consulUiParity.spec.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import en from "../locales/en";
+import es from "../locales/es";
+import it_ from "../locales/it";
+import ja from "../locales/ja";
+import ko from "../locales/ko";
+import ptBR from "../locales/pt-BR";
+import zhCN from "../locales/zh-CN";
+import zhTW from "../locales/zh-TW";
+
+const locales: Array<[string, Record<string, unknown>]> = [
+ ["en", en],
+ ["es", es],
+ ["it", it_],
+ ["ja", ja],
+ ["ko", ko],
+ ["pt-BR", ptBR],
+ ["zh-CN", zhCN],
+ ["zh-TW", zhTW],
+];
+
+function leafKeys(value: unknown, prefix = ""): string[] {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return [prefix];
+ return Object.entries(value as Record<string, unknown>).flatMap(([key, child]) => leafKeys(child, prefix ? `${prefix}.${key}` : key));
+}
+
+describe("Consul advanced UI locale parity", () => {
+ const expected = leafKeys((en as { consul: { ui: unknown } }).consul.ui).sort();
+ const expectedTools = leafKeys((en as { consul: { tools: unknown } }).consul.tools).sort();
+
+ it.each(locales)("%s exposes the full consul.ui key set", (_name, locale) => {
+ const ui = (locale as { consul: { ui: unknown } }).consul.ui;
+ expect(leafKeys(ui).sort()).toEqual(expected);
+ });
+
+ it.each(locales)("%s exposes the full consul.tools key set", (_name, locale) => {
+ const tools = (locale as { consul: { tools: unknown } }).consul.tools;
+ expect(leafKeys(tools).sort()).toEqual(expectedTools);
+ });
+
+ it("uses Chinese labels for the Consul KV workflow", () => {
+ const consul = (zhCN as { consul: { tools: Record<string, unknown>; keyLabel: string; valueContent: string; format: string } }).consul;
+ const tools = consul.tools;
+ expect(tools.search).toBe("全文搜索");
+ expect(tools.exportPrefix).toBe("导出");
+ expect(tools.import).toBe("导入");
+ expect(tools.migrate).toBe("同步");
+ expect(tools.deletePrefix).toBe("前缀删除");
+ expect(consul.keyLabel).toBe("键(Key)");
+ expect(consul.valueContent).toBe("值");
+ expect(consul.format).toBe("格式");
+ });
+
+ it("localizes Consul service, Session, and capability labels", () => {
+ const ui = (zhCN as { consul: { ui: Record<string, unknown> } }).consul.ui;
+ expect(ui.serviceKind).toBe("服务类型(ServiceKind)");
+ expect(ui.serviceWeights).toBe("通过 / 警告权重");
+ expect(ui.behaviorRelease).toBe("释放锁(release)");
+ expect(ui.behaviorDelete).toBe("删除 Key(delete)");
+ expect(ui.capabilityDisabled).toBe("未启用");
+ });
+
+ it.each(["ConsulOverview", "ConsulServices", "ConsulHealth", "ConsulSessions", "ConsulAcl", "ConsulScope", "ConsulMesh", "ConsulTools", "ConsulOperator", "ConsulWorkspace"])("%s uses the i18n composable", (component) => {
+ const source = readFileSync(new URL(`../../components/consul/${component}.vue`, import.meta.url), "utf8");
+ expect(source).toContain('import { useI18n } from "vue-i18n"');
+ expect(source).toContain("useI18n()");
+ });
+
+ it("keeps Consul user-facing labels out of component templates", () => {
+ const components = ["ConsulServices", "ConsulHealth", "ConsulSessions", "ConsulMesh", "ConsulKeyBrowser", "ConsulOperator"];
+ const forbidden = [
+ "Catalog nodes",
+ "No visible services",
+ "No visible nodes",
+ "Agent target:",
+ "Watch paused",
+ "Watching index",
+ "Pause watch",
+ "Start watch",
+ "HTTP Agent registrations belong",
+ "Catalog instances",
+ "Node services",
+ "Local Agent services",
+ "Enable maintenance",
+ "Disable maintenance",
+ "No matching health checks",
+ "Service instances",
+ "Local Agent checks",
+ 'placeholder="Watch prefix"',
+ ">Key</Badge>",
+ ">Value</Badge>",
+ 'placeholder="UPDATE AUTOPILOT"',
+ 'placeholder="CHANGE KEYRING"',
+ 'placeholder="UPDATE LICENSE"',
+ ">ServiceKind<",
+ ">Passing / Warning<",
+ ">Node ID<",
+ ">TaggedAddresses<",
+ ">EnableTagOverride<",
+ ">Behavior<",
+ ">CreateIndex<",
+ ">ModifyIndex<",
+ "Session {{ row.session }}",
+ ];
+
+ for (const component of components) {
+ const source = readFileSync(new URL(`../../components/consul/${component}.vue`, import.meta.url), "utf8");
+ const template = source.slice(source.indexOf("<template>"));
+ for (const literal of forbidden) expect(template, `${component} contains ${literal}`).not.toContain(literal);
+ }
+ });
+});
diff --git a/apps/desktop/src/i18n/locales/consulUi.ts b/apps/desktop/src/i18n/locales/consulUi.ts
new file mode 100644
index 0000000000..b6bc4f88b2
--- /dev/null
+++ b/apps/desktop/src/i18n/locales/consulUi.ts
@@ -0,0 +1,455 @@
+// Shared fallback for Consul's advanced workspaces. Individual locales may override these keys.
+export const consulUiMessages = {
+ ui: {
+ unknown: "Unknown",
+ peeringPending: "Pending",
+ peeringEstablishing: "Establishing",
+ peeringActive: "Active",
+ peeringFailing: "Failing",
+ peeringDeleting: "Deleting",
+ peeringTerminated: "Terminated",
+ refresh: "Refresh",
+ cancel: "Cancel",
+ create: "Create",
+ update: "Update",
+ save: "Save",
+ delete: "Delete",
+ edit: "Edit",
+ apply: "Apply",
+ close: "Close",
+ hide: "Hide",
+ reveal: "Reveal",
+ copy: "Copy",
+ copied: "Copied",
+ copyFailed: "Copy failed",
+ copyOnce: "Copy once",
+ pause: "Pause",
+ watchAction: "Watch",
+ watchPrefix: "Watch prefix",
+ watchModePrefix: "Prefix",
+ watchModeKey: "Exact key",
+ sessionProtected: "Protected by Session",
+ sessionProtectedHint: "Editing and deletion are disabled to protect this distributed lock.",
+ atomicTransaction: "Atomic transaction",
+ nonAtomicBatches: "Non-atomic across {count} batches",
+ batchOperation: "Batch {batch} · OpIndex {op}",
+ operationTotals: "Succeeded {succeeded} · Conflicted {conflicted} · Skipped {skipped} · Failed {failed}",
+ deleteOperationTotals: "Succeeded {succeeded} · Conflicted {conflicted} · Failed {failed}",
+ clientSideMigration: "DBX reads from the source and writes to the target. This is not native Consul cross-Datacenter replication.",
+ bundleFileType: "DBX Consul KV Bundle",
+ sourceKeyMissingModifyIndex: "Source key has no ModifyIndex",
+ transactionRejected: "Consul rejected the transaction",
+ overview: "Cluster overview",
+ capabilities: "Capabilities",
+ probeLoading: "Loading",
+ probeReady: "Ready",
+ probeForbidden: "Forbidden",
+ probeUnsupported: "Unsupported",
+ probeError: "Error",
+ autopilotHealth: "Autopilot health",
+ datacenter: "Datacenter",
+ agentNode: "Agent node",
+ agentAddress: "Agent address",
+ version: "Version",
+ mode: "Mode",
+ server: "Server",
+ client: "Client",
+ leader: "Leader",
+ raftPeers: "Raft peers",
+ membersAlive: "Members alive",
+ members: "Members",
+ node: "Node",
+ address: "Address",
+ status: "Status",
+ alive: "alive",
+ leaving: "leaving",
+ failed: "failed",
+ previousPage: "Previous page",
+ nextPage: "Next page",
+ pageStatus: "{page} / {pages} · {total} total",
+ searchAllServices: "Search all services",
+ searchAllNodes: "Search all nodes",
+ searchLocalServices: "Search local Agent services",
+ query: "Query",
+ searchHealthChecks: "Search check name, ID, node, service, output, or notes",
+ allCheckTypes: "All check types",
+ clearFilters: "Clear filters",
+ healthResultCount: "{filtered} of {total} checks",
+ services: "Services",
+ nodes: "Nodes",
+ service: "Service",
+ catalogServices: "Catalog services",
+ catalogNodes: "Catalog nodes",
+ noVisibleServices: "No visible services",
+ noVisibleNodes: "No visible nodes",
+ noMatchingServices: "No matching services",
+ noMatchingNodes: "No matching nodes",
+ agentTarget: "Agent target: {target}",
+ agentTargetVerifying: "Verifying Agent target",
+ unknownWritesDisabled: "unknown - writes disabled",
+ targetAgent: "the target Agent",
+ agentWriteReady: "Writable",
+ agentReadOnly: "Read-only",
+ agentWriteDisabledHint: "No matching Agent target is configured, so maintenance and deregistration are disabled. Detected Agent: {target}.",
+ register: "Register",
+ registrationHint: "HTTP Agent registrations belong to the target Agent runtime and do not modify its persistent configuration files.",
+ name: "Name",
+ id: "ID",
+ port: "Port",
+ tags: "Tags (comma-separated)",
+ registerOn: "Register on {node}",
+ catalogInstances: "Catalog instances",
+ nodeServices: "Node services",
+ serviceId: "Service ID",
+ localAgentServices: "Local Agent services",
+ enableMaintenance: "Enable maintenance",
+ disableMaintenance: "Disable maintenance",
+ deregister: "Deregister",
+ deregisterService: "Deregister local service {id} from {node}?",
+ maintenanceReason: "DBX user request",
+ serviceDetails: "{service} details",
+ kind: "Kind",
+ serviceKind: "ServiceKind",
+ standard: "standard",
+ metadata: "Metadata",
+ nodeMeta: "Node meta",
+ serviceMeta: "Service meta",
+ nodeId: "Node ID",
+ serviceWeights: "Passing / Warning",
+ taggedAddresses: "TaggedAddresses",
+ enableTagOverride: "EnableTagOverride",
+ agent: "Agent",
+ watch: "Watch",
+ writeOperation: "Write operation",
+ localServiceDetails: "Local service details",
+ agentIdentityRequestTimedOut: "Loading Agent identity timed out.",
+ localServicesRequestTimedOut: "Loading local Agent services timed out.",
+ localChecksRequestTimedOut: "Loading local Agent checks timed out.",
+ healthChecks: "Health checks",
+ state: "State",
+ nodeName: "Node name",
+ allStates: "All states",
+ passing: "Passing",
+ warning: "Warning",
+ critical: "Critical",
+ watchPaused: "Watch paused",
+ watchingIndex: "Watching index {index}",
+ pauseWatch: "Pause watch",
+ startWatch: "Start watch",
+ checkRegistrationHint: "Agent checks are runtime registrations on {node} and are not persisted to Agent configuration files.",
+ type: "Type",
+ ttl: "TTL",
+ http: "HTTP",
+ tcp: "TCP",
+ grpc: "gRPC",
+ docker: "Docker",
+ script: "Script",
+ arguments: "Arguments",
+ containerId: "Container ID",
+ endpoint: "Endpoint",
+ interval: "Interval",
+ timeout: "Timeout",
+ commandArguments: "Command arguments",
+ clusterHealth: "Cluster health",
+ nodeHealth: "Node health: {node}",
+ serviceHealth: "Service health: {service}",
+ noMatchingHealthChecks: "No matching health checks",
+ serviceInstances: "Service instances",
+ localAgentChecks: "Local Agent checks",
+ maintenance: "maintenance",
+ ttlPass: "TTL pass",
+ ttlWarn: "TTL warn",
+ ttlFail: "TTL fail",
+ deregisterCheck: "Deregister check {id} from {node}?",
+ checkDetails: "{check} details",
+ checkId: "Check ID",
+ notes: "Notes",
+ output: "Output",
+ definition: "Definition",
+ indexes: "CreateIndex / ModifyIndex",
+ sessionsAndLocks: "Sessions and locks",
+ sessions: "Sessions",
+ sessionDescription: "A Session is a lease-like contract used by Consul KV locks. TTL Sessions require renewal; Sessions without TTL remain until explicitly destroyed or invalidated by their checks.",
+ createSession: "Create Session",
+ searchSessions: "Search Session name, ID, node, or check",
+ sessionResultCount: "Showing {filtered} of {total} Sessions",
+ noMatchingSessions: "No matching Sessions",
+ allSessionTypes: "All Session types",
+ ttlSessions: "TTL Sessions",
+ persistentSessions: "No-TTL Sessions",
+ allBehaviors: "All behaviors",
+ aclFilteredSessions: "The Session list was filtered by ACLs",
+ sessionRequestTimedOut: "Loading Sessions timed out. Check the Consul connection and try again.",
+ complete: "Complete",
+ lock: "Lock",
+ lockManagement: "KV lock management",
+ lockIndex: "LockIndex {index}",
+ lockDelay: "Lock delay",
+ lockDelayHint: "0s–60s; delays reacquisition after invalidation.",
+ nodeOptional: "Node (optional)",
+ behavior: "Behavior",
+ behaviorRelease: "release",
+ behaviorDelete: "delete",
+ behaviorHint: "release keeps held keys; delete removes them when the Session expires.",
+ releaseLocks: "Release locks",
+ deleteKeys: "Delete keys",
+ deleteBehaviorWarning: "Behavior=delete removes every key held by this Session when it is invalidated. Continue?",
+ checks: "Checks",
+ nodeChecks: "Node checks",
+ serviceChecks: "Service checks",
+ nodeCheckShort: "Node",
+ serviceCheckShort: "Service",
+ serviceChecksPlaceholder: "service:api:health@namespace-a",
+ serviceChecksHint: "Comma-separated check IDs; use ID@namespace for a scoped check.",
+ lockHint: "Inspect the key, select a Session, then acquire or release the advisory lock.",
+ key: "Key",
+ inspectKey: "Inspect key",
+ keyExists: "Key exists",
+ keyNotFound: "Key does not exist",
+ keyUnlocked: "Key is not currently held",
+ keyHeldBy: "Held by Session {session}",
+ sessionValue: "Session {id}",
+ modifyIndexValue: "ModifyIndex {index}",
+ createIndex: "CreateIndex",
+ modifyIndexLabel: "ModifyIndex",
+ selectSession: "Select a Session",
+ sessionId: "Session ID",
+ expectedModifyIndex: "Expected ModifyIndex (0 for new key)",
+ value: "Value",
+ releaseMatchingSession: "Release",
+ acquire: "Acquire",
+ unnamedSession: "Unnamed Session",
+ heldKeys: "Held keys",
+ heldKeysIncomplete: "Results are incomplete or ACL-filtered",
+ stop: "Stop",
+ renewNow: "Renew now",
+ autoRenew: "Auto renew",
+ autoRenewPageHint: "Auto renewal runs only while this connection and page remain active.",
+ noRenewRequired: "No renewal needed",
+ noTtl: "No TTL",
+ ttlOptional: "TTL (optional)",
+ ttlRangeHint: "Leave empty for a persistent Session, or use 10s–24h.",
+ invalidSessionTtl: "TTL must be empty or a valid duration from 10s to 24h.",
+ invalidLockDelay: "Lock delay must be a valid duration from 0s to 60s.",
+ destroy: "Destroy",
+ noHeldKeys: "No held keys",
+ noVisibleSessions: "No visible Sessions",
+ destroySession: "Destroy Session {id}? Locks using this Session may be released or deleted by its Behavior.",
+ destroySessionImpact: "Destroy Session {id}? Behavior: {behavior}. Held keys ({count}): {keys}",
+ sessionImpactIncomplete: "Session impact is incomplete or ACL-filtered. Destruction is blocked.",
+ sessionDetails: "TTL {ttl} · {behavior} · checks {checks}",
+ tokens: "Tokens",
+ policies: "Policies",
+ roles: "Roles",
+ authMethods: "Auth Methods",
+ bindingRules: "Binding Rules",
+ templatedPolicies: "Templated Policies",
+ capability: "Capability: {status}",
+ capabilitySupported: "Supported",
+ capabilityUnsupported: "Unsupported",
+ capabilityDisabled: "Disabled",
+ capabilityForbidden: "No permission",
+ capabilityUnknown: "Unknown",
+ loading: "Loading...",
+ viewOrEdit: "View or edit",
+ cloneToken: "Clone token",
+ deleteAndInspectReferences: "Delete and inspect references",
+ noResources: "No resources",
+ editResource: "Edit {kind}",
+ createResource: "Create {kind}",
+ knownImpact: "Known impact: {tokens} tokens, {roles} roles, {bindingRules} binding rules",
+ incomplete: "(incomplete)",
+ reviewAclChanges: "Review ACL changes",
+ deleteResource: "Delete {label}",
+ tokenReferences: "Token references: {tokens} · Role references: {roles} · Binding rule references: {bindingRules}",
+ impactBlocked: "Impact is incomplete or ACL-filtered. Deletion is blocked.",
+ cloneTokenDescription: "Description for cloned token",
+ scope: "Consul scope",
+ adminPartition: "Admin Partition",
+ namespace: "Namespace",
+ default: "default",
+ applyScope: "Apply scope",
+ enterpriseCapability: "Enterprise capability: {status}. Lifecycle actions are unavailable.",
+ namespaces: "Namespaces",
+ lifecycleImpact: "Scoped resource impact",
+ inspectImpactAndDelete: "Inspect impact and delete",
+ impactAclFiltered: "Consul reports ACL-filtered results; deletion is blocked.",
+ impactUnavailable: "Could not enumerate: {resources}",
+ impactResource: {
+ services: "Services",
+ nodes: "Nodes",
+ kvKeys: "KV keys",
+ healthChecks: "Health checks",
+ sessions: "Sessions",
+ configEntries: "Config entries",
+ intentions: "Intentions",
+ peerings: "Peerings",
+ namespaces: "Namespaces",
+ aclTokens: "ACL tokens",
+ aclPolicies: "ACL policies",
+ aclRoles: "ACL roles",
+ aclAuthMethods: "ACL auth methods",
+ aclBindingRules: "ACL binding rules",
+ },
+ configEntries: "Config Entries",
+ intentions: "Intentions",
+ discoveryChain: "Discovery Chain",
+ peering: "Peering",
+ exportedServices: "Exported Services",
+ configEntryKind: "Config entry kind",
+ loadKind: "Load kind",
+ newJson: "New JSON",
+ modifyIndex: "ModifyIndex {index}",
+ rawJson: "Raw JSON",
+ newIntention: "New intention",
+ sourceService: "Source service",
+ destinationService: "Destination service",
+ check: "Check",
+ matchSource: "Match source",
+ matchDestination: "Match destination",
+ allowed: "Allowed",
+ denied: "Denied",
+ matchedIntentions: "Matched {count} intention(s)",
+ details: "Details",
+ serviceName: "Service name",
+ compile: "Compile",
+ defaultProtocol: "default protocol",
+ configuredDatacenter: "configured datacenter",
+ start: "Start",
+ next: "Next: {nodes}",
+ terminalTarget: "Terminal / target",
+ upstreamTargets: "Upstream targets ({count})",
+ peerName: "Peer name",
+ peeringToken: "Peering token to establish",
+ generateToken: "Generate token",
+ establish: "Establish",
+ editExportedServices: "Edit exported-services entry",
+ serviceMeshConfigEntry: "Service Mesh config entry",
+ applyWithCas: "Apply with CAS",
+ reviewMeshChanges: "Review Service Mesh changes",
+ deleteConfig: "Delete {kind}/{name}?",
+ deleteIntention: "Delete intention {id}?",
+ deleteIntentionExact: "Delete intention {source} -> {destination}?",
+ deletePeering: "Delete peering {name}?",
+ permissions: "{count} permissions",
+ actionRule: "action rule",
+ tools: "Consul tools",
+ preparedQueries: "Prepared queries",
+ events: "Events",
+ coordinates: "Network coordinates",
+ queryName: "Query name",
+ targetService: "Target service",
+ targetServiceValue: "Target service: {service}",
+ cancelEdit: "Cancel edit",
+ execute: "Execute",
+ explain: "Explain",
+ eventName: "Event name",
+ payload: "Payload",
+ fire: "Fire",
+ deletePreparedQuery: "Delete prepared query {id}?",
+ nodesDatacenter: "{count} nodes · {datacenter}",
+ coordinateError: "{segment} · error {error}",
+ preparedQueriesDescription: "Reusable service-discovery queries stored in Consul. Execute resolves matching healthy service instances; Explain shows the effective query. The simple editor changes only the name and target service, preserving advanced fields already stored by Consul.",
+ eventsDescription: "Lightweight, best-effort messages distributed through Consul gossip. Events are transient diagnostics or notifications, not a durable message queue.",
+ coordinatesDescription: "Read-only network coordinates estimated by Consul to compare network proximity. They are not geographic locations.",
+ noPreparedQueries: "No prepared queries",
+ noEvents: "No recent events",
+ noCoordinates: "No network coordinates",
+ queryExecutionResult: "Execution result · {count} instances · {datacenter}",
+ noQueryNodes: "No service instances matched this query",
+ queryExplanation: "Effective query",
+ eventNodeFilter: "Node regex (optional)",
+ eventServiceFilter: "Service regex (optional)",
+ eventTagFilter: "Tag regex (optional)",
+ eventPayloadBytes: "Payload {count} / 100 bytes",
+ segment: "Segment",
+ error: "Error",
+ adjustment: "Adjustment",
+ height: "Height",
+ operatorReadOnly: "Operator (read-only)",
+ snapshot: "Snapshot",
+ snapshotRestore: "Snapshot restore",
+ targetDatacenter: "Target Datacenter",
+ restoreSnapshot: "Restore snapshot",
+ restoreSnapshotConfirmation: "RESTORE SNAPSHOT {datacenter}",
+ autopilotUpdate: "Autopilot update",
+ cleanupDeadServers: "Cleanup dead servers",
+ updateAutopilot: "Update Autopilot",
+ updateAutopilotConfirmation: "UPDATE AUTOPILOT",
+ raftOperations: "Raft operations",
+ serverId: "Server ID",
+ peerAddress: "Peer address (remove only)",
+ reenterIdAddress: "Re-enter ID or address",
+ transferLeader: "Transfer leader",
+ removePeer: "Remove peer",
+ gossipKeyring: "Gossip keyring",
+ operation: "Operation",
+ install: "Install",
+ use: "Use",
+ remove: "Remove",
+ gossipKey: "Gossip key",
+ changeKeyring: "Change keyring",
+ changeKeyringConfirmation: "CHANGE KEYRING",
+ licenseUpdate: "License update",
+ license: "License",
+ updateLicense: "Update license",
+ updateLicenseConfirmation: "UPDATE LICENSE",
+ },
+ tools: {
+ search: "Search",
+ searchTitle: "Search Consul KV",
+ searchQuery: "Text to find",
+ prefixOptional: "Prefix (optional)",
+ searchAll: "Keys and values",
+ searchKeys: "Keys only",
+ searchValues: "Values only",
+ caseSensitive: "Case-sensitive",
+ scanned: "Scanned {count} keys",
+ searchLimited: "Results are limited to protect the connection.",
+ noSearchResults: "No matching keys",
+ searchSummary: "{matched} matches from {scanned} scanned keys",
+ exportSearchResults: "Export results",
+ searchResultsFileType: "Consul KV search results",
+ searchResultsExported: "Exported {count} search results",
+ exportPrefix: "Export prefix",
+ prefix: "Prefix",
+ emptyPrefixAll: "Leave empty for all accessible keys",
+ exportLimitHint: "Exports include the current scope and preserve the key metadata needed for safe import.",
+ exported: "Exported {count} keys",
+ import: "Import",
+ importTitle: "Import Consul KV bundle",
+ invalidBundle: "This file is not a valid DBX Consul KV bundle",
+ importApplied: "Imported {count} keys",
+ migrate: "Migrate",
+ migrateTitle: "Migrate Consul KV",
+ sourcePrefix: "Source prefix",
+ targetConnection: "Target connection",
+ selectTarget: "Select a target connection",
+ targetReadOnly: "The target connection is read-only.",
+ conflictPolicy: "Conflict policy",
+ policyAbort: "Abort on conflict",
+ policySkip: "Skip conflicts",
+ policyCas: "Use CAS",
+ bundleSummary: "{count} keys · Datacenter {dc} · Namespace {ns} · Partition {partition}",
+ creates: "Create {count}",
+ updates: "Update {count}",
+ unchanged: "Unchanged {count}",
+ skipped: "Skipped {count}",
+ conflicts: "Conflicts {count}",
+ loadPreview: "Load preview",
+ loadingPreview: "Loading preview...",
+ apply: "Apply",
+ preview: "Preview",
+ deletePrefix: "Delete prefix",
+ deletePrefixTitle: "Delete Consul KV prefix",
+ deletePrefixPlaceholder: "Prefix to delete",
+ deletePrefixWarning: "This operation deletes every visible key under the prefix. Review the preview before confirming.",
+ candidates: "Candidates {count}",
+ lockedCount: "Locked {count}",
+ filtered: "filtered",
+ complete: "complete",
+ confirmDeletePrefix: "Delete confirmed keys",
+ prefixDeleted: "Deleted {count} keys",
+ operation: { create: "Create", update: "Update", unchanged: "Unchanged", skipped: "Skipped", conflict: "Conflict", locked: "Locked", succeeded: "Succeeded", conflicted: "Conflicted", failed: "Failed" },
+ },
+} as const;
diff --git a/apps/desktop/src/i18n/locales/consulZhCN.ts b/apps/desktop/src/i18n/locales/consulZhCN.ts
new file mode 100644
index 0000000000..24ba5c25b0
--- /dev/null
+++ b/apps/desktop/src/i18n/locales/consulZhCN.ts
@@ -0,0 +1,517 @@
+import { consulUiMessages } from "./consulUi";
+
+export const consul = {
+ ...consulUiMessages,
+ ui: {
+ ...consulUiMessages.ui,
+ atomicTransaction: "单事务原子执行",
+ nonAtomicBatches: "跨 {count} 个批次不具备整体原子性",
+ batchOperation: "批次 {batch} · OpIndex {op}",
+ operationTotals: "成功 {succeeded} · 冲突 {conflicted} · 跳过 {skipped} · 失败 {failed}",
+ deleteOperationTotals: "成功 {succeeded} · 冲突 {conflicted} · 失败 {failed}",
+ clientSideMigration: "DBX 会从源连接读取后写入目标连接;这不是 Consul 原生跨 Datacenter 复制。",
+ copy: "复制",
+ copied: "已复制",
+ copyFailed: "复制失败",
+ sessionProtected: "受 Session 保护",
+ sessionProtectedHint: "为避免破坏分布式锁,编辑与删除已禁用。",
+ previousPage: "上一页",
+ nextPage: "下一页",
+ pageStatus: "第 {page} / {pages} 页 · 共 {total} 条",
+ searchAllServices: "全局搜索服务",
+ searchAllNodes: "全局搜索节点",
+ searchLocalServices: "搜索本地 Agent 服务",
+ query: "查询",
+ searchHealthChecks: "搜索检查名称、ID、节点、服务、输出或备注",
+ allCheckTypes: "全部检查类型",
+ clearFilters: "清除过滤",
+ healthResultCount: "显示 {filtered} / {total} 个检查",
+ unknown: "未知",
+ peeringPending: "等待中",
+ peeringEstablishing: "正在建立",
+ peeringActive: "已连接",
+ peeringFailing: "连接异常",
+ peeringDeleting: "正在删除",
+ peeringTerminated: "已终止",
+ refresh: "刷新",
+ cancel: "取消",
+ create: "创建",
+ update: "更新",
+ save: "保存",
+ delete: "删除",
+ edit: "编辑",
+ apply: "应用",
+ close: "关闭",
+ pause: "暂停",
+ watchAction: "监视",
+ watchPrefix: "监视前缀",
+ watchModePrefix: "前缀",
+ watchModeKey: "精确 Key",
+ bundleFileType: "DBX Consul KV 数据包",
+ sourceKeyMissingModifyIndex: "源 Key 没有 ModifyIndex",
+ transactionRejected: "Consul 拒绝了该事务",
+ overview: "集群概览",
+ capabilities: "能力探测",
+ probeLoading: "加载中",
+ probeReady: "可用",
+ probeForbidden: "无权限",
+ probeUnsupported: "不支持",
+ probeError: "错误",
+ autopilotHealth: "Autopilot 健康状态",
+ services: "服务",
+ nodes: "节点",
+ service: "服务",
+ node: "节点",
+ catalogServices: "Catalog 服务",
+ catalogNodes: "Catalog 节点",
+ noVisibleServices: "没有可见服务",
+ noVisibleNodes: "没有可见节点",
+ noMatchingServices: "没有匹配的服务",
+ noMatchingNodes: "没有匹配的节点",
+ agentTarget: "Agent 目标:{target}",
+ agentTargetVerifying: "正在校验 Agent 目标",
+ unknownWritesDisabled: "未知,写操作已禁用",
+ targetAgent: "目标 Agent",
+ agentWriteReady: "可操作",
+ agentReadOnly: "只读",
+ agentWriteDisabledHint: "未配置匹配的 Agent 目标,因此维护和注销操作已禁用。当前检测到:{target}。",
+ register: "注册",
+ registrationHint: "HTTP Agent 注册仅作用于目标 Agent 的运行时,不会修改其持久化配置文件。",
+ name: "名称",
+ port: "端口",
+ tags: "标签(逗号分隔)",
+ registerOn: "注册到 {node}",
+ catalogInstances: "Catalog 实例",
+ nodeServices: "节点服务",
+ serviceId: "服务 ID",
+ localAgentServices: "本地 Agent 服务",
+ enableMaintenance: "启用维护模式",
+ disableMaintenance: "停用维护模式",
+ deregister: "注销",
+ deregisterService: "从 {node} 注销本地服务 {id}?",
+ maintenanceReason: "DBX 用户请求",
+ serviceDetails: "{service} 详情",
+ kind: "类型",
+ serviceKind: "服务类型(ServiceKind)",
+ standard: "标准",
+ metadata: "元数据",
+ nodeMeta: "节点元数据",
+ serviceMeta: "服务元数据",
+ nodeId: "节点 ID",
+ serviceWeights: "通过 / 警告权重",
+ taggedAddresses: "标记地址(TaggedAddresses)",
+ enableTagOverride: "允许覆盖标签(EnableTagOverride)",
+ agent: "Agent",
+ writeOperation: "写操作",
+ localServiceDetails: "本地服务详情",
+ agentIdentityRequestTimedOut: "加载 Agent 身份信息超时。",
+ localServicesRequestTimedOut: "加载本地 Agent 服务超时。",
+ localChecksRequestTimedOut: "加载本地 Agent 检查超时。",
+ healthChecks: "健康检查",
+ state: "状态",
+ nodeName: "节点名称",
+ allStates: "全部状态",
+ passing: "通过",
+ warning: "警告",
+ critical: "严重",
+ watchingIndex: "正在监视索引 {index}",
+ checkRegistrationHint: "Agent 检查仅注册在 {node} 的运行时中,不会持久化到 Agent 配置文件。",
+ type: "类型",
+ arguments: "参数",
+ containerId: "Container ID",
+ endpoint: "端点",
+ interval: "间隔",
+ timeout: "超时",
+ commandArguments: "命令参数",
+ clusterHealth: "集群健康状态",
+ nodeHealth: "节点健康状态:{node}",
+ serviceHealth: "服务健康状态:{service}",
+ noMatchingHealthChecks: "没有匹配的健康检查",
+ serviceInstances: "服务实例",
+ localAgentChecks: "本地 Agent 检查",
+ maintenance: "维护中",
+ ttlPass: "TTL 通过",
+ ttlWarn: "TTL 警告",
+ ttlFail: "TTL 失败",
+ deregisterCheck: "从 {node} 注销检查 {id}?",
+ checkDetails: "{check} 详情",
+ checkId: "检查 ID",
+ notes: "备注",
+ output: "输出",
+ definition: "定义",
+ indexes: "CreateIndex / ModifyIndex",
+ sessionsAndLocks: "会话和锁",
+ scope: "Consul 作用域",
+ tools: "Consul 工具",
+ loading: "加载中...",
+ noResources: "没有资源",
+ capability: "能力:{status}",
+ capabilitySupported: "支持",
+ capabilityUnsupported: "不支持",
+ capabilityDisabled: "未启用",
+ capabilityForbidden: "无权限",
+ capabilityUnknown: "未知",
+ applyScope: "应用作用域",
+ impactAclFiltered: "Consul 返回了 ACL 过滤结果,删除已阻止。",
+ impactUnavailable: "无法完整枚举:{resources}",
+ impactResource: {
+ services: "服务",
+ nodes: "节点",
+ kvKeys: "KV Key",
+ healthChecks: "健康检查",
+ sessions: "Session",
+ configEntries: "配置条目",
+ intentions: "Intention",
+ peerings: "Peering",
+ namespaces: "Namespace",
+ aclTokens: "ACL Token",
+ aclPolicies: "ACL Policy",
+ aclRoles: "ACL Role",
+ aclAuthMethods: "ACL Auth Method",
+ aclBindingRules: "ACL Binding Rule",
+ },
+ reveal: "显示",
+ copyOnce: "复制一次",
+ datacenter: "数据中心",
+ agentNode: "Agent 节点",
+ agentAddress: "Agent 地址",
+ version: "版本",
+ mode: "模式",
+ server: "服务端",
+ client: "客户端",
+ leader: "Leader",
+ raftPeers: "Raft 对等节点",
+ membersAlive: "存活成员",
+ members: "成员",
+ address: "地址",
+ status: "状态",
+ alive: "存活",
+ leaving: "离开中",
+ failed: "故障",
+ tokens: "令牌",
+ policies: "策略",
+ roles: "角色",
+ authMethods: "认证方式",
+ bindingRules: "绑定规则",
+ templatedPolicies: "模板策略",
+ viewOrEdit: "查看或编辑",
+ cloneToken: "克隆令牌",
+ deleteAndInspectReferences: "检查引用后删除",
+ editResource: "编辑 {kind}",
+ createResource: "新建 {kind}",
+ knownImpact: "已知影响:{tokens} 个令牌、{roles} 个角色、{bindingRules} 条绑定规则",
+ incomplete: "(不完整)",
+ reviewAclChanges: "确认 ACL 变更",
+ deleteResource: "删除 {label}",
+ tokenReferences: "令牌引用:{tokens} · 角色引用:{roles} · 绑定规则引用:{bindingRules}",
+ impactBlocked: "影响范围不完整或已被 ACL 过滤,禁止删除。",
+ cloneTokenDescription: "克隆令牌的说明",
+ sessions: "会话",
+ sessionDescription: "会话是 Consul 分布式锁使用的租约型契约。带 TTL 的会话需要续租;无 TTL 会话会持续存在,直到主动销毁或关联检查失效。",
+ createSession: "创建会话",
+ searchSessions: "搜索会话名称、ID、节点或检查项",
+ sessionResultCount: "显示 {filtered} / {total} 个会话",
+ noMatchingSessions: "没有匹配的会话",
+ allSessionTypes: "全部会话类型",
+ ttlSessions: "TTL 会话",
+ persistentSessions: "无 TTL 会话",
+ allBehaviors: "全部失效行为",
+ aclFilteredSessions: "会话列表已被 ACL 过滤",
+ sessionRequestTimedOut: "加载会话超时,请检查 Consul 连接后重试。",
+ complete: "完整",
+ lock: "锁",
+ lockManagement: "KV 锁管理",
+ lockIndex: "锁索引 {index}",
+ lockDelay: "锁延迟",
+ lockDelayHint: "范围 0s–60s;会话失效后延迟其他会话重新获取锁。",
+ nodeOptional: "节点(可选)",
+ behavior: "失效行为",
+ behaviorRelease: "释放锁(release)",
+ behaviorDelete: "删除 Key(delete)",
+ behaviorHint: "release 会保留 Key 并释放锁;delete 会在会话失效时删除所持 Key。",
+ releaseLocks: "释放锁(release)",
+ deleteKeys: "删除 Key(delete)",
+ deleteBehaviorWarning: "delete 行为会在会话失效时删除它持有的所有 Key。确定继续吗?",
+ checks: "关联检查",
+ nodeChecks: "节点检查",
+ serviceChecks: "服务检查",
+ nodeCheckShort: "节点",
+ serviceCheckShort: "服务",
+ serviceChecksPlaceholder: "service:api:health@namespace-a",
+ serviceChecksHint: "多个检查 ID 用逗号分隔;作用域检查可写为 ID@命名空间。",
+ lockHint: "先检查 Key,再选择会话执行获取或释放。",
+ key: "Key",
+ inspectKey: "检查 Key",
+ keyExists: "Key 已存在",
+ keyNotFound: "Key 不存在",
+ keyUnlocked: "Key 当前未被会话持有",
+ keyHeldBy: "由会话 {session} 持有",
+ sessionValue: "会话 {id}",
+ modifyIndexValue: "ModifyIndex {index}",
+ createIndex: "CreateIndex",
+ modifyIndexLabel: "ModifyIndex",
+ selectSession: "选择会话",
+ sessionId: "会话 ID",
+ expectedModifyIndex: "期望的 ModifyIndex(新 Key 为 0)",
+ value: "值",
+ releaseMatchingSession: "释放",
+ acquire: "获取",
+ unnamedSession: "未命名会话",
+ heldKeys: "持有的 Key",
+ heldKeysIncomplete: "结果不完整或已被 ACL 过滤",
+ stop: "停止",
+ renewNow: "立即续租",
+ autoRenew: "自动续租",
+ autoRenewPageHint: "仅在当前连接和页面保持活跃时自动续租。",
+ noRenewRequired: "无需续租",
+ noTtl: "无 TTL",
+ ttlOptional: "TTL(可选)",
+ ttlRangeHint: "留空表示持久会话;填写时范围为 10s–24h。",
+ invalidSessionTtl: "TTL 必须留空,或填写 10s–24h 的有效时长。",
+ invalidLockDelay: "锁延迟必须填写 0s–60s 的有效时长。",
+ destroy: "销毁",
+ noHeldKeys: "没有持有的 Key",
+ noVisibleSessions: "没有可见会话",
+ destroySession: "销毁会话 {id}?该会话所持锁会按其行为释放或删除。",
+ destroySessionImpact: "销毁会话 {id}?行为:{behavior}。持有的 Key({count}):{keys}",
+ sessionImpactIncomplete: "会话影响范围不完整或已被 ACL 过滤,已阻止销毁。",
+ sessionDetails: "TTL {ttl} · {behavior} · 检查项 {checks}",
+ adminPartition: "管理分区",
+ namespace: "命名空间",
+ default: "默认",
+ enterpriseCapability: "Enterprise 能力:{status}。生命周期操作不可用。",
+ namespaces: "命名空间",
+ lifecycleImpact: "作用域资源影响",
+ inspectImpactAndDelete: "检查影响并删除",
+ configEntries: "配置条目",
+ intentions: "服务意图",
+ discoveryChain: "服务发现链",
+ peering: "对等连接",
+ exportedServices: "导出服务",
+ configEntryKind: "配置条目类型",
+ loadKind: "加载类型",
+ newJson: "新建 JSON",
+ modifyIndex: "ModifyIndex {index}",
+ rawJson: "原始 JSON",
+ newIntention: "新建服务意图",
+ sourceService: "源服务",
+ destinationService: "目标服务",
+ check: "检查",
+ matchSource: "匹配源服务",
+ matchDestination: "匹配目标服务",
+ allowed: "允许",
+ denied: "拒绝",
+ matchedIntentions: "匹配到 {count} 条服务意图",
+ details: "详情",
+ serviceName: "服务名称",
+ compile: "编译",
+ defaultProtocol: "默认协议",
+ configuredDatacenter: "配置的数据中心",
+ start: "起点",
+ next: "下一跳:{nodes}",
+ terminalTarget: "终点 / 目标",
+ upstreamTargets: "上游目标({count})",
+ peerName: "对等连接名称",
+ peeringToken: "用于建立连接的对等令牌",
+ generateToken: "生成令牌",
+ establish: "建立",
+ editExportedServices: "编辑 exported-services 条目",
+ serviceMeshConfigEntry: "服务网格配置条目",
+ applyWithCas: "使用 CAS 应用",
+ reviewMeshChanges: "确认服务网格变更",
+ deleteConfig: "删除 {kind}/{name}?",
+ deleteIntention: "删除服务意图 {id}?",
+ deleteIntentionExact: "删除服务意图 {source} -> {destination}?",
+ deletePeering: "删除对等连接 {name}?",
+ permissions: "{count} 条权限",
+ actionRule: "动作规则",
+ preparedQueries: "预设查询",
+ events: "事件",
+ coordinates: "网络坐标",
+ queryName: "查询名称",
+ targetService: "目标服务",
+ targetServiceValue: "目标服务:{service}",
+ cancelEdit: "取消编辑",
+ execute: "执行",
+ explain: "说明",
+ eventName: "事件名称",
+ payload: "负载内容",
+ fire: "触发",
+ deletePreparedQuery: "删除预设查询 {id}?",
+ nodesDatacenter: "{count} 个节点 · {datacenter}",
+ coordinateError: "{segment} · 错误 {error}",
+ preparedQueriesDescription: "保存在 Consul 中、可重复使用的服务发现查询。执行会解析符合条件的健康服务实例,说明会展示最终生效的查询。简易编辑器只修改名称和目标服务,并保留 Consul 中已有的高级字段。",
+ eventsDescription: "通过 Consul Gossip 分发的轻量、尽力而为消息,适合临时诊断和通知;它不是持久化消息队列。",
+ coordinatesDescription: "Consul 估算的只读网络坐标,用于比较节点间的网络距离;它不是地理位置坐标。",
+ noPreparedQueries: "暂无预设查询",
+ noEvents: "暂无近期事件",
+ noCoordinates: "暂无网络坐标",
+ queryExecutionResult: "执行结果 · {count} 个实例 · {datacenter}",
+ noQueryNodes: "没有服务实例符合该查询",
+ queryExplanation: "生效的查询",
+ eventNodeFilter: "节点正则(可选)",
+ eventServiceFilter: "服务正则(可选)",
+ eventTagFilter: "标签正则(可选)",
+ eventPayloadBytes: "负载 {count} / 100 字节",
+ segment: "网络分段",
+ error: "误差",
+ adjustment: "校正值",
+ height: "高度",
+ operatorReadOnly: "运维(只读)",
+ snapshot: "快照",
+ snapshotRestore: "恢复快照",
+ targetDatacenter: "目标数据中心",
+ restoreSnapshot: "恢复快照",
+ autopilotUpdate: "Autopilot 更新",
+ cleanupDeadServers: "清理失效服务端",
+ updateAutopilot: "更新 Autopilot",
+ raftOperations: "Raft 操作",
+ serverId: "服务端 ID",
+ peerAddress: "对等节点地址(仅移除时需要)",
+ reenterIdAddress: "重新输入 ID 或地址",
+ transferLeader: "转移 Leader",
+ removePeer: "移除对等节点",
+ gossipKeyring: "Gossip 密钥环",
+ operation: "操作",
+ install: "安装",
+ use: "使用",
+ remove: "移除",
+ gossipKey: "Gossip 密钥",
+ changeKeyring: "修改密钥环",
+ licenseUpdate: "许可证更新",
+ license: "许可证",
+ updateLicense: "更新许可证",
+ watch: "监视",
+ watchPaused: "监视已暂停",
+ pauseWatch: "暂停监视",
+ startWatch: "启动监视",
+ },
+ tools: {
+ search: "全文搜索",
+ searchTitle: "搜索 Consul KV",
+ searchQuery: "输入要查找的内容",
+ prefixOptional: "前缀(可选)",
+ searchAll: "Key 和值",
+ searchKeys: "仅 Key",
+ searchValues: "仅值",
+ caseSensitive: "区分大小写",
+ scanned: "已扫描 {count} 个 Key",
+ searchLimited: "为保护连接,本次结果已受限。",
+ noSearchResults: "没有匹配的 Key",
+ searchSummary: "已扫描 {scanned} 个 Key,匹配 {matched} 个",
+ exportSearchResults: "导出结果",
+ searchResultsFileType: "Consul KV 搜索结果",
+ searchResultsExported: "已导出 {count} 条搜索结果",
+ exportPrefix: "导出",
+ prefix: "前缀",
+ emptyPrefixAll: "留空则导出全部可访问 Key",
+ exportLimitHint: "导出会保留当前作用域及安全导入所需的 Key 元数据。",
+ exported: "已导出 {count} 个 Key",
+ import: "导入",
+ importTitle: "导入 Consul KV 数据包",
+ invalidBundle: "该文件不是有效的 DBX Consul KV 数据包",
+ importApplied: "已导入 {count} 个 Key",
+ migrate: "同步",
+ migrateTitle: "迁移 Consul KV",
+ sourcePrefix: "源前缀",
+ targetConnection: "目标连接",
+ selectTarget: "选择目标连接",
+ targetReadOnly: "目标连接为只读,无法写入。",
+ conflictPolicy: "冲突策略",
+ policyAbort: "遇到冲突即终止",
+ policySkip: "跳过冲突项",
+ policyCas: "使用 CAS",
+ bundleSummary: "{count} 个 Key · 数据中心 {dc} · 命名空间 {ns} · 管理分区 {partition}",
+ creates: "新建 {count}",
+ updates: "更新 {count}",
+ unchanged: "未变更 {count}",
+ skipped: "跳过 {count}",
+ conflicts: "冲突 {count}",
+ loadPreview: "加载预览",
+ loadingPreview: "正在加载预览...",
+ apply: "应用",
+ preview: "预览",
+ deletePrefix: "前缀删除",
+ deletePrefixTitle: "删除 Consul KV 前缀",
+ deletePrefixPlaceholder: "输入要删除的前缀",
+ deletePrefixWarning: "此操作会删除该前缀下所有可见 Key。请先核对预览,再执行确认。",
+ candidates: "候选项 {count}",
+ lockedCount: "已锁定 {count}",
+ filtered: "已过滤",
+ complete: "完整",
+ confirmDeletePrefix: "删除已确认的 Key",
+ prefixDeleted: "已删除 {count} 个 Key",
+ operation: { create: "新建", update: "更新", unchanged: "未变更", skipped: "已跳过", conflict: "冲突", locked: "已锁定", succeeded: "成功", conflicted: "冲突", failed: "失败" },
+ },
+ prefixPlaceholder: "Key 前缀,例如 app/ 或 services/",
+ newKey: "新建 Key",
+ loadingKeys: "正在加载 Key...",
+ empty: "未找到 Key",
+ loadMore: "加载更多",
+ selectKey: "选择一个 Key 查看其值",
+ loadingValue: "正在加载值...",
+ notFound: "未找到 Key",
+ edit: "编辑",
+ editKey: "编辑 Key",
+ delete: "删除",
+ deleteTitle: "删除 Consul KV Key",
+ keyLabel: "键(Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key 不能为空",
+ rootReadonly: "根前缀不能修改,请输入具体 Key 路径。",
+ saved: "Key 已保存",
+ deleted: "Key 已删除",
+ base64Readonly: "请在 Base64 模式下编辑二进制值。",
+ rename: "重命名",
+ clone: "克隆",
+ copyKey: "复制 Key",
+ export: "导出",
+ value: "值",
+ valueContent: "值",
+ format: "格式",
+ metadata: "KV 元数据",
+ prettyJson: "格式化",
+ invalidJson: "JSON 格式无效",
+ summarySize: "大小",
+ conflict: "该 Key 自加载后已发生变化,请刷新后重试。",
+ keyAlreadyExists: "同名 Key 已存在,请使用其他名称或编辑现有 Key。",
+ aclFiltered: "部分 Consul KV Key 已被 ACL 策略过滤。",
+ locked: "该 Key 正由 Consul Session 持有,不能编辑或删除。",
+ valueTooLarge: "Consul KV 值不能超过 512 KiB。",
+ watchKey: "监视",
+ stopWatching: "停止",
+ workspace: {
+ overview: "概览",
+ kv: "键值存储",
+ services: "服务",
+ health: "健康检查",
+ sessions: "会话",
+ scope: "作用域",
+ mesh: "服务网格",
+ tools: "工具",
+ operator: "运维",
+ refresh: "刷新能力信息",
+ loading: "正在加载 Consul 能力...",
+ agentIdentity: "Agent 身份",
+ capabilities: "能力状态",
+ version: "版本",
+ edition: "版本类型",
+ datacenter: "数据中心",
+ node: "Agent 节点",
+ mode: "Agent 模式",
+ agent: "Agent API",
+ acl: "访问控制",
+ namespaces: "命名空间",
+ partitions: "管理分区",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "支持",
+ unsupported: "不支持",
+ forbidden: "无权限",
+ unknown: "未知",
+ },
+ },
+};
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index a3fb998e1d..52d012618a 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1,4 +1,80 @@
import docs from "./docs/en";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "Key",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "Rename",
+ clone: "Clone",
+ copyKey: "Copy Key",
+ export: "Export",
+ value: "Value",
+ valueContent: "Value",
+ format: "Format",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "Watch",
+ stopWatching: "Stop",
+ workspace: {
+ overview: "Overview",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "Refresh capabilities",
+ loading: "Loading Consul capabilities...",
+ agentIdentity: "Agent identity",
+ capabilities: "Capabilities",
+ version: "Version",
+ edition: "Edition",
+ datacenter: "Datacenter",
+ node: "Agent node",
+ mode: "Agent mode",
+ agent: "Agent API",
+ acl: "ACL",
+ namespaces: "Namespaces",
+ partitions: "Admin Partitions",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "Supported",
+ unsupported: "Unsupported",
+ forbidden: "No permission",
+ unknown: "Unknown",
+ },
+ },
+};
export default {
app: {
@@ -458,6 +534,34 @@ export default {
etcdClientCertBrowse: "Choose client certificate",
etcdClientKeyBrowse: "Choose client private key",
etcdClientCertPairRequired: "Client certificate and private key must be provided together.",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "Connect String",
zookeeperConnectStringHint: "Comma or line separated host:port entries, with an optional shared /chroot. Leave blank to use the host and port above.",
zookeeperClusterInputHint: "For a ZooKeeper ensemble, enter all nodes either in the URL (for example zookeeper://zk-1:2181,zk-2:2181/app) or in Connect String below.",
@@ -1140,6 +1244,7 @@ export default {
etcdDashboard: "etcd Dashboard",
etcdAccessControl: "etcd Access Control",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
gridfs: "GridFS",
vector: "Vector",
@@ -3739,6 +3844,7 @@ export default {
},
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "Path prefix, e.g. /app/",
newKey: "New Znode",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index c35f92048a..fed789b5d8 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/es";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "Clave (Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "Renombrar",
+ clone: "Clonar",
+ copyKey: "Copiar clave",
+ export: "Exportar",
+ value: "Value",
+ valueContent: "Valor",
+ format: "Formato",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "Vigilar",
+ stopWatching: "Detener",
+ workspace: {
+ overview: "Resumen",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "Actualizar capacidades",
+ loading: "Cargando capacidades de Consul...",
+ agentIdentity: "Identidad del agente",
+ capabilities: "Capacidades",
+ version: "Versión",
+ edition: "Edición",
+ datacenter: "Centro de datos",
+ node: "Nodo del agente",
+ mode: "Modo del agente",
+ agent: "API del agente",
+ acl: "ACL",
+ namespaces: "Espacios de nombres",
+ partitions: "Particiones administrativas",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Servidor",
+ clientMode: "Cliente",
+ capability: {
+ supported: "Compatible",
+ unsupported: "No compatible",
+ forbidden: "Sin permiso",
+ unknown: "Desconocido",
+ },
+ },
+};
export default withEnglishFallback({
app: {
@@ -438,6 +514,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "Elegir certificado de cliente",
etcdClientKeyBrowse: "Elegir clave privada de cliente",
etcdClientCertPairRequired: "El certificado y la clave privada deben proporcionarse juntos.",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "Cadena de conexión",
zookeeperConnectStringHint: "Entradas host:puerto separadas por coma o por línea. Déjalo en blanco para usar el host y puerto de arriba.",
zookeeperCreateModePersistent: "Persistente",
@@ -1119,6 +1223,7 @@ export default withEnglishFallback({
redis: "Redis",
etcd: "etcd",
zookeeper: "ZooKeeper",
+ consul: "Consul",
vector: "Vector",
users: "Usuarios y Privilegios",
executionSummary: "Resumen",
@@ -3586,6 +3691,7 @@ export default withEnglishFallback({
leaseCreated: "Lease {id} creado",
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "Prefijo de ruta, ej. /app/",
newKey: "Nuevo Znode",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 7b3e3e9fcc..997105f9ac 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/it";
+import { consulUiMessages } from "./consulUi";
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "Chiave (Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "Rinomina",
+ clone: "Clona",
+ copyKey: "Copia chiave",
+ export: "Esporta",
+ value: "Value",
+ valueContent: "Valore",
+ format: "Formato",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "Monitora",
+ stopWatching: "Interrompi",
+ workspace: {
+ overview: "Panoramica",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "Aggiorna capacità",
+ loading: "Caricamento delle capacità Consul...",
+ agentIdentity: "Identità agent",
+ capabilities: "Capacità",
+ version: "Versione",
+ edition: "Edizione",
+ datacenter: "Datacenter",
+ node: "Nodo agent",
+ mode: "Modalità agent",
+ agent: "API agent",
+ acl: "ACL",
+ namespaces: "Namespace",
+ partitions: "Partizioni amministrative",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "Supportato",
+ unsupported: "Non supportato",
+ forbidden: "Nessun permesso",
+ unknown: "Sconosciuto",
+ },
+ },
+};
+
export default withEnglishFallback({
app: {
name: "DBX",
@@ -437,6 +513,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "Scegli certificato client",
etcdClientKeyBrowse: "Scegli chiave privata client",
etcdClientCertPairRequired: "Il certificato client e la chiave privata devono essere forniti insieme.",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "Stringa di connessione",
zookeeperConnectStringHint: "Voci host:porta separate da virgola o da riga. Lascia vuoto per usare l'host e la porta sopra.",
zookeeperCreateModePersistent: "Persistente",
@@ -1117,6 +1221,7 @@ export default withEnglishFallback({
redis: "Redis",
etcd: "etcd",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
vector: "Vector",
objects: "Oggetti",
@@ -3584,6 +3689,7 @@ export default withEnglishFallback({
leaseCreated: "Lease {id} creato",
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "Prefisso percorso, es. /app/",
newKey: "Nuovo Znode",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 232af9499d..6e8d96f627 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/ja";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "キー(Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "名前を変更",
+ clone: "複製",
+ copyKey: "Keyをコピー",
+ export: "エクスポート",
+ value: "Value",
+ valueContent: "値",
+ format: "形式",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "監視",
+ stopWatching: "停止",
+ workspace: {
+ overview: "概要",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "機能情報を更新",
+ loading: "Consul機能を読み込み中...",
+ agentIdentity: "Agent情報",
+ capabilities: "機能",
+ version: "バージョン",
+ edition: "エディション",
+ datacenter: "データセンター",
+ node: "Agentノード",
+ mode: "Agentモード",
+ agent: "Agent API",
+ acl: "ACL",
+ namespaces: "名前空間",
+ partitions: "管理パーティション",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "対応",
+ unsupported: "非対応",
+ forbidden: "権限なし",
+ unknown: "不明",
+ },
+ },
+};
export default withEnglishFallback({
app: {
@@ -705,6 +781,34 @@ export default withEnglishFallback({
colorBlue: "青",
colorPurple: "紫",
colorCustom: "カスタム色",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "接続文字列",
zookeeperConnectStringHint: "カンマまたは改行区切りの host:port エントリ。空欄の場合は上のホストとポートを使用します。",
zookeeperCreateModePersistent: "永続",
@@ -1181,6 +1285,7 @@ export default withEnglishFallback({
fixedTabs: "固定タブ",
openDataTabs: "開いているテーブル",
zookeeper: "ZooKeeper",
+ consul: "Consul",
vector: "ベクター",
gridfs: "GridFS",
etcdDashboard: "etcd ダッシュボード",
@@ -2670,6 +2775,7 @@ export default withEnglishFallback({
gridfs: "GridFS",
buckets: "バケット",
},
+ consul,
zookeeper: {
prefixPlaceholder: "パスプレフィックス(例: /app/)",
newKey: "新しいZnode",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 7f876851b2..ca9cf6172a 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/ko";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "키(Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "이름 변경",
+ clone: "복제",
+ copyKey: "Key 복사",
+ export: "내보내기",
+ value: "Value",
+ valueContent: "값",
+ format: "형식",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "감시",
+ stopWatching: "중지",
+ workspace: {
+ overview: "개요",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "기능 정보 새로 고침",
+ loading: "Consul 기능을 불러오는 중...",
+ agentIdentity: "Agent 정보",
+ capabilities: "기능",
+ version: "버전",
+ edition: "에디션",
+ datacenter: "데이터센터",
+ node: "Agent 노드",
+ mode: "Agent 모드",
+ agent: "Agent API",
+ acl: "ACL",
+ namespaces: "네임스페이스",
+ partitions: "관리 파티션",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "지원",
+ unsupported: "지원 안 함",
+ forbidden: "권한 없음",
+ unknown: "알 수 없음",
+ },
+ },
+};
export default withEnglishFallback({
app: {
@@ -452,6 +528,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "클라이언트 인증서 선택",
etcdClientKeyBrowse: "클라이언트 개인 키 선택",
etcdClientCertPairRequired: "클라이언트 인증서와 개인 키를 함께 제공해야 합니다.",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "연결 문자열",
zookeeperConnectStringHint: "쉼표 또는 줄바꿈으로 구분된 host:port 항목. 비워두면 위의 호스트와 포트를 사용합니다.",
zookeeperCreateModePersistent: "영구",
@@ -1029,6 +1133,7 @@ export default withEnglishFallback({
etcd: "etcd",
etcdDashboard: "etcd 대시보드",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
gridfs: "GridFS",
vector: "Vector",
@@ -3262,6 +3367,7 @@ export default withEnglishFallback({
},
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "경로 접두사, 예: /app/",
newKey: "새 Znode",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index e713e700f6..6ac5bcd1a3 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/pt-BR";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key prefix, e.g. app/ or services/",
+ newKey: "New Key",
+ loadingKeys: "Loading keys...",
+ empty: "No keys found",
+ loadMore: "Load more",
+ selectKey: "Select a key to view its value",
+ loadingValue: "Loading value...",
+ notFound: "Key not found",
+ edit: "Edit",
+ editKey: "Edit Key",
+ delete: "Delete",
+ deleteTitle: "Delete Consul KV key",
+ keyLabel: "Chave (Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key is required",
+ rootReadonly: "The root prefix cannot be modified. Enter a key path.",
+ saved: "Key saved",
+ deleted: "Key deleted",
+ base64Readonly: "Edit binary values in Base64 mode.",
+ rename: "Renomear",
+ clone: "Clonar",
+ copyKey: "Copiar chave",
+ export: "Exportar",
+ value: "Value",
+ valueContent: "Valor",
+ format: "Formato",
+ metadata: "KV metadata",
+ prettyJson: "Pretty",
+ invalidJson: "Invalid JSON",
+ summarySize: "Size",
+ conflict: "This Key changed after it was loaded. Refresh it and try again.",
+ keyAlreadyExists: "A Key with this name already exists. Choose another name or edit the existing Key.",
+ aclFiltered: "Some Consul KV keys are hidden by ACL policies.",
+ locked: "This Key is held by a Consul Session and cannot be edited or deleted.",
+ valueTooLarge: "Consul KV values cannot exceed 512 KiB.",
+ watchKey: "Monitorar",
+ stopWatching: "Parar",
+ workspace: {
+ overview: "Visão geral",
+ kv: "KV",
+ services: "Services",
+ health: "Health",
+ sessions: "Sessions",
+ scope: "Scope",
+ mesh: "Service Mesh",
+ tools: "Tools",
+ operator: "Operator",
+ refresh: "Atualizar recursos",
+ loading: "Carregando recursos do Consul...",
+ agentIdentity: "Identidade do agente",
+ capabilities: "Recursos",
+ version: "Versão",
+ edition: "Edição",
+ datacenter: "Datacenter",
+ node: "Nó do agente",
+ mode: "Modo do agente",
+ agent: "API do agente",
+ acl: "ACL",
+ namespaces: "Namespaces",
+ partitions: "Partições administrativas",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Servidor",
+ clientMode: "Cliente",
+ capability: {
+ supported: "Compatível",
+ unsupported: "Não compatível",
+ forbidden: "Sem permissão",
+ unknown: "Desconhecido",
+ },
+ },
+};
export default withEnglishFallback({
app: {
@@ -438,6 +514,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "Escolher certificado do cliente",
etcdClientKeyBrowse: "Escolher chave privada do cliente",
etcdClientCertPairRequired: "O certificado e a chave privada do cliente devem ser fornecidos juntos.",
+ consulAddress: "Consul API address",
+ consulAddressInvalid: "Enter an absolute HTTP or HTTPS Consul API address without credentials, query parameters, or a fragment.",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "Optional Consul ACL Token",
+ consulDatacenter: "Datacenter",
+ consulNamespace: "Namespace",
+ consulPartition: "Admin Partition",
+ consulAgentTargetNode: "Agent target node",
+ consulAgentTargetAddress: "Agent direct address",
+ consulAgentTargetHint: "Required for Agent writes. DNS/load-balanced and Transport Layer endpoints stay read-only.",
+ consulMeshFeatures: "Service mesh",
+ consulMeshVisible: "Show advanced service mesh workspace",
+ consulMeshVisibleHint: "Enable only to manage Connect, intentions, or peering. When disabled, the workspace stays hidden.",
+ consulOperatorWrites: "Operator writes",
+ consulOperatorVisible: "Show experimental Operator workspace",
+ consulOperatorSnapshotRestore: "Enable snapshot restore",
+ consulOperatorAutopilot: "Enable Autopilot updates",
+ consulOperatorRaft: "Enable Raft changes",
+ consulOperatorKeyring: "Enable Keyring changes",
+ consulOperatorLicense: "Enable License updates",
+ consulAgentTargetIncomplete: "Agent target node and direct address must be configured together.",
+ consulAgentTargetAddressMismatch: "Agent direct address must match the Consul endpoint host.",
+ consulConsistency: "Read consistency",
+ consulConsistencyDefault: "Default",
+ consulConsistencyStale: "Stale",
+ consulConsistencyConsistent: "Consistent",
+ consulTlsSkipVerify: "Skip certificate verification",
+ consulTlsSkipVerifyHint: "Use only for trusted self-signed Consul endpoints.",
zookeeperConnectString: "String de Conexão",
zookeeperConnectStringHint: "Entradas host:porta separadas por vírgula ou linha. Deixe em branco para usar o host e porta acima.",
zookeeperCreateModePersistent: "Persistente",
@@ -1118,6 +1222,7 @@ export default withEnglishFallback({
redis: "Redis",
etcd: "etcd",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
vector: "Vector",
objects: "Objetos",
@@ -3586,6 +3691,7 @@ export default withEnglishFallback({
leaseCreated: "Lease {id} criado",
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "Prefixo de caminho, ex.: /app/",
newKey: "Novo Znode",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 6ca13ab60f..dca1e1a072 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1,5 +1,6 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/zh-CN";
+import { consul } from "./consulZhCN";
export default withEnglishFallback({
app: {
@@ -459,6 +460,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "选择客户端证书",
etcdClientKeyBrowse: "选择客户端私钥",
etcdClientCertPairRequired: "客户端证书和私钥必须一起填写。",
+ consulAddress: "Consul API 地址",
+ consulAddressInvalid: "请输入不包含凭据、查询参数或片段的 HTTP/HTTPS Consul API 绝对地址。",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "可选的 Consul ACL Token",
+ consulDatacenter: "数据中心",
+ consulNamespace: "命名空间",
+ consulPartition: "管理分区",
+ consulAgentTargetNode: "目标 Agent 节点",
+ consulAgentTargetAddress: "Agent 直连地址",
+ consulAgentTargetHint: "Agent 写操作必填。DNS/负载均衡和 Transport Layer 连接保持只读。",
+ consulMeshFeatures: "服务网格",
+ consulMeshVisible: "显示服务网格高级功能",
+ consulMeshVisibleHint: "仅在需要管理 Connect、服务意图或对等连接时开启;关闭后主导航不会显示服务网格。",
+ consulOperatorWrites: "Operator 写入",
+ consulOperatorVisible: "显示实验性 Operator 工作台",
+ consulOperatorSnapshotRestore: "启用 Snapshot 恢复",
+ consulOperatorAutopilot: "启用 Autopilot 修改",
+ consulOperatorRaft: "启用 Raft 修改",
+ consulOperatorKeyring: "启用 Keyring 修改",
+ consulOperatorLicense: "启用 License 修改",
+ consulAgentTargetIncomplete: "目标 Agent 节点和直连地址必须同时配置。",
+ consulAgentTargetAddressMismatch: "Agent 直连地址必须与 Consul 地址的主机一致。",
+ consulConsistency: "读取一致性",
+ consulConsistencyDefault: "默认",
+ consulConsistencyStale: "允许陈旧读取",
+ consulConsistencyConsistent: "强一致读取",
+ consulTlsSkipVerify: "跳过证书校验",
+ consulTlsSkipVerifyHint: "仅用于可信的自签名 Consul 服务端。",
zookeeperConnectString: "Connect String",
zookeeperConnectStringHint: "可用逗号或换行分隔 host:port,并可在末尾填写整个集群共用的 /chroot;留空时使用上面的 host 和端口。",
zookeeperClusterInputHint: "ZooKeeper 集群可在上方 URL 中填写全部节点(例如 zookeeper://zk-1:2181,zk-2:2181/app),也可在下方 Connect String 中填写。",
@@ -1140,6 +1169,7 @@ export default withEnglishFallback({
etcdDashboard: "etcd 大盘",
etcdAccessControl: "etcd 访问控制",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
gridfs: "GridFS",
vector: "向量",
@@ -3357,7 +3387,7 @@ export default withEnglishFallback({
},
etcd: {
prefixPlaceholder: "搜索 Key 路径,例如 /app/ 或 service",
- newKey: "新建 Key",
+ newKey: "新建键(Key)",
loadingKeys: "正在加载 Key...",
empty: "未找到 Key",
loadMore: "加载更多",
@@ -3737,6 +3767,7 @@ export default withEnglishFallback({
},
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "路径前缀,例如 /app/",
newKey: "新建 Znode",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 02f6b80d5e..347698454e 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1,5 +1,81 @@
import { withEnglishFallback } from "./fallback";
import docs from "./docs/zh-TW";
+import { consulUiMessages } from "./consulUi";
+
+const consul = {
+ ...consulUiMessages,
+ prefixPlaceholder: "Key 前綴,例如 app/ 或 services/",
+ newKey: "新增 Key",
+ loadingKeys: "正在載入 Key...",
+ empty: "找不到 Key",
+ loadMore: "載入更多",
+ selectKey: "選擇一個 Key 以檢視其值",
+ loadingValue: "正在載入值...",
+ notFound: "找不到 Key",
+ edit: "編輯",
+ editKey: "編輯 Key",
+ delete: "刪除",
+ deleteTitle: "刪除 Consul KV Key",
+ keyLabel: "鍵(Key)",
+ keyPlaceholder: "path/to/key",
+ keyRequired: "Key 不能為空",
+ rootReadonly: "根前綴無法修改,請輸入具體 Key 路徑。",
+ saved: "Key 已儲存",
+ deleted: "Key 已刪除",
+ base64Readonly: "請在 Base64 模式下編輯二進位值。",
+ rename: "重新命名",
+ clone: "複製",
+ copyKey: "複製 Key",
+ export: "匯出",
+ value: "值",
+ valueContent: "值",
+ format: "格式",
+ metadata: "KV 中繼資料",
+ prettyJson: "格式化",
+ invalidJson: "JSON 格式無效",
+ summarySize: "大小",
+ conflict: "此 Key 自載入後已變更,請重新整理後再試。",
+ keyAlreadyExists: "同名 Key 已存在,請使用其他名稱或編輯現有 Key。",
+ aclFiltered: "部分 Consul KV Key 已被 ACL 原則過濾。",
+ locked: "此 Key 正由 Consul Session 持有,無法編輯或刪除。",
+ valueTooLarge: "Consul KV 值不能超過 512 KiB。",
+ watchKey: "監視",
+ stopWatching: "停止",
+ workspace: {
+ overview: "概覽",
+ kv: "KV",
+ services: "服務",
+ health: "健康檢查",
+ sessions: "Session",
+ scope: "作用域",
+ mesh: "Service Mesh",
+ tools: "工具",
+ operator: "Operator",
+ refresh: "重新整理能力資訊",
+ loading: "正在載入 Consul 能力...",
+ agentIdentity: "Agent 身分",
+ capabilities: "能力狀態",
+ version: "版本",
+ edition: "版本類型",
+ datacenter: "資料中心",
+ node: "Agent 節點",
+ mode: "Agent 模式",
+ agent: "Agent API",
+ acl: "ACL",
+ namespaces: "命名空間",
+ partitions: "管理分區",
+ enterprise: "Enterprise",
+ community: "Community",
+ serverMode: "Server",
+ clientMode: "Client",
+ capability: {
+ supported: "支援",
+ unsupported: "不支援",
+ forbidden: "無權限",
+ unknown: "未知",
+ },
+ },
+};
export default withEnglishFallback({
app: {
@@ -438,6 +514,34 @@ export default withEnglishFallback({
etcdClientCertBrowse: "選擇用戶端憑證",
etcdClientKeyBrowse: "選擇用戶端私鑰",
etcdClientCertPairRequired: "用戶端憑證和私鑰必須一起填寫。",
+ consulAddress: "Consul API 位址",
+ consulAddressInvalid: "請輸入不包含憑證、查詢參數或片段的 HTTP/HTTPS Consul API 絕對位址。",
+ consulToken: "ACL Token",
+ consulTokenPlaceholder: "選填的 Consul ACL Token",
+ consulDatacenter: "資料中心",
+ consulNamespace: "命名空間",
+ consulPartition: "管理分區",
+ consulAgentTargetNode: "目標 Agent 節點",
+ consulAgentTargetAddress: "Agent 直連位址",
+ consulAgentTargetHint: "Agent 寫入操作必填。DNS/負載均衡和 Transport Layer 連線維持唯讀。",
+ consulMeshFeatures: "服務網格",
+ consulMeshVisible: "顯示服務網格進階功能",
+ consulMeshVisibleHint: "僅在需要管理 Connect、服務意圖或對等連線時開啟;關閉後主導覽不會顯示服務網格。",
+ consulOperatorWrites: "Operator 寫入",
+ consulOperatorVisible: "顯示實驗性 Operator 工作台",
+ consulOperatorSnapshotRestore: "啟用 Snapshot 還原",
+ consulOperatorAutopilot: "啟用 Autopilot 修改",
+ consulOperatorRaft: "啟用 Raft 修改",
+ consulOperatorKeyring: "啟用 Keyring 修改",
+ consulOperatorLicense: "啟用 License 修改",
+ consulAgentTargetIncomplete: "目標 Agent 節點和直連位址必須同時設定。",
+ consulAgentTargetAddressMismatch: "Agent 直連位址必須與 Consul 位址的主機一致。",
+ consulConsistency: "讀取一致性",
+ consulConsistencyDefault: "預設",
+ consulConsistencyStale: "允許陳舊讀取",
+ consulConsistencyConsistent: "強一致讀取",
+ consulTlsSkipVerify: "略過憑證驗證",
+ consulTlsSkipVerifyHint: "僅用於可信任的自簽章 Consul 端點。",
zookeeperConnectString: "連線字串",
zookeeperConnectStringHint: "以逗號或換行分隔的 host:port 項目。留空則使用上方的主機和連接埠。",
zookeeperCreateModePersistent: "持久",
@@ -1117,6 +1221,7 @@ export default withEnglishFallback({
redis: "Redis",
etcd: "etcd",
zookeeper: "ZooKeeper",
+ consul: "Consul",
mongo: "Mongo",
vector: "向量",
objects: "物件",
@@ -6036,6 +6141,7 @@ export default withEnglishFallback({
leaseCreated: "已建立 Lease {id}",
},
},
+ consul,
zookeeper: {
prefixPlaceholder: "路徑前綴,例如 /app/",
newKey: "新增 Znode",
diff --git a/apps/desktop/src/lib/__tests__/connection/consulConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/consulConnectionDialog.spec.ts
new file mode 100644
index 0000000000..66ae30cca6
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/connection/consulConnectionDialog.spec.ts
@@ -0,0 +1,25 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
+
+function section(startMarker: string, endMarker: string): string {
+ const start = dialogSource.indexOf(startMarker);
+ const end = dialogSource.indexOf(endMarker, start);
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(end).toBeGreaterThan(start);
+ return dialogSource.slice(start, end);
+}
+
+describe("Consul connection dialog", () => {
+ it("keeps Operator feature switches in the Consul form instead of the JDBC form", () => {
+ const jdbcForm = section("<!-- JDBC: optional external plugin -->", "<!-- Local database files: file path only -->");
+ const consulForm = section("<!-- Consul KV: HTTP endpoint, ACL token and scope -->", "<!-- etcd: endpoints, user, password, TLS -->");
+ const operatorModels = ["consulOperatorVisible", "consulOperatorSnapshotRestoreEnabled", "consulOperatorAutopilotWriteEnabled", "consulOperatorRaftWriteEnabled", "consulOperatorKeyringWriteEnabled", "consulOperatorLicenseWriteEnabled"];
+
+ for (const model of operatorModels) {
+ expect(jdbcForm).not.toContain(`v-model="${model}"`);
+ expect(consulForm).toContain(`v-model="${model}"`);
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/kv/slashPrefixLazyKeyTree.spec.ts b/apps/desktop/src/lib/__tests__/kv/slashPrefixLazyKeyTree.spec.ts
new file mode 100644
index 0000000000..376ede4b33
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/kv/slashPrefixLazyKeyTree.spec.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { createLazyKvKeyTreeState, replaceLazyKvChildren } from "@/lib/kv/slashPrefixLazyKeyTree";
+
+describe("slashPrefixLazyKeyTree", () => {
+ it("treats a trailing-slash Consul Key with no children as a leaf after expansion", () => {
+ const state = createLazyKvKeyTreeState("", "relative");
+ replaceLazyKvChildren(state, null, [{ key: "feature/", hasValue: true }], null);
+
+ const node = state.nodeByKey.get("feature/");
+ expect(node?.hasChildren).toBe(true);
+
+ replaceLazyKvChildren(state, "feature/", [], null, { filteredByAcls: false });
+ expect(state.nodeByKey.get("feature/")?.hasChildren).toBe(false);
+ });
+
+ it("keeps the directory affordance when ACL filtering makes an empty listing inconclusive", () => {
+ const state = createLazyKvKeyTreeState("", "relative");
+ replaceLazyKvChildren(state, null, [{ key: "feature/", hasValue: true }], null);
+
+ replaceLazyKvChildren(state, "feature/", [], null, { filteredByAcls: true });
+ expect(state.nodeByKey.get("feature/")?.hasChildren).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeItemLayout.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeItemLayout.spec.ts
index 63e89ea91b..dc7c534135 100644
--- a/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeItemLayout.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeItemLayout.spec.ts
@@ -24,6 +24,7 @@ describe("sidebar tree item layout", () => {
expect(canTreeNodeShowExpander({ type: "etcd-root", childCount: 0 })).toBe(false);
expect(canTreeNodeShowExpander({ type: "etcd-dashboard", childCount: 0 })).toBe(false);
expect(canTreeNodeShowExpander({ type: "etcd-access-control", childCount: 0 })).toBe(false);
+ expect(canTreeNodeShowExpander({ type: "consul-overview", childCount: 0 })).toBe(false);
});
it("aligns comments to the longest sibling name without crossing parent groups", () => {
diff --git a/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts
index b39c6e29e9..93a17dc0d8 100644
--- a/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sidebar/treeNodeClick.spec.ts
@@ -1,9 +1,20 @@
import { describe, expect, it } from "vitest";
-import { objectSourceKindForTreeNode, treeNodeRowAction } from "@/lib/sidebar/treeNodeClick";
+import { isDirectNavigationTreeNode, objectSourceKindForTreeNode, shouldActivateTreeNodeOnSingleClick, treeNodeRowAction } from "@/lib/sidebar/treeNodeClick";
describe("treeNodeClick", () => {
it("opens synonym nodes as synonym source", () => {
expect(objectSourceKindForTreeNode("synonym")).toBe("SYNONYM");
expect(treeNodeRowAction("synonym", false)).toBe("open-source");
});
+
+ it("opens Consul navigation entries on one click regardless of object activation preference", () => {
+ expect(isDirectNavigationTreeNode("consul-root")).toBe(true);
+ expect(isDirectNavigationTreeNode("consul-overview")).toBe(true);
+ expect(isDirectNavigationTreeNode("table")).toBe(false);
+ expect(shouldActivateTreeNodeOnSingleClick("consul-root", "double")).toBe(true);
+ expect(shouldActivateTreeNodeOnSingleClick("consul-overview", "double")).toBe(true);
+ expect(shouldActivateTreeNodeOnSingleClick("table", "double")).toBe(false);
+ expect(treeNodeRowAction("consul-root", false, "double")).toBe("toggle");
+ expect(treeNodeRowAction("consul-overview", false, "double")).toBe("toggle");
+ });
});
diff --git a/apps/desktop/src/lib/__tests__/zookeeper/zookeeperLazyKeyTree.spec.ts b/apps/desktop/src/lib/__tests__/zookeeper/zookeeperLazyKeyTree.spec.ts
index f259b75c44..a976db885e 100644
--- a/apps/desktop/src/lib/__tests__/zookeeper/zookeeperLazyKeyTree.spec.ts
+++ b/apps/desktop/src/lib/__tests__/zookeeper/zookeeperLazyKeyTree.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { createLazyKvKeyTreeState, createZooKeeperChildPathDraft, flattenLazyKvKeyTree, replaceLazyKvChildren, resetLazyKvKeyTree } from "@/lib/zookeeper/zookeeperLazyKeyTree";
+import { createLazyKvKeyTreeState, createZooKeeperChildPathDraft, flattenLazyKvKeyTree, replaceLazyKvChildren, replaceLazyKvFocusedRoot, resetLazyKvKeyTree } from "@/lib/zookeeper/zookeeperLazyKeyTree";
describe("zookeeper lazy key tree", () => {
it("stores only the current path direct children on reset", () => {
@@ -49,4 +49,41 @@ describe("zookeeper lazy key tree", () => {
expect(createZooKeeperChildPathDraft("/app")).toBe("/app/");
expect(createZooKeeperChildPathDraft("app/")).toBe("/app/");
});
+
+ it("keeps an exact focused Key without children as a leaf", () => {
+ const state = createLazyKvKeyTreeState("", "relative");
+
+ replaceLazyKvFocusedRoot(state, { key: "dbx-demo/locks/persistent", numChildren: 0, valueSize: 12, hasValue: true }, [], null);
+
+ const leaf = state.nodeByKey.get("dbx-demo/locks/persistent");
+ expect(leaf?.hasChildren).toBe(false);
+ expect(leaf?.hasValue).toBe(true);
+ expect(leaf?.label).toBe("persistent");
+ });
+
+ it("keeps a real Consul Key and its child prefix as one dual-purpose node", () => {
+ const state = createLazyKvKeyTreeState("", "relative");
+
+ replaceLazyKvFocusedRoot(state, { key: "applications", numChildren: 1, valueSize: 7, hasValue: true }, [{ key: "applications/api", numChildren: 0, valueSize: 3 }], null);
+
+ const root = state.nodeByKey.get("applications");
+ expect(root?.hasValue).toBe(true);
+ expect(root?.hasChildren).toBe(true);
+ expect(root?.children.map((child) => child.key)).toEqual(["applications/api"]);
+ });
+
+ it("requires an exact GET before treating a trailing-slash Consul path as a Key", () => {
+ const state = createLazyKvKeyTreeState("", "relative");
+
+ replaceLazyKvChildren(state, null, [{ key: "applications/", numChildren: 2 }], null);
+
+ const prefix = state.nodeByKey.get("applications/");
+ expect(prefix?.hasChildren).toBe(true);
+ expect(prefix?.hasValue).toBeNull();
+
+ replaceLazyKvFocusedRoot(state, { key: "applications/", numChildren: 0, hasValue: true }, [], null);
+ const exactTrailingSlashKey = state.nodeByKey.get("applications/");
+ expect(exactTrailingSlashKey?.hasChildren).toBe(false);
+ expect(exactTrailingSlashKey?.hasValue).toBe(true);
+ });
});
diff --git a/apps/desktop/src/lib/backend/__tests__/consulCoreEndpointContract.spec.ts b/apps/desktop/src/lib/backend/__tests__/consulCoreEndpointContract.spec.ts
new file mode 100644
index 0000000000..a906c84b4b
--- /dev/null
+++ b/apps/desktop/src/lib/backend/__tests__/consulCoreEndpointContract.spec.ts
@@ -0,0 +1,192 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+type Scope = "global" | "read" | "write";
+type Method = "GET" | "PUT" | "POST" | "DELETE";
+type Contract = { domain: string; file: string; method: Method; path: string; needle?: string; methodNeedle?: string; scopeNeedle?: string; scope: Scope };
+
+const contracts: Contract[] = [
+ { domain: "capabilities", file: "capabilities.rs", method: "GET", path: "/v1/agent/self", scope: "global" },
+ { domain: "capabilities", file: "capabilities.rs", method: "GET", path: "/v1/acl/token/self", scope: "read" },
+ { domain: "kv", file: "kv.rs", method: "GET", path: "/v1/kv/{key-or-prefix}", needle: "/v1/kv/{encoded}", scope: "read" },
+ { domain: "kv", file: "kv.rs", method: "PUT", path: "/v1/kv/{key}", needle: "/v1/kv/{encoded}", scope: "write" },
+ { domain: "kv", file: "kv.rs", method: "DELETE", path: "/v1/kv/{key}", needle: "/v1/kv/{encoded}", scope: "write" },
+ { domain: "txn", file: "txn.rs", method: "PUT", path: "/v1/txn", scope: "write" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/kv/{key-or-prefix}", needle: "/v1/kv/{encoded}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/catalog/nodes", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/catalog/services", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/catalog/service/{service}", needle: "/v1/catalog/service/{}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/catalog/node/{node}", needle: "/v1/catalog/node/{}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/health/node/{node}", needle: "/v1/health/node/{}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/health/checks/{service}", needle: "/v1/health/checks/{}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/health/service/{service}", needle: "/v1/health/service/{}{suffix}", scope: "read" },
+ { domain: "blocking", file: "blocking.rs", method: "GET", path: "/v1/health/state/{state}", needle: "/v1/health/state/{}", scope: "read" },
+ { domain: "status", file: "status.rs", method: "GET", path: "/v1/status/leader", scope: "global" },
+ { domain: "status", file: "status.rs", method: "GET", path: "/v1/status/peers", scope: "global" },
+ { domain: "catalog", file: "catalog.rs", method: "GET", path: "/v1/catalog/datacenters", scope: "global" },
+ { domain: "catalog", file: "catalog.rs", method: "GET", path: "/v1/catalog/nodes", scope: "read" },
+ { domain: "catalog", file: "catalog.rs", method: "GET", path: "/v1/catalog/services", scope: "read" },
+ { domain: "catalog", file: "catalog.rs", method: "GET", path: "/v1/catalog/service/{service}", needle: "/v1/catalog/service/{}", scope: "read" },
+ { domain: "catalog", file: "catalog.rs", method: "GET", path: "/v1/catalog/node/{node}", needle: "/v1/catalog/node/{}", scope: "read" },
+ { domain: "health", file: "health.rs", method: "GET", path: "/v1/health/node/{node}", needle: "/v1/health/node/{}", methodNeedle: "read_list(", scope: "read" },
+ { domain: "health", file: "health.rs", method: "GET", path: "/v1/health/checks/{service}", needle: "/v1/health/checks/{}", methodNeedle: "read_list(", scope: "read" },
+ { domain: "health", file: "health.rs", method: "GET", path: "/v1/health/service/{service}", needle: "/v1/health/service/{}", methodNeedle: "read_list(", scope: "read" },
+ { domain: "health", file: "health.rs", method: "GET", path: "/v1/health/state/{state}", needle: "/v1/health/state/{state}", methodNeedle: "read_list(", scope: "read" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/self", scope: "global" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/members", scope: "global" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/metrics", scope: "global" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/services", scope: "read" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/service/{id}", needle: "/v1/agent/service/{}", scope: "read" },
+ { domain: "agent", file: "agent.rs", method: "GET", path: "/v1/agent/checks", scope: "read" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/service/register", scope: "write" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/service/deregister/{id}", needle: "/v1/agent/service/deregister/{}", scope: "write" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/service/maintenance/{id}", needle: "/v1/agent/service/maintenance/{}", scope: "write" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/check/register", scope: "write" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/check/deregister/{id}", needle: "/v1/agent/check/deregister/{}", scope: "write" },
+ { domain: "agent", file: "agent.rs", method: "PUT", path: "/v1/agent/check/update/{id}", needle: "/v1/agent/check/update/{}", scope: "write" },
+ { domain: "session", file: "session.rs", method: "GET", path: "/v1/session/list", scope: "read" },
+ { domain: "session", file: "session.rs", method: "GET", path: "/v1/session/node/{node}", needle: "/v1/session/node/{}", scope: "read" },
+ { domain: "session", file: "session.rs", method: "GET", path: "/v1/session/info/{id}", needle: "/v1/session/info/{}", scope: "read" },
+ { domain: "session", file: "session.rs", method: "PUT", path: "/v1/session/create", scope: "write" },
+ { domain: "session", file: "session.rs", method: "PUT", path: "/v1/session/renew/{id}", needle: "/v1/session/renew/{}", scope: "write" },
+ { domain: "session", file: "session.rs", method: "PUT", path: "/v1/session/destroy/{id}", needle: "/v1/session/destroy/{}", scope: "write" },
+ { domain: "acl", file: "acl.rs", method: "GET", path: "/v1/acl/token/self", scope: "read" },
+ { domain: "acl", file: "acl.rs", method: "PUT", path: "/v1/acl/token/{id}/clone", needle: "/v1/acl/token/{accessor_id}/clone", scope: "write" },
+ { domain: "acl", file: "acl.rs", method: "GET", path: "/v1/acl/{tokens|policies|roles|auth-methods|binding-rules|templated-policies}", needle: "/v1/acl/tokens", scope: "read" },
+ { domain: "acl", file: "acl.rs", method: "PUT", path: "/v1/acl/{token|policy|role|auth-method|binding-rule}", needle: "/v1/acl/token", scope: "write" },
+ { domain: "acl", file: "acl.rs", method: "PUT", path: "/v1/acl/{kind}/{id}", needle: "(Method::PUT, item_path", scope: "write" },
+ { domain: "acl", file: "acl.rs", method: "DELETE", path: "/v1/acl/{kind}/{id}", needle: "item_path(kind, id)", scope: "write" },
+ { domain: "enterprise", file: "enterprise.rs", method: "GET", path: "/v1/namespaces", scope: "read" },
+ { domain: "enterprise", file: "enterprise.rs", method: "GET", path: "/v1/partitions", scope: "read" },
+ { domain: "enterprise", file: "enterprise.rs", method: "GET", path: "/v1/{namespace|partition}/{name}", needle: "/v1/namespace/{name}", scope: "read" },
+ { domain: "enterprise", file: "enterprise.rs", method: "PUT", path: "/v1/{namespace|partition}", needle: "/v1/namespace", scope: "write" },
+ { domain: "enterprise", file: "enterprise.rs", method: "PUT", path: "/v1/{namespace|partition}/{name}", needle: "Some(name) => (Method::PUT", scope: "write" },
+ { domain: "enterprise", file: "enterprise.rs", method: "DELETE", path: "/v1/{namespace|partition}/{name}", needle: "client.send(Method::DELETE", scopeNeedle: "append_enterprise_target", scope: "write" },
+ { domain: "mesh-config", file: "mesh/config_entries.rs", method: "GET", path: "/v1/config/{kind}", needle: "/v1/config/{}", scope: "read" },
+ { domain: "mesh-config", file: "mesh/config_entries.rs", method: "GET", path: "/v1/config/{kind}/{name}", needle: "/v1/config/{}/{}", scope: "read" },
+ { domain: "mesh-config", file: "mesh/config_entries.rs", method: "PUT", path: "/v1/config", scope: "write" },
+ { domain: "mesh-config", file: "mesh/config_entries.rs", method: "DELETE", path: "/v1/config/{kind}/{name}", needle: "config_path(kind, name)", scope: "write" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "GET", path: "/v1/connect/intentions", scope: "read" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "GET", path: "/v1/connect/intentions/{id}", needle: "/v1/connect/intentions/{}", scope: "read" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "GET", path: "/v1/connect/intentions/exact", scope: "read" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "PUT", path: "/v1/connect/intentions/exact", scope: "write" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "DELETE", path: "/v1/connect/intentions/{id|exact}", needle: "send_json(Method::DELETE", scope: "write" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "GET", path: "/v1/connect/intentions/match", scope: "read" },
+ { domain: "intentions", file: "mesh/intentions.rs", method: "GET", path: "/v1/connect/intentions/check", scope: "read" },
+ { domain: "discovery", file: "mesh/discovery.rs", method: "GET", path: "/v1/discovery-chain/{service}", needle: "/v1/discovery-chain/{service}", scope: "read" },
+ { domain: "peering", file: "mesh/peering.rs", method: "GET", path: "/v1/peerings", scope: "read" },
+ { domain: "peering", file: "mesh/peering.rs", method: "GET", path: "/v1/peering/{name}", needle: "/v1/peering/{}", scope: "read" },
+ { domain: "peering", file: "mesh/peering.rs", method: "POST", path: "/v1/peering/token", scope: "write" },
+ { domain: "peering", file: "mesh/peering.rs", method: "POST", path: "/v1/peering/establish", scope: "write" },
+ { domain: "peering", file: "mesh/peering.rs", method: "DELETE", path: "/v1/peering/{name}", needle: "send_json(Method::DELETE", scope: "write" },
+ { domain: "exported-services", file: "mesh/exported_services.rs", method: "GET", path: "/v1/exported-services", scope: "read" },
+ { domain: "exported-services", file: "mesh/exported_services.rs", method: "PUT", path: "/v1/config", needle: "consul_mesh_config_apply_core", methodNeedle: "consul_mesh_config_apply_core", scopeNeedle: "consul_mesh_config_apply_core", scope: "write" },
+ { domain: "tools", file: "tools.rs", method: "GET", path: "/v1/query", scope: "read" },
+ { domain: "tools", file: "tools.rs", method: "POST", path: "/v1/query", scope: "write" },
+ { domain: "tools", file: "tools.rs", method: "PUT", path: "/v1/query/{id}", needle: "/v1/query/{}", scope: "write" },
+ { domain: "tools", file: "tools.rs", method: "DELETE", path: "/v1/query/{id}", needle: "send_json(Method::DELETE", scope: "write" },
+ { domain: "tools", file: "tools.rs", method: "GET", path: "/v1/query/{id}/execute", needle: "/v1/query/{}/execute", scope: "read" },
+ { domain: "tools", file: "tools.rs", method: "GET", path: "/v1/query/{id}/explain", needle: "/v1/query/{}/explain", scope: "read" },
+ { domain: "tools", file: "tools.rs", method: "GET", path: "/v1/event/list", scope: "read" },
+ { domain: "tools", file: "tools.rs", method: "PUT", path: "/v1/event/fire/{name}", needle: "/v1/event/fire/{}", scope: "write" },
+ { domain: "tools", file: "tools.rs", method: "GET", path: "/v1/coordinate/nodes", scope: "read" },
+ { domain: "operator", file: "operator.rs", method: "GET", path: "/v1/operator/{autopilot|raft|usage|license}", needle: "/v1/operator/autopilot/configuration", scope: "read" },
+ { domain: "operator", file: "operator.rs", method: "POST", path: "/v1/operator/audit-hash", scope: "read" },
+ { domain: "operator", file: "operator.rs", method: "GET", path: "/v1/snapshot", scope: "read" },
+ { domain: "operator", file: "operator.rs", method: "PUT", path: "/v1/snapshot", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "PUT", path: "/v1/operator/autopilot/configuration", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "POST", path: "/v1/operator/raft/transfer-leader", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "DELETE", path: "/v1/operator/raft/peer", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "POST", path: "/v1/operator/keyring", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "PUT", path: "/v1/operator/keyring", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "DELETE", path: "/v1/operator/keyring", scope: "write" },
+ { domain: "operator", file: "operator.rs", method: "PUT", path: "/v1/operator/license", scope: "write" },
+];
+
+const sourceCache = new Map<string, string>();
+function source(file: string): string {
+ if (!sourceCache.has(file)) sourceCache.set(file, readFileSync(join(process.cwd(), "crates/dbx-core/src/consul", file), "utf8"));
+ return sourceCache.get(file)!;
+}
+
+const methodScopeSnapshot = {
+ "kv.rs": [4, 3, 0, 1, 4, 4],
+ "txn.rs": [0, 1, 0, 0, 0, 1],
+ "blocking.rs": [2, 0, 0, 0, 2, 0],
+ "status.rs": [2, 0, 0, 0, 0, 0],
+ "catalog.rs": [2, 0, 0, 0, 5, 0],
+ "health.rs": [0, 0, 0, 0, 4, 0],
+ "agent.rs": [6, 2, 0, 0, 3, 2],
+ "session.rs": [1, 3, 0, 0, 3, 3],
+ "acl.rs": [9, 3, 0, 1, 9, 3],
+ "enterprise.rs": [5, 2, 0, 1, 3, 2],
+ "mesh/config_entries.rs": [2, 1, 0, 1, 2, 2],
+ "mesh/intentions.rs": [6, 1, 0, 2, 6, 3],
+ "mesh/discovery.rs": [1, 0, 0, 0, 1, 0],
+ "mesh/peering.rs": [2, 0, 2, 1, 2, 3],
+ "mesh/exported_services.rs": [1, 0, 0, 0, 1, 0],
+ "tools.rs": [7, 2, 1, 1, 5, 3],
+ "operator.rs": [2, 4, 3, 2, 3, 6],
+ "capabilities.rs": [3, 0, 1, 0, 3, 0],
+} satisfies Record<string, [number, number, number, number, number, number]>;
+
+describe("Consul Core endpoint contract", () => {
+ it("enumerates every supported domain without duplicate rows", () => {
+ expect(new Set(contracts.map(({ domain }) => domain))).toEqual(new Set(["capabilities", "kv", "txn", "blocking", "status", "catalog", "health", "agent", "session", "acl", "enterprise", "mesh-config", "intentions", "discovery", "peering", "exported-services", "tools", "operator"]));
+ const identities = contracts.map(({ domain, method, path, scope }) => `${domain}:${method}:${path}:${scope}`);
+ expect(new Set(identities).size).toBe(identities.length);
+ });
+
+ it.each(contracts)("$domain $method $path uses $scope scope", ({ file, method, path, needle, methodNeedle, scopeNeedle, scope }) => {
+ const code = source(file);
+ const evidence = needle ?? path;
+ expect(code, `${file} path evidence for ${path}`).toContain(evidence);
+ expect(code, `${file} method evidence for ${method} ${path}`).toContain(methodNeedle ?? `Method::${method}`);
+ if (scopeNeedle) expect(code, `${file} scope delegation for ${path}`).toContain(scopeNeedle);
+ else if (scope === "read") expect(code).toMatch(/append_scope\(&mut url, true\)|request_json\([\s\S]*?true|send_json\([\s\S]*?true|read_list\(/);
+ else if (scope === "write") expect(code).toMatch(/append_scope\(&mut url, false\)|request_json\([\s\S]*?false|send_json\([\s\S]*?false|ensure_writable/);
+ });
+
+ it("centralizes scoped requests and ACL token headers", () => {
+ const client = source("client.rs");
+ expect(client).toContain("self.append_scope(&mut url, read);");
+ expect(client).toContain('request.header("X-Consul-Token", &self.config.token)');
+ expect(client.match(/request\.header\("X-Consul-Token"/g)).toHaveLength(2);
+ });
+
+ it("keeps gossip keys in the request body and maps each operation to its official method", () => {
+ const operator = source("operator.rs");
+ expect(operator).toContain("ConsulKeyringOperation::Install => Method::POST");
+ expect(operator).toContain("ConsulKeyringOperation::Use => Method::PUT");
+ expect(operator).toContain("ConsulKeyringOperation::Remove => Method::DELETE");
+ expect(operator).toContain("ConsulKeyringWriteBody { key: request.key.trim() }");
+ expect(operator).not.toMatch(/query_pairs_mut\(\)\.append_pair\([^\n]*request\.key/);
+ });
+
+ it("uses the official write methods for ACL, Enterprise, and Audit endpoints", () => {
+ const acl = source("acl.rs");
+ expect(acl).toContain('request_json(Method::PUT, url, Some(&request), false, "clone ACL token")');
+ expect(acl).toContain("(Method::PUT, collection_create_path(kind)?.to_string())");
+
+ const enterprise = source("enterprise.rs");
+ expect(enterprise).toMatch(/None => \(\s*Method::PUT,/);
+
+ const operator = source("operator.rs");
+ expect(operator).toContain('ConsulOperatorReadKind::Audit => "/v1/operator/audit-hash"');
+ expect(operator).toMatch(/matches!\(kind, ConsulOperatorReadKind::Audit\)[\s\S]*?request_json\(\s*Method::POST/);
+ });
+
+ it.each(Object.entries(methodScopeSnapshot))("keeps %s method/scope call counts stable", (file, expected) => {
+ const code = source(file).split("#[cfg(test)]")[0];
+ const count = (pattern: RegExp) => code.match(pattern)?.length ?? 0;
+ expect([
+ count(/Method::GET/g),
+ count(/Method::PUT/g),
+ count(/Method::POST/g),
+ count(/Method::DELETE/g),
+ count(/(?:request_json|send_json)\([^;]*?true/g) + count(/append_scope\(&mut url, true/g) + count(/read_list\(/g),
+ count(/(?:request_json|send_json)\([^;]*?false/g) + count(/append_scope\(&mut url, false/g) + count(/request_json_unscoped\(/g),
+ ]).toEqual(expected);
+ });
+});
diff --git a/apps/desktop/src/lib/backend/__tests__/consulTransportContract.spec.ts b/apps/desktop/src/lib/backend/__tests__/consulTransportContract.spec.ts
new file mode 100644
index 0000000000..f73644db8a
--- /dev/null
+++ b/apps/desktop/src/lib/backend/__tests__/consulTransportContract.spec.ts
@@ -0,0 +1,166 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const tauri = readFileSync(new URL("../tauri.ts", import.meta.url), "utf8");
+const http = readFileSync(new URL("../http.ts", import.meta.url), "utf8");
+const api = readFileSync(new URL("../api.ts", import.meta.url), "utf8");
+const tauriRegistry = readFileSync(new URL("../../../../../../src-tauri/src/lib.rs", import.meta.url), "utf8");
+const webRegistry = readFileSync(new URL("../../../../../../crates/dbx-web/src/main.rs", import.meta.url), "utf8");
+const operations = [...api.matchAll(/export const (consul\w+) = forward/g)].map((match) => match[1]);
+const expectedOperations = [
+ "consulCapabilities",
+ "consulTxn",
+ "consulRenameKey",
+ "consulBlockingQuery",
+ "consulDomainWatch",
+ "consulCancelBlocking",
+ "consulWatchStart",
+ "consulListRecursive",
+ "consulSearch",
+ "consulSearchProgress",
+ "consulCancelSearch",
+ "consulExportBundle",
+ "consulImportPreview",
+ "consulImportExecute",
+ "consulDeletePrefixPreview",
+ "consulDeletePrefixExecute",
+ "consulListPrefix",
+ "consulGet",
+ "consulPut",
+ "consulDelete",
+ "consulPreparedQueryList",
+ "consulPreparedQueryRead",
+ "consulPreparedQueryCreate",
+ "consulPreparedQueryUpdate",
+ "consulPreparedQueryDelete",
+ "consulPreparedQueryExecute",
+ "consulPreparedQueryExplain",
+ "consulEventList",
+ "consulEventFire",
+ "consulCoordinateNodes",
+ "consulOperatorRead",
+ "consulSnapshotGenerate",
+ "consulSnapshotRestore",
+ "consulAutopilotUpdate",
+ "consulRaftTransfer",
+ "consulRaftRemove",
+ "consulKeyringWrite",
+ "consulLicenseWrite",
+ "consulStatusLeader",
+ "consulStatusPeers",
+ "consulAgentSelf",
+ "consulAgentMembers",
+ "consulAgentMetrics",
+ "consulCatalogDatacenters",
+ "consulCatalogNodes",
+ "consulCatalogServices",
+ "consulCatalogServiceNodes",
+ "consulCatalogNodeServices",
+ "consulHealthNode",
+ "consulHealthChecks",
+ "consulHealthService",
+ "consulHealthState",
+ "consulAgentServices",
+ "consulAgentService",
+ "consulAgentChecks",
+ "consulAgentRegisterService",
+ "consulAgentDeregisterService",
+ "consulAgentServiceMaintenance",
+ "consulAgentRegisterCheck",
+ "consulAgentDeregisterCheck",
+ "consulAgentUpdateTtl",
+ "consulSessions",
+ "consulNodeSessions",
+ "consulSession",
+ "consulSessionKeys",
+ "consulSessionDestroyImpact",
+ "consulCreateSession",
+ "consulRenewSession",
+ "consulDestroySession",
+ "consulAcquireLock",
+ "consulReleaseLock",
+ "consulAclList",
+ "consulAclTokenSelf",
+ "consulAclTokenClone",
+ "consulAclGet",
+ "consulAclApply",
+ "consulAclReferences",
+ "consulAclDelete",
+ "consulEnterpriseList",
+ "consulEnterpriseGet",
+ "consulEnterpriseApply",
+ "consulEnterpriseImpact",
+ "consulEnterpriseDelete",
+ "consulMeshConfigList",
+ "consulMeshConfigGet",
+ "consulMeshConfigApply",
+ "consulMeshConfigDelete",
+ "consulMeshIntentionsList",
+ "consulMeshIntentionGet",
+ "consulMeshIntentionGetExact",
+ "consulMeshIntentionUpsert",
+ "consulMeshIntentionDelete",
+ "consulMeshIntentionDeleteExact",
+ "consulMeshIntentionMatch",
+ "consulMeshIntentionCheck",
+ "consulMeshDiscoveryChain",
+ "consulMeshPeeringList",
+ "consulMeshPeeringGet",
+ "consulMeshPeeringGenerateToken",
+ "consulMeshPeeringEstablish",
+ "consulMeshPeeringDelete",
+ "consulMeshExportedServicesList",
+ "consulMeshExportedServicesApply",
+] as const;
+
+function functionBody(source: string, operation: string): string {
+ const start = source.indexOf(`export async function ${operation}(`);
+ expect(start, `${operation} transport function`).toBeGreaterThanOrEqual(0);
+ const end = source.indexOf("\nexport async function ", start + 1);
+ return source.slice(start, end === -1 ? source.length : end);
+}
+
+function snakeCase(value: string): string {
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
+}
+
+describe("Consul dual transport contract", () => {
+ it.each(operations)("exports %s in Tauri and Web transports", (operation) => {
+ expect(tauri).toContain(`function ${operation}`);
+ expect(http).toContain(`function ${operation}`);
+ });
+
+ it("covers every public Consul operation", () => {
+ expect(operations).toEqual(expectedOperations);
+ expect(new Set(operations).size).toBe(operations.length);
+ });
+
+ it.each(expectedOperations)("registers %s end-to-end", (operation) => {
+ const command = functionBody(tauri, operation).match(/invoke\("([^"]+)"/)?.[1];
+ const httpBody = functionBody(http, operation);
+ const route = httpBody.match(/post\("([^"]+)"/)?.[1] ?? (operation === "consulWatchStart" && httpBody.includes("consulBlockingQuery") ? "/api/consul/blocking-query" : undefined);
+ expect(command, `${operation} invoke command`).toBe(snakeCase(operation));
+ expect(route, `${operation} HTTP route`).toMatch(/^\/api\/consul\//);
+ expect(tauriRegistry).toContain(`commands::consul_cmd::${command},`);
+ expect(webRegistry).toContain(`.route("${route?.replace(/^\/api/, "")}", post(`);
+ });
+
+ it("routes cancellable Catalog and Health watches through both transports", () => {
+ expect(tauri).toContain('invoke("consul_domain_watch"');
+ expect(http).toContain('post("/api/consul/domain-watch"');
+ expect(api).toContain('consulDomainWatch = forward("consulDomainWatch")');
+ });
+
+ it("exposes the Agent service detail endpoint in both transports", () => {
+ expect(tauri).toContain('invoke("consul_agent_service"');
+ expect(http).toContain('post("/api/consul/agent/service"');
+ expect(api).toContain('consulAgentService = forward("consulAgentService")');
+ });
+
+ it("keeps advanced domains asynchronously split", () => {
+ const workspace = readFileSync(new URL("../../../components/consul/ConsulWorkspace.vue", import.meta.url), "utf8");
+ for (const component of ["ConsulKeyBrowser", "ConsulServices", "ConsulHealth", "ConsulSessions", "ConsulAcl", "ConsulScope", "ConsulMesh", "ConsulTools", "ConsulOperator"]) {
+ expect(workspace).toContain(`const ${component} = defineAsyncComponent`);
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts b/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts
index b68b10db96..e980f26733 100644
--- a/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts
+++ b/apps/desktop/src/lib/backend/__tests__/debugLog.spec.ts
@@ -99,4 +99,19 @@ describe("debug log local timestamps", () => {
expect(text).toContain(`[${timestamp}] [INFO] hello`);
expect(text).not.toContain(".882Z");
});
+
+ it("redacts Consul and nested identity-provider secrets", () => {
+ localStorage.setItem(DEBUG_LOG_ENABLED_KEY, "1");
+ appendDebugLog("error", {
+ SecretID: "acl-secret",
+ peering_token: "peering-secret",
+ nested: { OIDCClientSecret: "oidc-secret", safe: "visible" },
+ });
+
+ const text = getDebugLogText();
+ expect(text).not.toContain("acl-secret");
+ expect(text).not.toContain("peering-secret");
+ expect(text).not.toContain("oidc-secret");
+ expect(text).toContain("visible");
+ });
});
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 189d6e931a..04b80b3907 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -470,6 +470,111 @@ export const zookeeperGet = forward("zookeeperGet");
export const zookeeperPut = forward("zookeeperPut");
export const zookeeperDelete = forward("zookeeperDelete");
+// Consul KV
+export const consulCapabilities = forward("consulCapabilities");
+export const consulTxn = forward("consulTxn");
+export const consulRenameKey = forward("consulRenameKey");
+export const consulBlockingQuery = forward("consulBlockingQuery");
+export const consulDomainWatch = forward("consulDomainWatch");
+export const consulCancelBlocking = forward("consulCancelBlocking");
+export const consulWatchStart = forward("consulWatchStart");
+export const consulListRecursive = forward("consulListRecursive");
+export const consulSearch = forward("consulSearch");
+export const consulSearchProgress = forward("consulSearchProgress");
+export const consulCancelSearch = forward("consulCancelSearch");
+export const consulExportBundle = forward("consulExportBundle");
+export const consulImportPreview = forward("consulImportPreview");
+export const consulImportExecute = forward("consulImportExecute");
+export const consulDeletePrefixPreview = forward("consulDeletePrefixPreview");
+export const consulDeletePrefixExecute = forward("consulDeletePrefixExecute");
+export const consulListPrefix = forward("consulListPrefix");
+export const consulGet = forward("consulGet");
+export const consulPut = forward("consulPut");
+export const consulDelete = forward("consulDelete");
+export const consulPreparedQueryList = forward("consulPreparedQueryList");
+export const consulPreparedQueryRead = forward("consulPreparedQueryRead");
+export const consulPreparedQueryCreate = forward("consulPreparedQueryCreate");
+export const consulPreparedQueryUpdate = forward("consulPreparedQueryUpdate");
+export const consulPreparedQueryDelete = forward("consulPreparedQueryDelete");
+export const consulPreparedQueryExecute = forward("consulPreparedQueryExecute");
+export const consulPreparedQueryExplain = forward("consulPreparedQueryExplain");
+export const consulEventList = forward("consulEventList");
+export const consulEventFire = forward("consulEventFire");
+export const consulCoordinateNodes = forward("consulCoordinateNodes");
+export const consulOperatorRead = forward("consulOperatorRead");
+export const consulSnapshotGenerate = forward("consulSnapshotGenerate");
+export const consulSnapshotRestore = forward("consulSnapshotRestore");
+export const consulAutopilotUpdate = forward("consulAutopilotUpdate");
+export const consulRaftTransfer = forward("consulRaftTransfer");
+export const consulRaftRemove = forward("consulRaftRemove");
+export const consulKeyringWrite = forward("consulKeyringWrite");
+export const consulLicenseWrite = forward("consulLicenseWrite");
+export const consulStatusLeader = forward("consulStatusLeader");
+export const consulStatusPeers = forward("consulStatusPeers");
+export const consulAgentSelf = forward("consulAgentSelf");
+export const consulAgentMembers = forward("consulAgentMembers");
+export const consulAgentMetrics = forward("consulAgentMetrics");
+export const consulCatalogDatacenters = forward("consulCatalogDatacenters");
+export const consulCatalogNodes = forward("consulCatalogNodes");
+export const consulCatalogServices = forward("consulCatalogServices");
+export const consulCatalogServiceNodes = forward("consulCatalogServiceNodes");
+export const consulCatalogNodeServices = forward("consulCatalogNodeServices");
+export const consulHealthNode = forward("consulHealthNode");
+export const consulHealthChecks = forward("consulHealthChecks");
+export const consulHealthService = forward("consulHealthService");
+export const consulHealthState = forward("consulHealthState");
+export const consulAgentServices = forward("consulAgentServices");
+export const consulAgentService = forward("consulAgentService");
+export const consulAgentChecks = forward("consulAgentChecks");
+export const consulAgentRegisterService = forward("consulAgentRegisterService");
+export const consulAgentDeregisterService = forward("consulAgentDeregisterService");
+export const consulAgentServiceMaintenance = forward("consulAgentServiceMaintenance");
+export const consulAgentRegisterCheck = forward("consulAgentRegisterCheck");
+export const consulAgentDeregisterCheck = forward("consulAgentDeregisterCheck");
+export const consulAgentUpdateTtl = forward("consulAgentUpdateTtl");
+export const consulSessions = forward("consulSessions");
+export const consulNodeSessions = forward("consulNodeSessions");
+export const consulSession = forward("consulSession");
+export const consulSessionKeys = forward("consulSessionKeys");
+export const consulSessionDestroyImpact = forward("consulSessionDestroyImpact");
+export const consulCreateSession = forward("consulCreateSession");
+export const consulRenewSession = forward("consulRenewSession");
+export const consulDestroySession = forward("consulDestroySession");
+export const consulAcquireLock = forward("consulAcquireLock");
+export const consulReleaseLock = forward("consulReleaseLock");
+export const consulAclList = forward("consulAclList");
+export const consulAclTokenSelf = forward("consulAclTokenSelf");
+export const consulAclTokenClone = forward("consulAclTokenClone");
+export const consulAclGet = forward("consulAclGet");
+export const consulAclApply = forward("consulAclApply");
+export const consulAclReferences = forward("consulAclReferences");
+export const consulAclDelete = forward("consulAclDelete");
+export const consulEnterpriseList = forward("consulEnterpriseList");
+export const consulEnterpriseGet = forward("consulEnterpriseGet");
+export const consulEnterpriseApply = forward("consulEnterpriseApply");
+export const consulEnterpriseImpact = forward("consulEnterpriseImpact");
+export const consulEnterpriseDelete = forward("consulEnterpriseDelete");
+export const consulMeshConfigList = forward("consulMeshConfigList");
+export const consulMeshConfigGet = forward("consulMeshConfigGet");
+export const consulMeshConfigApply = forward("consulMeshConfigApply");
+export const consulMeshConfigDelete = forward("consulMeshConfigDelete");
+export const consulMeshIntentionsList = forward("consulMeshIntentionsList");
+export const consulMeshIntentionGet = forward("consulMeshIntentionGet");
+export const consulMeshIntentionGetExact = forward("consulMeshIntentionGetExact");
+export const consulMeshIntentionUpsert = forward("consulMeshIntentionUpsert");
+export const consulMeshIntentionDelete = forward("consulMeshIntentionDelete");
+export const consulMeshIntentionDeleteExact = forward("consulMeshIntentionDeleteExact");
+export const consulMeshIntentionMatch = forward("consulMeshIntentionMatch");
+export const consulMeshIntentionCheck = forward("consulMeshIntentionCheck");
+export const consulMeshDiscoveryChain = forward("consulMeshDiscoveryChain");
+export const consulMeshPeeringList = forward("consulMeshPeeringList");
+export const consulMeshPeeringGet = forward("consulMeshPeeringGet");
+export const consulMeshPeeringGenerateToken = forward("consulMeshPeeringGenerateToken");
+export const consulMeshPeeringEstablish = forward("consulMeshPeeringEstablish");
+export const consulMeshPeeringDelete = forward("consulMeshPeeringDelete");
+export const consulMeshExportedServicesList = forward("consulMeshExportedServicesList");
+export const consulMeshExportedServicesApply = forward("consulMeshExportedServicesApply");
+
// HBase
export const hbaseGetTableSchema = forward("hbaseGetTableSchema");
export const hbaseScanRows = forward("hbaseScanRows");
diff --git a/apps/desktop/src/lib/backend/debugLog.ts b/apps/desktop/src/lib/backend/debugLog.ts
index 9c7bf8cb47..20bd7a507a 100644
--- a/apps/desktop/src/lib/backend/debugLog.ts
+++ b/apps/desktop/src/lib/backend/debugLog.ts
@@ -53,7 +53,7 @@ function readEntries(): DebugLogEntry[] {
}
function redactSensitiveText(value: string): string {
- return value.replace(/("(?:password|passphrase|apiKey|api_key|token|secret|connectionString|connection_string)"\s*:\s*")([^"]*)(")/gi, "$1[redacted]$3").replace(/\b(password|passphrase|apiKey|api_key|token|secret)=([^&\s]+)/gi, "$1=[redacted]");
+ return value.replace(/("[^"]*(?:password|passphrase|api[_-]?key|token|secret|jwt|connection[_-]?string)[^"]*"\s*:\s*")([^"]*)(")/gi, "$1[redacted]$3").replace(/\b([^=&\s]*(?:password|passphrase|api[_-]?key|token|secret|jwt)[^=&\s]*)=([^&\s]+)/gi, "$1=[redacted]");
}
function formatValue(value: unknown, seen = new WeakSet<object>()): string {
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 49384493ac..f3c1ba04fa 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -2706,6 +2706,355 @@ export async function zookeeperDelete(connectionId: string, key: string): Promis
return post("/api/zookeeper/delete", { connectionId, key });
}
+// ---------------------------------------------------------------------------
+// Consul
+// ---------------------------------------------------------------------------
+
+export async function consulCapabilities(connectionId: string): Promise<import("@/types/consul").ConsulCapabilities> {
+ return post("/api/consul/capabilities", { connectionId });
+}
+
+export async function consulTxn(connectionId: string, request: import("@/types/consul").ConsulTxnRequest): Promise<import("@/types/consul").ConsulTxnResult> {
+ return post("/api/consul/txn", { connectionId, request });
+}
+
+export async function consulRenameKey(connectionId: string, source: string, target: string, expectedModifyIndex: KvInt64, copy = false): Promise<import("@/types/consul").ConsulTxnResult> {
+ return post("/api/consul/rename-key", { connectionId, source, target, expectedModifyIndex, copy });
+}
+
+export async function consulBlockingQuery(connectionId: string, request: import("@/types/consul").ConsulBlockingRequest): Promise<import("@/types/consul").ConsulBlockingResponse> {
+ return post("/api/consul/blocking-query", { connectionId, request });
+}
+
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogServices" } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<Record<string, string[]>>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogNodes" } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulCatalogNode[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogServiceNodes"; service: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulCatalogServiceNode[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogNodeServices"; node: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulNodeServices>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthNode"; node: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthServiceChecks"; service: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(
+ connectionId: string,
+ request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthServiceInstances"; service: string; passing: boolean | null } },
+): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulServiceInstance[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthState"; state: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulDomainWatchItems>>;
+export async function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulDomainWatchItems>> {
+ return post("/api/consul/domain-watch", { connectionId, request });
+}
+
+export async function consulCancelBlocking(connectionId: string, scope: import("@/types/consul").ConsulScope, generation: number, operationId: string): Promise<boolean> {
+ return post("/api/consul/cancel-blocking", { connectionId, scope, generation, operationId });
+}
+
+export async function consulWatchStart(connectionId: string, request: import("@/types/consul").ConsulBlockingRequest): Promise<string> {
+ await consulBlockingQuery(connectionId, request);
+ return request.operationId;
+}
+
+export async function consulListRecursive(connectionId: string, prefix: string, maxEntries = 10_000, maxValueBytes = 32 * 1024 * 1024): Promise<import("@/types/consul").ConsulRecursiveListResponse> {
+ return post("/api/consul/list-recursive", { connectionId, prefix, maxEntries, maxValueBytes });
+}
+
+export async function consulSearch(connectionId: string, request: import("@/types/consul").ConsulSearchRequest): Promise<import("@/types/consul").ConsulSearchResponse> {
+ return post("/api/consul/search", { connectionId, request });
+}
+
+export async function consulSearchProgress(connectionId: string, requestId: string, scope: import("@/types/consul").ConsulScope, generation: number): Promise<import("@/types/consul").ConsulSearchProgress> {
+ return post("/api/consul/search-progress", { connectionId, requestId, scope, generation });
+}
+
+export async function consulCancelSearch(connectionId: string, requestId: string, scope: import("@/types/consul").ConsulScope, generation: number): Promise<boolean> {
+ return post("/api/consul/cancel-search", { connectionId, requestId, scope, generation });
+}
+
+export async function consulExportBundle(connectionId: string, request: import("@/types/consul").ConsulExportRequest): Promise<import("@/types/consul").ConsulKvBundle> {
+ return post("/api/consul/export-bundle", { connectionId, request });
+}
+
+export async function consulImportPreview(connectionId: string, request: import("@/types/consul").ConsulImportRequest): Promise<import("@/types/consul").ConsulImportPreview> {
+ return post("/api/consul/import-preview", { connectionId, request });
+}
+
+export async function consulImportExecute(connectionId: string, request: import("@/types/consul").ConsulImportRequest): Promise<import("@/types/consul").ConsulImportReport> {
+ return post("/api/consul/import-execute", { connectionId, request });
+}
+
+export async function consulDeletePrefixPreview(connectionId: string, prefix: string): Promise<import("@/types/consul").ConsulDeletePrefixPreview> {
+ return post("/api/consul/delete-prefix-preview", { connectionId, prefix });
+}
+
+export async function consulDeletePrefixExecute(connectionId: string, request: import("@/types/consul").ConsulDeletePrefixRequest): Promise<import("@/types/consul").ConsulDeletePrefixReport> {
+ return post("/api/consul/delete-prefix-execute", { connectionId, request });
+}
+
+export async function consulListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
+ return post("/api/consul/list-prefix", { connectionId, prefix, limit, continuation: continuation ?? null });
+}
+
+export async function consulGet(connectionId: string, key: string): Promise<KvGetResponse> {
+ return post("/api/consul/get", { connectionId, key });
+}
+
+export async function consulPut(connectionId: string, key: string, value: KvValue, options?: KvPutOptions | null): Promise<KvPutResponse> {
+ return post("/api/consul/put", { connectionId, key, value, options: options ?? null });
+}
+
+export async function consulDelete(connectionId: string, key: string, options?: KvDeleteOptions | null): Promise<KvDeleteResponse> {
+ return post("/api/consul/delete", { connectionId, key, options: options ?? null });
+}
+
+export async function consulPreparedQueryList(connectionId: string): Promise<import("@/types/consul").ConsulPreparedQuery[]> {
+ return post("/api/consul/prepared-query/list", { connectionId });
+}
+export async function consulPreparedQueryRead(connectionId: string, id: string): Promise<import("@/types/consul").ConsulPreparedQuery> {
+ return post("/api/consul/prepared-query/read", { connectionId, id });
+}
+export async function consulPreparedQueryCreate(connectionId: string, input: import("@/types/consul").ConsulPreparedQueryInput): Promise<string> {
+ return post("/api/consul/prepared-query/create", { connectionId, input });
+}
+export async function consulPreparedQueryUpdate(connectionId: string, id: string, input: import("@/types/consul").ConsulPreparedQueryInput): Promise<void> {
+ await post("/api/consul/prepared-query/update", { connectionId, id, input });
+}
+export async function consulPreparedQueryDelete(connectionId: string, id: string): Promise<void> {
+ await post("/api/consul/prepared-query/delete", { connectionId, id });
+}
+export async function consulPreparedQueryExecute(connectionId: string, request: import("@/types/consul").ConsulPreparedQueryExecuteRequest): Promise<import("@/types/consul").ConsulPreparedQueryExecuteResponse> {
+ return post("/api/consul/prepared-query/execute", { connectionId, request });
+}
+export async function consulPreparedQueryExplain(connectionId: string, query: string): Promise<unknown> {
+ return post("/api/consul/prepared-query/explain", { connectionId, id: query });
+}
+export async function consulEventList(connectionId: string, name?: string | null): Promise<import("@/types/consul").ConsulEvent[]> {
+ return post("/api/consul/event/list", { connectionId, name: name ?? null });
+}
+export async function consulEventFire(connectionId: string, request: import("@/types/consul").ConsulEventFireRequest): Promise<import("@/types/consul").ConsulEvent> {
+ return post("/api/consul/event/fire", { connectionId, request });
+}
+export async function consulCoordinateNodes(connectionId: string): Promise<import("@/types/consul").ConsulCoordinate[]> {
+ return post("/api/consul/coordinate/nodes", { connectionId });
+}
+export async function consulOperatorRead(connectionId: string, kind: import("@/types/consul").ConsulOperatorReadKind): Promise<import("@/types/consul").ConsulOperatorDocument> {
+ return post("/api/consul/operator/read", { connectionId, kind });
+}
+export async function consulSnapshotGenerate(connectionId: string): Promise<import("@/types/consul").ConsulSnapshot> {
+ return post("/api/consul/operator/snapshot/generate", { connectionId });
+}
+export async function consulSnapshotRestore(connectionId: string, request: import("@/types/consul").ConsulSnapshotRestoreRequest): Promise<void> {
+ await post("/api/consul/operator/snapshot/restore", { connectionId, request });
+}
+export async function consulAutopilotUpdate(connectionId: string, update: import("@/types/consul").ConsulAutopilotUpdate, confirmation: string): Promise<void> {
+ await post("/api/consul/operator/autopilot/update", { connectionId, update, confirmation });
+}
+export async function consulRaftTransfer(connectionId: string, request: import("@/types/consul").ConsulRaftWriteRequest): Promise<void> {
+ await post("/api/consul/operator/raft/transfer", { connectionId, request });
+}
+export async function consulRaftRemove(connectionId: string, request: import("@/types/consul").ConsulRaftWriteRequest): Promise<void> {
+ await post("/api/consul/operator/raft/remove", { connectionId, request });
+}
+export async function consulKeyringWrite(connectionId: string, request: import("@/types/consul").ConsulKeyringWriteRequest): Promise<void> {
+ await post("/api/consul/operator/keyring/write", { connectionId, request });
+}
+export async function consulLicenseWrite(connectionId: string, request: import("@/types/consul").ConsulLicenseWriteRequest): Promise<void> {
+ await post("/api/consul/operator/license/write", { connectionId, request });
+}
+
+export async function consulStatusLeader(connectionId: string): Promise<string> {
+ return post("/api/consul/status/leader", { connectionId });
+}
+export async function consulStatusPeers(connectionId: string): Promise<string[]> {
+ return post("/api/consul/status/peers", { connectionId });
+}
+export async function consulAgentSelf(connectionId: string): Promise<import("@/types/consul").ConsulAgentIdentity> {
+ return post("/api/consul/agent/self", { connectionId });
+}
+export async function consulAgentMembers(connectionId: string, wan = false, segment?: string | null): Promise<import("@/types/consul").ConsulAgentMember[]> {
+ return post("/api/consul/agent/members", { connectionId, wan, segment: segment ?? null });
+}
+export async function consulAgentMetrics(connectionId: string): Promise<unknown> {
+ return post("/api/consul/agent/metrics", { connectionId });
+}
+export async function consulCatalogDatacenters(connectionId: string): Promise<string[]> {
+ return post("/api/consul/catalog/datacenters", { connectionId });
+}
+export async function consulCatalogNodes(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulCatalogNode[]>> {
+ return post("/api/consul/catalog/nodes", { connectionId, options });
+}
+export async function consulCatalogServices(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<Record<string, string[]>>> {
+ return post("/api/consul/catalog/services", { connectionId, options });
+}
+export async function consulCatalogServiceNodes(connectionId: string, service: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulCatalogServiceNode[]>> {
+ return post("/api/consul/catalog/service-nodes", { connectionId, name: service, options });
+}
+export async function consulCatalogNodeServices(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulNodeServices>> {
+ return post("/api/consul/catalog/node-services", { connectionId, name: node, options });
+}
+export async function consulHealthNode(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return post("/api/consul/health/node", { connectionId, name: node, options });
+}
+export async function consulHealthChecks(connectionId: string, service: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return post("/api/consul/health/checks", { connectionId, name: service, options });
+}
+export async function consulHealthService(connectionId: string, service: string, passing: boolean | null = null, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulServiceInstance[]>> {
+ return post("/api/consul/health/service", { connectionId, name: service, passing, options });
+}
+export async function consulHealthState(connectionId: string, healthState: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return post("/api/consul/health/state", { connectionId, name: healthState, options });
+}
+export async function consulAgentServices(connectionId: string): Promise<Record<string, import("@/types/consul").ConsulAgentService>> {
+ return post("/api/consul/agent/services", { connectionId });
+}
+export async function consulAgentService(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentService> {
+ return post("/api/consul/agent/service", { connectionId, id });
+}
+export async function consulAgentChecks(connectionId: string): Promise<Record<string, import("@/types/consul").ConsulHealthCheck>> {
+ return post("/api/consul/agent/checks", { connectionId });
+}
+export async function consulAgentRegisterService(connectionId: string, registration: import("@/types/consul").ConsulAgentServiceRegistration): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/service/register", { connectionId, registration });
+}
+export async function consulAgentDeregisterService(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/service/deregister", { connectionId, id });
+}
+export async function consulAgentServiceMaintenance(connectionId: string, id: string, enable: boolean, reason?: string | null): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/service/maintenance", { connectionId, id, enable, reason: reason ?? null });
+}
+export async function consulAgentRegisterCheck(connectionId: string, registration: import("@/types/consul").ConsulAgentCheckRegistration): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/check/register", { connectionId, registration });
+}
+export async function consulAgentDeregisterCheck(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/check/deregister", { connectionId, id });
+}
+export async function consulAgentUpdateTtl(connectionId: string, id: string, status: import("@/types/consul").ConsulCheckStatus, output?: string | null): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return post("/api/consul/agent/check/ttl", { connectionId, id, status, output: output ?? null });
+}
+export async function consulSessions(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulSession[]>> {
+ return post("/api/consul/sessions", { connectionId, options });
+}
+export async function consulNodeSessions(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulSession[]>> {
+ return post("/api/consul/sessions/node", { connectionId, name: node, options });
+}
+export async function consulSession(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSession | null> {
+ return post("/api/consul/session", { connectionId, id });
+}
+export async function consulSessionKeys(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSessionKeysResponse> {
+ return post("/api/consul/session/keys", { connectionId, id });
+}
+export async function consulSessionDestroyImpact(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSessionDestroyImpact> {
+ return post("/api/consul/session/destroy-impact", { connectionId, id });
+}
+export async function consulCreateSession(connectionId: string, request: import("@/types/consul").ConsulSessionCreateRequest): Promise<import("@/types/consul").ConsulSession> {
+ return post("/api/consul/session/create", { connectionId, request });
+}
+export async function consulRenewSession(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSession> {
+ return post("/api/consul/session/renew", { connectionId, id });
+}
+export async function consulDestroySession(connectionId: string, request: import("@/types/consul").ConsulSessionDestroyRequest): Promise<boolean> {
+ return post("/api/consul/session/destroy", { connectionId, request });
+}
+export async function consulAcquireLock(connectionId: string, request: import("@/types/consul").ConsulLockRequest): Promise<import("@/types/consul").ConsulLockResponse> {
+ return post("/api/consul/lock/acquire", { connectionId, request });
+}
+export async function consulReleaseLock(connectionId: string, key: string, session: string): Promise<import("@/types/consul").ConsulLockResponse> {
+ return post("/api/consul/lock/release", { connectionId, key, session });
+}
+
+export async function consulAclList(connectionId: string, kind: import("@/types/consul").ConsulAclKind): Promise<import("@/types/consul").ConsulAclList> {
+ return post("/api/consul/acl/list", { connectionId, kind });
+}
+export async function consulAclTokenSelf(connectionId: string): Promise<import("@/types/consul").ConsulAclToken> {
+ return post("/api/consul/acl/token/self", { connectionId });
+}
+export async function consulAclTokenClone(connectionId: string, accessorId: string, description: string): Promise<import("@/types/consul").ConsulAclToken> {
+ return post("/api/consul/acl/token/clone", { connectionId, id: accessorId, description });
+}
+export async function consulAclGet(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclItem> {
+ return post("/api/consul/acl/get", { connectionId, kind, id });
+}
+export async function consulAclApply(connectionId: string, id: string | null, value: import("@/types/consul").ConsulAclWrite): Promise<import("@/types/consul").ConsulAclItem> {
+ return post("/api/consul/acl/apply", { connectionId, id, value });
+}
+export async function consulAclReferences(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclReferences> {
+ return post("/api/consul/acl/references", { connectionId, kind, id });
+}
+export async function consulAclDelete(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclReferences> {
+ return post("/api/consul/acl/delete", { connectionId, kind, id });
+}
+export async function consulEnterpriseList(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind): Promise<import("@/types/consul").ConsulEnterpriseList> {
+ return post("/api/consul/enterprise/list", { connectionId, kind });
+}
+export async function consulEnterpriseGet(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulEnterpriseItem> {
+ return post("/api/consul/enterprise/get", { connectionId, kind, name });
+}
+export async function consulEnterpriseApply(connectionId: string, existingName: string | null, item: import("@/types/consul").ConsulEnterpriseWrite): Promise<import("@/types/consul").ConsulEnterpriseItem> {
+ return post("/api/consul/enterprise/apply", { connectionId, existingName, item });
+}
+export async function consulEnterpriseImpact(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulScopeImpact> {
+ return post("/api/consul/enterprise/impact", { connectionId, kind, name });
+}
+export async function consulEnterpriseDelete(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulScopeImpact> {
+ return post("/api/consul/enterprise/delete", { connectionId, kind, name });
+}
+export async function consulMeshConfigList(connectionId: string, kind: string): Promise<import("@/types/consul").ConsulConfigEntry[]> {
+ return post("/api/consul/mesh/config/list", { connectionId, kind });
+}
+export async function consulMeshConfigGet(connectionId: string, kind: string, name: string): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return post("/api/consul/mesh/config/get", { connectionId, kind, name });
+}
+export async function consulMeshConfigApply(connectionId: string, request: import("@/types/consul").ConsulConfigEntryApply): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return post("/api/consul/mesh/config/apply", { connectionId, request });
+}
+export async function consulMeshConfigDelete(connectionId: string, kind: string, name: string, expectedModifyIndex: number): Promise<boolean> {
+ return post("/api/consul/mesh/config/delete", { connectionId, kind, name, expectedModifyIndex });
+}
+export async function consulMeshIntentionsList(connectionId: string): Promise<import("@/types/consul").ConsulIntention[]> {
+ return post("/api/consul/mesh/intentions/list", { connectionId });
+}
+export async function consulMeshIntentionGet(connectionId: string, id: string): Promise<import("@/types/consul").ConsulIntention> {
+ return post("/api/consul/mesh/intentions/get", { connectionId, id });
+}
+export async function consulMeshIntentionGetExact(connectionId: string, request: import("@/types/consul").ConsulIntentionExactRequest): Promise<import("@/types/consul").ConsulIntention> {
+ return post("/api/consul/mesh/intentions/get-exact", { connectionId, exactRequest: request });
+}
+export async function consulMeshIntentionUpsert(connectionId: string, item: import("@/types/consul").ConsulIntention): Promise<import("@/types/consul").ConsulIntention> {
+ return post("/api/consul/mesh/intentions/upsert", { connectionId, intention: item });
+}
+export async function consulMeshIntentionDelete(connectionId: string, id: string): Promise<boolean> {
+ return post("/api/consul/mesh/intentions/delete", { connectionId, id });
+}
+export async function consulMeshIntentionDeleteExact(connectionId: string, request: import("@/types/consul").ConsulIntentionExactRequest): Promise<boolean> {
+ return post("/api/consul/mesh/intentions/delete-exact", { connectionId, exactRequest: request });
+}
+export async function consulMeshIntentionMatch(connectionId: string, request: import("@/types/consul").ConsulIntentionMatchRequest): Promise<import("@/types/consul").ConsulIntention[]> {
+ return post("/api/consul/mesh/intentions/match", { connectionId, matchRequest: request });
+}
+export async function consulMeshIntentionCheck(connectionId: string, request: import("@/types/consul").ConsulIntentionCheckRequest): Promise<import("@/types/consul").ConsulIntentionCheckResponse> {
+ return post("/api/consul/mesh/intentions/check", { connectionId, checkRequest: request });
+}
+export async function consulMeshDiscoveryChain(connectionId: string, service: string): Promise<import("@/types/consul").ConsulDiscoveryChain> {
+ return post("/api/consul/mesh/discovery-chain", { connectionId, service });
+}
+export async function consulMeshPeeringList(connectionId: string): Promise<import("@/types/consul").ConsulPeering[]> {
+ return post("/api/consul/mesh/peerings/list", { connectionId });
+}
+export async function consulMeshPeeringGet(connectionId: string, name: string): Promise<import("@/types/consul").ConsulPeering> {
+ return post("/api/consul/mesh/peerings/get", { connectionId, name });
+}
+export async function consulMeshPeeringGenerateToken(connectionId: string, request: import("@/types/consul").ConsulPeeringGenerateRequest): Promise<import("@/types/consul").ConsulPeeringToken> {
+ return post("/api/consul/mesh/peerings/generate-token", { connectionId, generateRequest: request });
+}
+export async function consulMeshPeeringEstablish(connectionId: string, request: import("@/types/consul").ConsulPeeringEstablishRequest): Promise<import("@/types/consul").ConsulPeering> {
+ return post("/api/consul/mesh/peerings/establish", { connectionId, establishRequest: request });
+}
+export async function consulMeshPeeringDelete(connectionId: string, name: string): Promise<boolean> {
+ return post("/api/consul/mesh/peerings/delete", { connectionId, name });
+}
+export async function consulMeshExportedServicesList(connectionId: string): Promise<import("@/types/consul").ConsulExportedService[]> {
+ return post("/api/consul/mesh/exported-services/list", { connectionId });
+}
+export async function consulMeshExportedServicesApply(connectionId: string, name: string, expectedModifyIndex: number, raw: Record<string, unknown>): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return post("/api/consul/mesh/exported-services/apply", { connectionId, name, expectedModifyIndex, raw });
+}
+
// ---------------------------------------------------------------------------
// Nacos
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 5a3c90dc95..6788be2534 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -2404,6 +2404,9 @@ export interface KvKeyMetadata {
ephemeralOwner?: number | null;
dataLength?: number | null;
numChildren?: number | null;
+ flags?: KvInt64 | number | null;
+ lockIndex?: KvInt64 | number | null;
+ session?: string | null;
}
export interface KvKeySummary extends KvKeyMetadata {
@@ -2417,6 +2420,7 @@ export interface KvListPrefixResponse {
keys: KvKeySummary[];
continuation?: string | null;
revision?: KvInt64 | number | null;
+ filteredByAcls?: boolean | null;
}
export interface KvListPrefixOptions {
@@ -2460,6 +2464,7 @@ export interface KvPutOptions {
keyBytes?: KvValue | null;
expectedModRevision?: KvInt64 | null;
expectedCreateRevision?: KvInt64 | null;
+ flags?: KvInt64 | null;
}
export interface KvDeleteOptions {
@@ -2804,6 +2809,351 @@ export async function zookeeperDelete(connectionId: string, key: string): Promis
return invoke("zookeeper_delete", { connectionId, key });
}
+// --- Consul KV ---
+export async function consulCapabilities(connectionId: string): Promise<import("@/types/consul").ConsulCapabilities> {
+ return invoke("consul_capabilities", { connectionId });
+}
+
+export async function consulTxn(connectionId: string, request: import("@/types/consul").ConsulTxnRequest): Promise<import("@/types/consul").ConsulTxnResult> {
+ return invoke("consul_txn", { connectionId, request });
+}
+
+export async function consulRenameKey(connectionId: string, source: string, target: string, expectedModifyIndex: KvInt64, copy = false): Promise<import("@/types/consul").ConsulTxnResult> {
+ return invoke("consul_rename_key", { connectionId, source, target, expectedModifyIndex, copy });
+}
+
+export async function consulBlockingQuery(connectionId: string, request: import("@/types/consul").ConsulBlockingRequest): Promise<import("@/types/consul").ConsulBlockingResponse> {
+ return invoke("consul_blocking_query", { connectionId, request });
+}
+
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogServices" } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<Record<string, string[]>>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogNodes" } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulCatalogNode[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogServiceNodes"; service: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulCatalogServiceNode[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "catalogNodeServices"; node: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulNodeServices>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthNode"; node: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthServiceChecks"; service: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(
+ connectionId: string,
+ request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthServiceInstances"; service: string; passing: boolean | null } },
+): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulServiceInstance[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest & { target: { kind: "healthState"; state: string } }): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulHealthCheck[]>>;
+export function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulDomainWatchItems>>;
+export async function consulDomainWatch(connectionId: string, request: import("@/types/consul").ConsulDomainWatchRequest): Promise<import("@/types/consul").ConsulDomainWatchResponse<import("@/types/consul").ConsulDomainWatchItems>> {
+ return invoke("consul_domain_watch", { connectionId, request });
+}
+
+export async function consulCancelBlocking(connectionId: string, scope: import("@/types/consul").ConsulScope, generation: number, operationId: string): Promise<boolean> {
+ return invoke("consul_cancel_blocking", { connectionId, scope, generation, operationId });
+}
+
+export async function consulWatchStart(connectionId: string, request: import("@/types/consul").ConsulBlockingRequest): Promise<string> {
+ return invoke("consul_watch_start", { connectionId, request });
+}
+
+export async function consulListRecursive(connectionId: string, prefix: string, maxEntries = 10_000, maxValueBytes = 32 * 1024 * 1024): Promise<import("@/types/consul").ConsulRecursiveListResponse> {
+ return invoke("consul_list_recursive", { connectionId, prefix, maxEntries, maxValueBytes });
+}
+
+export async function consulSearch(connectionId: string, request: import("@/types/consul").ConsulSearchRequest): Promise<import("@/types/consul").ConsulSearchResponse> {
+ return invoke("consul_search", { connectionId, request });
+}
+
+export async function consulSearchProgress(connectionId: string, requestId: string, scope: import("@/types/consul").ConsulScope, generation: number): Promise<import("@/types/consul").ConsulSearchProgress> {
+ return invoke("consul_search_progress", { connectionId, requestId, scope, generation });
+}
+
+export async function consulCancelSearch(connectionId: string, requestId: string, scope: import("@/types/consul").ConsulScope, generation: number): Promise<boolean> {
+ return invoke("consul_cancel_search", { connectionId, requestId, scope, generation });
+}
+
+export async function consulExportBundle(connectionId: string, request: import("@/types/consul").ConsulExportRequest): Promise<import("@/types/consul").ConsulKvBundle> {
+ return invoke("consul_export_bundle", { connectionId, request });
+}
+
+export async function consulImportPreview(connectionId: string, request: import("@/types/consul").ConsulImportRequest): Promise<import("@/types/consul").ConsulImportPreview> {
+ return invoke("consul_import_preview", { connectionId, request });
+}
+
+export async function consulImportExecute(connectionId: string, request: import("@/types/consul").ConsulImportRequest): Promise<import("@/types/consul").ConsulImportReport> {
+ return invoke("consul_import_execute", { connectionId, request });
+}
+
+export async function consulDeletePrefixPreview(connectionId: string, prefix: string): Promise<import("@/types/consul").ConsulDeletePrefixPreview> {
+ return invoke("consul_delete_prefix_preview", { connectionId, prefix });
+}
+
+export async function consulDeletePrefixExecute(connectionId: string, request: import("@/types/consul").ConsulDeletePrefixRequest): Promise<import("@/types/consul").ConsulDeletePrefixReport> {
+ return invoke("consul_delete_prefix_execute", { connectionId, request });
+}
+
+export async function consulListPrefix(connectionId: string, prefix: string, limit: number, continuation?: string | null): Promise<KvListPrefixResponse> {
+ return invoke("consul_list_prefix", { connectionId, prefix, limit, continuation: continuation ?? null });
+}
+
+export async function consulGet(connectionId: string, key: string): Promise<KvGetResponse> {
+ return invoke("consul_get", { connectionId, key });
+}
+
+export async function consulPut(connectionId: string, key: string, value: KvValue, options?: KvPutOptions | null): Promise<KvPutResponse> {
+ return invoke("consul_put", { connectionId, key, value, options: options ?? null });
+}
+
+export async function consulDelete(connectionId: string, key: string, options?: KvDeleteOptions | null): Promise<KvDeleteResponse> {
+ return invoke("consul_delete", { connectionId, key, options: options ?? null });
+}
+
+export async function consulPreparedQueryList(connectionId: string): Promise<import("@/types/consul").ConsulPreparedQuery[]> {
+ return invoke("consul_prepared_query_list", { connectionId });
+}
+export async function consulPreparedQueryRead(connectionId: string, id: string): Promise<import("@/types/consul").ConsulPreparedQuery> {
+ return invoke("consul_prepared_query_read", { connectionId, id });
+}
+export async function consulPreparedQueryCreate(connectionId: string, input: import("@/types/consul").ConsulPreparedQueryInput): Promise<string> {
+ return invoke("consul_prepared_query_create", { connectionId, input });
+}
+export async function consulPreparedQueryUpdate(connectionId: string, id: string, input: import("@/types/consul").ConsulPreparedQueryInput): Promise<void> {
+ return invoke("consul_prepared_query_update", { connectionId, id, input });
+}
+export async function consulPreparedQueryDelete(connectionId: string, id: string): Promise<void> {
+ return invoke("consul_prepared_query_delete", { connectionId, id });
+}
+export async function consulPreparedQueryExecute(connectionId: string, request: import("@/types/consul").ConsulPreparedQueryExecuteRequest): Promise<import("@/types/consul").ConsulPreparedQueryExecuteResponse> {
+ return invoke("consul_prepared_query_execute", { connectionId, request });
+}
+export async function consulPreparedQueryExplain(connectionId: string, query: string): Promise<unknown> {
+ return invoke("consul_prepared_query_explain", { connectionId, query });
+}
+export async function consulEventList(connectionId: string, name?: string | null): Promise<import("@/types/consul").ConsulEvent[]> {
+ return invoke("consul_event_list", { connectionId, name: name ?? null });
+}
+export async function consulEventFire(connectionId: string, request: import("@/types/consul").ConsulEventFireRequest): Promise<import("@/types/consul").ConsulEvent> {
+ return invoke("consul_event_fire", { connectionId, request });
+}
+export async function consulCoordinateNodes(connectionId: string): Promise<import("@/types/consul").ConsulCoordinate[]> {
+ return invoke("consul_coordinate_nodes", { connectionId });
+}
+export async function consulOperatorRead(connectionId: string, kind: import("@/types/consul").ConsulOperatorReadKind): Promise<import("@/types/consul").ConsulOperatorDocument> {
+ return invoke("consul_operator_read", { connectionId, kind });
+}
+export async function consulSnapshotGenerate(connectionId: string): Promise<import("@/types/consul").ConsulSnapshot> {
+ return invoke("consul_snapshot_generate", { connectionId });
+}
+export async function consulSnapshotRestore(connectionId: string, request: import("@/types/consul").ConsulSnapshotRestoreRequest): Promise<void> {
+ return invoke("consul_snapshot_restore", { connectionId, request });
+}
+export async function consulAutopilotUpdate(connectionId: string, update: import("@/types/consul").ConsulAutopilotUpdate, confirmation: string): Promise<void> {
+ return invoke("consul_autopilot_update", { connectionId, update, confirmation });
+}
+export async function consulRaftTransfer(connectionId: string, request: import("@/types/consul").ConsulRaftWriteRequest): Promise<void> {
+ return invoke("consul_raft_transfer", { connectionId, request });
+}
+export async function consulRaftRemove(connectionId: string, request: import("@/types/consul").ConsulRaftWriteRequest): Promise<void> {
+ return invoke("consul_raft_remove", { connectionId, request });
+}
+export async function consulKeyringWrite(connectionId: string, request: import("@/types/consul").ConsulKeyringWriteRequest): Promise<void> {
+ return invoke("consul_keyring_write", { connectionId, request });
+}
+export async function consulLicenseWrite(connectionId: string, request: import("@/types/consul").ConsulLicenseWriteRequest): Promise<void> {
+ return invoke("consul_license_write", { connectionId, request });
+}
+
+export async function consulStatusLeader(connectionId: string): Promise<string> {
+ return invoke("consul_status_leader", { connectionId });
+}
+export async function consulStatusPeers(connectionId: string): Promise<string[]> {
+ return invoke("consul_status_peers", { connectionId });
+}
+export async function consulAgentSelf(connectionId: string): Promise<import("@/types/consul").ConsulAgentIdentity> {
+ return invoke("consul_agent_self", { connectionId });
+}
+export async function consulAgentMembers(connectionId: string, wan = false, segment?: string | null): Promise<import("@/types/consul").ConsulAgentMember[]> {
+ return invoke("consul_agent_members", { connectionId, wan, segment: segment ?? null });
+}
+export async function consulAgentMetrics(connectionId: string): Promise<unknown> {
+ return invoke("consul_agent_metrics", { connectionId });
+}
+export async function consulCatalogDatacenters(connectionId: string): Promise<string[]> {
+ return invoke("consul_catalog_datacenters", { connectionId });
+}
+export async function consulCatalogNodes(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulCatalogNode[]>> {
+ return invoke("consul_catalog_nodes", { connectionId, options });
+}
+export async function consulCatalogServices(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<Record<string, string[]>>> {
+ return invoke("consul_catalog_services", { connectionId, options });
+}
+export async function consulCatalogServiceNodes(connectionId: string, service: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulCatalogServiceNode[]>> {
+ return invoke("consul_catalog_service_nodes", { connectionId, service, options });
+}
+export async function consulCatalogNodeServices(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulNodeServices>> {
+ return invoke("consul_catalog_node_services", { connectionId, node, options });
+}
+export async function consulHealthNode(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return invoke("consul_health_node", { connectionId, node, options });
+}
+export async function consulHealthChecks(connectionId: string, service: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return invoke("consul_health_checks", { connectionId, service, options });
+}
+export async function consulHealthService(connectionId: string, service: string, passing: boolean | null = null, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulServiceInstance[]>> {
+ return invoke("consul_health_service", { connectionId, service, passing, options });
+}
+export async function consulHealthState(connectionId: string, healthState: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulHealthCheck[]>> {
+ return invoke("consul_health_state", { connectionId, healthState, options });
+}
+export async function consulAgentServices(connectionId: string): Promise<Record<string, import("@/types/consul").ConsulAgentService>> {
+ return invoke("consul_agent_services", { connectionId });
+}
+export async function consulAgentService(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentService> {
+ return invoke("consul_agent_service", { connectionId, id });
+}
+export async function consulAgentChecks(connectionId: string): Promise<Record<string, import("@/types/consul").ConsulHealthCheck>> {
+ return invoke("consul_agent_checks", { connectionId });
+}
+export async function consulAgentRegisterService(connectionId: string, registration: import("@/types/consul").ConsulAgentServiceRegistration): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_register_service", { connectionId, registration });
+}
+export async function consulAgentDeregisterService(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_deregister_service", { connectionId, id });
+}
+export async function consulAgentServiceMaintenance(connectionId: string, id: string, enable: boolean, reason?: string | null): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_service_maintenance", { connectionId, id, enable, reason: reason ?? null });
+}
+export async function consulAgentRegisterCheck(connectionId: string, registration: import("@/types/consul").ConsulAgentCheckRegistration): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_register_check", { connectionId, registration });
+}
+export async function consulAgentDeregisterCheck(connectionId: string, id: string): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_deregister_check", { connectionId, id });
+}
+export async function consulAgentUpdateTtl(connectionId: string, id: string, status: import("@/types/consul").ConsulCheckStatus, output?: string | null): Promise<import("@/types/consul").ConsulAgentWriteResult> {
+ return invoke("consul_agent_update_ttl", { connectionId, id, status, output: output ?? null });
+}
+export async function consulSessions(connectionId: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulSession[]>> {
+ return invoke("consul_sessions", { connectionId, options });
+}
+export async function consulNodeSessions(connectionId: string, node: string, options: import("@/types/consul").ConsulReadOptions = {}): Promise<import("@/types/consul").ConsulListResponse<import("@/types/consul").ConsulSession[]>> {
+ return invoke("consul_node_sessions", { connectionId, node, options });
+}
+export async function consulSession(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSession | null> {
+ return invoke("consul_session", { connectionId, id });
+}
+export async function consulSessionKeys(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSessionKeysResponse> {
+ return invoke("consul_session_keys", { connectionId, id });
+}
+export async function consulSessionDestroyImpact(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSessionDestroyImpact> {
+ return invoke("consul_session_destroy_impact", { connectionId, id });
+}
+export async function consulCreateSession(connectionId: string, request: import("@/types/consul").ConsulSessionCreateRequest): Promise<import("@/types/consul").ConsulSession> {
+ return invoke("consul_create_session", { connectionId, request });
+}
+export async function consulRenewSession(connectionId: string, id: string): Promise<import("@/types/consul").ConsulSession> {
+ return invoke("consul_renew_session", { connectionId, id });
+}
+export async function consulDestroySession(connectionId: string, request: import("@/types/consul").ConsulSessionDestroyRequest): Promise<boolean> {
+ return invoke("consul_destroy_session", { connectionId, request });
+}
+export async function consulAcquireLock(connectionId: string, request: import("@/types/consul").ConsulLockRequest): Promise<import("@/types/consul").ConsulLockResponse> {
+ return invoke("consul_acquire_lock", { connectionId, request });
+}
+export async function consulReleaseLock(connectionId: string, key: string, session: string): Promise<import("@/types/consul").ConsulLockResponse> {
+ return invoke("consul_release_lock", { connectionId, key, session });
+}
+
+export async function consulAclList(connectionId: string, kind: import("@/types/consul").ConsulAclKind): Promise<import("@/types/consul").ConsulAclList> {
+ return invoke("consul_acl_list", { connectionId, kind });
+}
+export async function consulAclTokenSelf(connectionId: string): Promise<import("@/types/consul").ConsulAclToken> {
+ return invoke("consul_acl_token_self", { connectionId });
+}
+export async function consulAclTokenClone(connectionId: string, accessorId: string, description: string): Promise<import("@/types/consul").ConsulAclToken> {
+ return invoke("consul_acl_token_clone", { connectionId, accessorId, request: { Description: description } });
+}
+export async function consulAclGet(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclItem> {
+ return invoke("consul_acl_get", { connectionId, kind, id });
+}
+export async function consulAclApply(connectionId: string, id: string | null, value: import("@/types/consul").ConsulAclWrite): Promise<import("@/types/consul").ConsulAclItem> {
+ return invoke("consul_acl_apply", { connectionId, id, value });
+}
+export async function consulAclReferences(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclReferences> {
+ return invoke("consul_acl_references", { connectionId, kind, id });
+}
+export async function consulAclDelete(connectionId: string, kind: import("@/types/consul").ConsulAclKind, id: string): Promise<import("@/types/consul").ConsulAclReferences> {
+ return invoke("consul_acl_delete", { connectionId, kind, id });
+}
+export async function consulEnterpriseList(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind): Promise<import("@/types/consul").ConsulEnterpriseList> {
+ return invoke("consul_enterprise_list", { connectionId, kind });
+}
+export async function consulEnterpriseGet(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulEnterpriseItem> {
+ return invoke("consul_enterprise_get", { connectionId, kind, name });
+}
+export async function consulEnterpriseApply(connectionId: string, existingName: string | null, item: import("@/types/consul").ConsulEnterpriseWrite): Promise<import("@/types/consul").ConsulEnterpriseItem> {
+ return invoke("consul_enterprise_apply", { connectionId, existingName, item });
+}
+export async function consulEnterpriseImpact(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulScopeImpact> {
+ return invoke("consul_enterprise_impact", { connectionId, kind, name });
+}
+export async function consulEnterpriseDelete(connectionId: string, kind: import("@/types/consul").ConsulEnterpriseKind, name: string): Promise<import("@/types/consul").ConsulScopeImpact> {
+ return invoke("consul_enterprise_delete", { connectionId, kind, name });
+}
+export async function consulMeshConfigList(connectionId: string, kind: string): Promise<import("@/types/consul").ConsulConfigEntry[]> {
+ return invoke("consul_mesh_config_list", { connectionId, kind });
+}
+export async function consulMeshConfigGet(connectionId: string, kind: string, name: string): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return invoke("consul_mesh_config_get", { connectionId, kind, name });
+}
+export async function consulMeshConfigApply(connectionId: string, request: import("@/types/consul").ConsulConfigEntryApply): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return invoke("consul_mesh_config_apply", { connectionId, request });
+}
+export async function consulMeshConfigDelete(connectionId: string, kind: string, name: string, expectedModifyIndex: number): Promise<boolean> {
+ return invoke("consul_mesh_config_delete", { connectionId, kind, name, expectedModifyIndex });
+}
+export async function consulMeshIntentionsList(connectionId: string): Promise<import("@/types/consul").ConsulIntention[]> {
+ return invoke("consul_mesh_intentions_list", { connectionId });
+}
+export async function consulMeshIntentionGet(connectionId: string, id: string): Promise<import("@/types/consul").ConsulIntention> {
+ return invoke("consul_mesh_intention_get", { connectionId, id });
+}
+export async function consulMeshIntentionGetExact(connectionId: string, request: import("@/types/consul").ConsulIntentionExactRequest): Promise<import("@/types/consul").ConsulIntention> {
+ return invoke("consul_mesh_intention_get_exact", { connectionId, request });
+}
+export async function consulMeshIntentionUpsert(connectionId: string, item: import("@/types/consul").ConsulIntention): Promise<import("@/types/consul").ConsulIntention> {
+ return invoke("consul_mesh_intention_upsert", { connectionId, item });
+}
+export async function consulMeshIntentionDelete(connectionId: string, id: string): Promise<boolean> {
+ return invoke("consul_mesh_intention_delete", { connectionId, id });
+}
+export async function consulMeshIntentionDeleteExact(connectionId: string, request: import("@/types/consul").ConsulIntentionExactRequest): Promise<boolean> {
+ return invoke("consul_mesh_intention_delete_exact", { connectionId, request });
+}
+export async function consulMeshIntentionMatch(connectionId: string, request: import("@/types/consul").ConsulIntentionMatchRequest): Promise<import("@/types/consul").ConsulIntention[]> {
+ return invoke("consul_mesh_intention_match", { connectionId, request });
+}
+export async function consulMeshIntentionCheck(connectionId: string, request: import("@/types/consul").ConsulIntentionCheckRequest): Promise<import("@/types/consul").ConsulIntentionCheckResponse> {
+ return invoke("consul_mesh_intention_check", { connectionId, request });
+}
+export async function consulMeshDiscoveryChain(connectionId: string, service: string): Promise<import("@/types/consul").ConsulDiscoveryChain> {
+ return invoke("consul_mesh_discovery_chain", { connectionId, service });
+}
+export async function consulMeshPeeringList(connectionId: string): Promise<import("@/types/consul").ConsulPeering[]> {
+ return invoke("consul_mesh_peering_list", { connectionId });
+}
+export async function consulMeshPeeringGet(connectionId: string, name: string): Promise<import("@/types/consul").ConsulPeering> {
+ return invoke("consul_mesh_peering_get", { connectionId, name });
+}
+export async function consulMeshPeeringGenerateToken(connectionId: string, request: import("@/types/consul").ConsulPeeringGenerateRequest): Promise<import("@/types/consul").ConsulPeeringToken> {
+ return invoke("consul_mesh_peering_generate_token", { connectionId, request });
+}
+export async function consulMeshPeeringEstablish(connectionId: string, request: import("@/types/consul").ConsulPeeringEstablishRequest): Promise<import("@/types/consul").ConsulPeering> {
+ return invoke("consul_mesh_peering_establish", { connectionId, request });
+}
+export async function consulMeshPeeringDelete(connectionId: string, name: string): Promise<boolean> {
+ return invoke("consul_mesh_peering_delete", { connectionId, name });
+}
+export async function consulMeshExportedServicesList(connectionId: string): Promise<import("@/types/consul").ConsulExportedService[]> {
+ return invoke("consul_mesh_exported_services_list", { connectionId });
+}
+export async function consulMeshExportedServicesApply(connectionId: string, name: string, expectedModifyIndex: number, raw: Record<string, unknown>): Promise<import("@/types/consul").ConsulConfigEntry> {
+ return invoke("consul_mesh_exported_services_apply", { connectionId, name, expectedModifyIndex, raw });
+}
+
// --- HBase ---
export async function hbaseGetTableSchema(connectionId: string, namespace: string, table: string): Promise<import("@/types/hbase").HBaseTableSchema> {
return invoke("hbase_get_table_schema", { connectionId, namespace, table });
diff --git a/apps/desktop/src/lib/connection/connectionOpenTarget.ts b/apps/desktop/src/lib/connection/connectionOpenTarget.ts
index b4ef520af1..930f604456 100644
--- a/apps/desktop/src/lib/connection/connectionOpenTarget.ts
+++ b/apps/desktop/src/lib/connection/connectionOpenTarget.ts
@@ -1,7 +1,7 @@
import type { ConnectionConfig } from "@/types/database";
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
-export type QuickConnectionOpenTarget = { kind: "mq-admin" } | { kind: "nacos-admin" } | { kind: "etcd" } | { kind: "zookeeper" } | { kind: "query"; database: string };
+export type QuickConnectionOpenTarget = { kind: "mq-admin" } | { kind: "nacos-admin" } | { kind: "etcd" } | { kind: "zookeeper" } | { kind: "consul" } | { kind: "query"; database: string };
export function quickConnectionOpenTarget(connection: Pick<ConnectionConfig, "db_type" | "database">, databaseOptions: string[] = []): QuickConnectionOpenTarget {
if (connection.db_type === "mq") {
@@ -16,5 +16,8 @@ export function quickConnectionOpenTarget(connection: Pick<ConnectionConfig, "db
if (connection.db_type === "zookeeper") {
return { kind: "zookeeper" };
}
+ if (connection.db_type === "consul") {
+ return { kind: "consul" };
+ }
return { kind: "query", database: resolveDefaultDatabase(connection, databaseOptions) };
}
diff --git a/apps/desktop/src/lib/connection/connectionPresentation.ts b/apps/desktop/src/lib/connection/connectionPresentation.ts
index 17aec1938a..813da48e9a 100644
--- a/apps/desktop/src/lib/connection/connectionPresentation.ts
+++ b/apps/desktop/src/lib/connection/connectionPresentation.ts
@@ -136,6 +136,7 @@ export function connectionDisplayUrlScheme(connection: Pick<ConnectionConfig, "d
case "rqlite":
case "turso":
case "mq":
+ case "consul":
return connection.ssl ? "https" : "http";
case "cloudflare-d1":
return "https";
@@ -171,6 +172,9 @@ export function connectionUrlPlaceholder(dbType: DatabaseType): string {
case "zookeeper":
return "zookeeper://host:2181";
+ case "consul":
+ return "http://host:8500";
+
case "sqlite":
return "sqlite:///absolute/path/to/database.db";
diff --git a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
index a1dcabc896..073bb1b6e1 100644
--- a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
+++ b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
@@ -5,7 +5,7 @@ const DRAFT_VISIBLE_DATABASES_PREFIX = "__visible_draft_";
// Turso and Cloudflare D1 target one fixed SQLite-compatible `main` namespace;
// non-database services expose their own root objects rather than database namespaces.
-const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos"]);
+const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul"]);
type VisibleDatabaseConnectionFields = Pick<
ConnectionConfig,
diff --git a/apps/desktop/src/lib/consul/__tests__/agentTarget.spec.ts b/apps/desktop/src/lib/consul/__tests__/agentTarget.spec.ts
new file mode 100644
index 0000000000..54f1a78ee5
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/agentTarget.spec.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { consulAgentAddressesMatch, consulAgentWriteTargetSafe } from "../agentTarget";
+
+describe("Consul Agent target safety", () => {
+ it("treats loopback aliases as equivalent", () => {
+ expect(consulAgentAddressesMatch("localhost", "127.0.0.1")).toBe(true);
+ expect(consulAgentAddressesMatch("::1", "localhost")).toBe(true);
+ });
+
+ it("rejects DNS and Transport targets in the UI gate", () => {
+ const target = { agentTarget: { node: "node-1", address: "127.0.0.1" } };
+ expect(consulAgentWriteTargetSafe({ external_config: { ...target, serverAddr: "https://consul.example" } }, "node-1")).toBe(false);
+ expect(consulAgentWriteTargetSafe({ transport_layers: [{}], external_config: { ...target, serverAddr: "http://127.0.0.1:8500" } }, "node-1")).toBe(false);
+ expect(consulAgentWriteTargetSafe({ external_config: { ...target, serverAddr: "http://localhost:8500" } }, "node-1")).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/consulPolicy.spec.ts b/apps/desktop/src/lib/consul/__tests__/consulPolicy.spec.ts
new file mode 100644
index 0000000000..fe447456f9
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/consulPolicy.spec.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { capabilityVisible, capabilityWritable, requireConfirmation, scopeHasWildcard } from "@/lib/consul/consulPolicy";
+import { nextWatchIndex } from "@/lib/consul/watchState";
+
+describe("Consul domain policies", () => {
+ it("keeps forbidden separate from unsupported", () => {
+ expect(capabilityVisible("forbidden")).toBe(true);
+ expect(capabilityVisible("unsupported")).toBe(false);
+ expect(capabilityWritable("supported", false)).toBe(true);
+ expect(capabilityWritable("supported", true)).toBe(false);
+ });
+
+ it("requires explicit wildcard scope and exact confirmations", () => {
+ expect(scopeHasWildcard({ datacenter: "dc1", namespace: "*", partition: "default" })).toBe(true);
+ expect(scopeHasWildcard({ datacenter: "dc1", namespace: "team", partition: "default" })).toBe(false);
+ expect(requireConfirmation("DELETE team", "DELETE team")).toBe(true);
+ expect(requireConfirmation("DELETE team", "delete team")).toBe(false);
+ });
+
+ it("resets blocking indexes after zero or rollback", () => {
+ expect(nextWatchIndex("50", "0")).toEqual({ index: "1", reset: true });
+ expect(nextWatchIndex("50", "49")).toEqual({ index: "1", reset: true });
+ expect(nextWatchIndex("50", "51")).toEqual({ index: "51", reset: false });
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/meshVisibility.spec.ts b/apps/desktop/src/lib/consul/__tests__/meshVisibility.spec.ts
new file mode 100644
index 0000000000..d09712c4c7
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/meshVisibility.spec.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+import { consulMeshWorkspaceVisible } from "@/lib/consul/meshVisibility";
+
+describe("consulMeshWorkspaceVisible", () => {
+ it("keeps the advanced workspace hidden unless explicitly enabled", () => {
+ expect(consulMeshWorkspaceVisible({})).toBe(false);
+ expect(consulMeshWorkspaceVisible(undefined)).toBe(false);
+ expect(consulMeshWorkspaceVisible({ consulMeshVisible: false })).toBe(false);
+ });
+
+ it("shows the workspace when the connection explicitly enables it", () => {
+ expect(consulMeshWorkspaceVisible({ consulMeshVisible: true })).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/pagination.spec.ts b/apps/desktop/src/lib/consul/__tests__/pagination.spec.ts
new file mode 100644
index 0000000000..3989e0a014
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/pagination.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { clampConsulPage, consulPageCount, paginateConsulItems } from "@/lib/consul/pagination";
+
+describe("Consul list pagination", () => {
+ it("splits large result sets without dropping the final partial page", () => {
+ const items = Array.from({ length: 123 }, (_, index) => index + 1);
+ expect(consulPageCount(items.length, 50)).toBe(3);
+ expect(paginateConsulItems(items, 1, 50)).toEqual(items.slice(0, 50));
+ expect(paginateConsulItems(items, 3, 50)).toEqual(items.slice(100));
+ });
+
+ it("clamps stale pages after filtering or deletion", () => {
+ expect(clampConsulPage(9, 51, 50)).toBe(2);
+ expect(clampConsulPage(0, 51, 50)).toBe(1);
+ expect(clampConsulPage(Number.NaN, 0, 50)).toBe(1);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/sessionModel.spec.ts b/apps/desktop/src/lib/consul/__tests__/sessionModel.spec.ts
new file mode 100644
index 0000000000..0c6227e8a1
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/sessionModel.spec.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { normalizeConsulSession } from "../sessionModel";
+
+describe("Consul Session transport normalization", () => {
+ it("accepts the legacy Checks response during a desktop backend hot restart", () => {
+ const session = normalizeConsulSession({
+ ID: "session-1",
+ Name: "demo",
+ Node: "node-1",
+ LockDelay: 15_000_000_000,
+ Behavior: "release",
+ TTL: "",
+ Checks: ["serfHealth"],
+ CreateIndex: 12,
+ });
+
+ expect(session.NodeChecks).toEqual(["serfHealth"]);
+ expect(session.ServiceChecks).toEqual([]);
+ expect(session.ModifyIndex).toBe(12);
+ });
+
+ it("normalizes nullable Consul 2.0 check collections", () => {
+ const session = normalizeConsulSession({
+ ID: "session-2",
+ NodeChecks: undefined,
+ ServiceChecks: null as never,
+ });
+
+ expect(session.NodeChecks).toEqual([]);
+ expect(session.ServiceChecks).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/sessionRenew.spec.ts b/apps/desktop/src/lib/consul/__tests__/sessionRenew.spec.ts
new file mode 100644
index 0000000000..ee373c6d50
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/sessionRenew.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { consulSessionRenewDelayMs, parseConsulDurationMs } from "../sessionRenew";
+
+describe("Consul Session renew timing", () => {
+ it("parses compound Consul durations", () => {
+ expect(parseConsulDurationMs("1m30s")).toBe(90_000);
+ expect(parseConsulDurationMs("250ms")).toBe(250);
+ expect(parseConsulDurationMs("0s")).toBe(0);
+ expect(parseConsulDurationMs("not-a-duration")).toBeNull();
+ });
+
+ it("renews halfway through the TTL within safe timer bounds", () => {
+ expect(consulSessionRenewDelayMs("10s")).toBe(5_000);
+ expect(consulSessionRenewDelayMs("2m")).toBe(30_000);
+ expect(consulSessionRenewDelayMs("250ms")).toBe(1_000);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/__tests__/watchState.spec.ts b/apps/desktop/src/lib/consul/__tests__/watchState.spec.ts
new file mode 100644
index 0000000000..e42808ca28
--- /dev/null
+++ b/apps/desktop/src/lib/consul/__tests__/watchState.spec.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { isCurrentWatchEvent, nextWatchIndex } from "../watchState";
+import type { ConsulWatchEvent } from "@/types/consul";
+
+const event: ConsulWatchEvent = {
+ connectionId: "connection-a",
+ operationId: "watch-a",
+ generation: 7,
+ result: null,
+ error: null,
+};
+
+describe("Consul watch lifecycle", () => {
+ it("resets zero and regressed indexes to the minimum blocking index", () => {
+ expect(nextWatchIndex("15", "0")).toEqual({ index: "1", reset: true });
+ expect(nextWatchIndex("15", "14")).toEqual({ index: "1", reset: true });
+ expect(nextWatchIndex("15", "16")).toEqual({ index: "16", reset: false });
+ });
+
+ it("rejects events from stale connections, operations, and scope generations", () => {
+ expect(isCurrentWatchEvent({ connectionId: "connection-a", operationId: "watch-a", generation: 7 }, event)).toBe(true);
+ expect(isCurrentWatchEvent({ connectionId: "connection-b", operationId: "watch-a", generation: 7 }, event)).toBe(false);
+ expect(isCurrentWatchEvent({ connectionId: "connection-a", operationId: "watch-b", generation: 7 }, event)).toBe(false);
+ expect(isCurrentWatchEvent({ connectionId: "connection-a", operationId: "watch-a", generation: 8 }, event)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/consul/agentTarget.ts b/apps/desktop/src/lib/consul/agentTarget.ts
new file mode 100644
index 0000000000..1feb5dc058
--- /dev/null
+++ b/apps/desktop/src/lib/consul/agentTarget.ts
@@ -0,0 +1,53 @@
+type AgentTargetConnection = {
+ read_only?: boolean;
+ transport_layers?: Array<{ enabled?: boolean }>;
+ external_config?: unknown;
+};
+
+function normalizeAddress(value: string): string {
+ return value
+ .trim()
+ .replace(/^\[|\]$/g, "")
+ .toLowerCase();
+}
+
+function isIpv4(value: string): boolean {
+ const parts = value.split(".");
+ return parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
+}
+
+function isIpv6(value: string): boolean {
+ return value.includes(":") && /^[0-9a-f:]+$/i.test(value);
+}
+
+function isLoopback(value: string): boolean {
+ const address = normalizeAddress(value);
+ return address === "localhost" || address === "::1" || (isIpv4(address) && address.startsWith("127."));
+}
+
+export function consulAgentAddressesMatch(left: string, right: string): boolean {
+ const a = normalizeAddress(left);
+ const b = normalizeAddress(right);
+ return a === b || (a === "localhost" && isLoopback(b)) || (b === "localhost" && isLoopback(a));
+}
+
+export function consulAgentWriteTargetSafe(connection: AgentTargetConnection | undefined, identityNode: string | undefined): boolean {
+ if (!connection || connection.read_only || connection.transport_layers?.some((layer) => layer.enabled !== false)) return false;
+ const external = connection.external_config;
+ if (!external || typeof external !== "object" || Array.isArray(external)) return false;
+ const config = external as Record<string, unknown>;
+ const rawTarget = config.agentTarget || config.agent_target;
+ if (!rawTarget || typeof rawTarget !== "object" || Array.isArray(rawTarget)) return false;
+ const target = rawTarget as Record<string, unknown>;
+ const node = String(target.node || "").trim();
+ const address = String(target.address || "").trim();
+ if (!node || !address || node !== identityNode) return false;
+ const serverAddress = String(config.serverAddr || config.server_addr || "").trim();
+ try {
+ const host = normalizeAddress(new URL(serverAddress).hostname);
+ if (host !== "localhost" && !isIpv4(host) && !isIpv6(host)) return false;
+ return consulAgentAddressesMatch(host, address);
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/src/lib/consul/consulPolicy.ts b/apps/desktop/src/lib/consul/consulPolicy.ts
new file mode 100644
index 0000000000..e172781af1
--- /dev/null
+++ b/apps/desktop/src/lib/consul/consulPolicy.ts
@@ -0,0 +1,22 @@
+import type { ConsulCapabilities, ConsulCapabilityStatus, ConsulScope } from "@/types/consul";
+
+export function capabilityVisible(status: ConsulCapabilityStatus): boolean {
+ return status !== "unsupported" && status !== "disabled";
+}
+
+export function capabilityWritable(status: ConsulCapabilityStatus, readonly: boolean): boolean {
+ return !readonly && status === "supported";
+}
+
+export function scopeHasWildcard(scope: ConsulScope): boolean {
+ return scope.datacenter === "*" || scope.namespace === "*" || scope.partition === "*";
+}
+
+export function capabilityStatus(capabilities: ConsulCapabilities | null, key: keyof ConsulCapabilities): ConsulCapabilityStatus {
+ const value = capabilities?.[key];
+ return value === "supported" || value === "unsupported" || value === "disabled" || value === "forbidden" ? value : "unknown";
+}
+
+export function requireConfirmation(expected: string, actual: string): boolean {
+ return expected.length > 0 && actual.trim() === expected;
+}
diff --git a/apps/desktop/src/lib/consul/meshVisibility.ts b/apps/desktop/src/lib/consul/meshVisibility.ts
new file mode 100644
index 0000000000..603d170b64
--- /dev/null
+++ b/apps/desktop/src/lib/consul/meshVisibility.ts
@@ -0,0 +1,8 @@
+function externalConfigRecord(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
+}
+
+export function consulMeshWorkspaceVisible(externalConfig: unknown): boolean {
+ const config = externalConfigRecord(externalConfig);
+ return config.consulMeshVisible === true;
+}
diff --git a/apps/desktop/src/lib/consul/pagination.ts b/apps/desktop/src/lib/consul/pagination.ts
new file mode 100644
index 0000000000..e3cab33cdf
--- /dev/null
+++ b/apps/desktop/src/lib/consul/pagination.ts
@@ -0,0 +1,19 @@
+export const CONSUL_LIST_PAGE_SIZE = 50;
+
+export function consulPageCount(total: number, pageSize = CONSUL_LIST_PAGE_SIZE): number {
+ const safeTotal = Math.max(0, Math.trunc(total));
+ const safePageSize = Math.max(1, Math.trunc(pageSize));
+ return Math.max(1, Math.ceil(safeTotal / safePageSize));
+}
+
+export function clampConsulPage(page: number, total: number, pageSize = CONSUL_LIST_PAGE_SIZE): number {
+ const safePage = Number.isFinite(page) ? Math.trunc(page) : 1;
+ return Math.min(Math.max(1, safePage), consulPageCount(total, pageSize));
+}
+
+export function paginateConsulItems<T>(items: readonly T[], page: number, pageSize = CONSUL_LIST_PAGE_SIZE): T[] {
+ const safePageSize = Math.max(1, Math.trunc(pageSize));
+ const safePage = clampConsulPage(page, items.length, safePageSize);
+ const start = (safePage - 1) * safePageSize;
+ return items.slice(start, start + safePageSize);
+}
diff --git a/apps/desktop/src/lib/consul/sessionModel.ts b/apps/desktop/src/lib/consul/sessionModel.ts
new file mode 100644
index 0000000000..e2efc396da
--- /dev/null
+++ b/apps/desktop/src/lib/consul/sessionModel.ts
@@ -0,0 +1,22 @@
+import type { ConsulSession, ConsulSessionServiceCheck } from "@/types/consul";
+
+type ConsulSessionWire = Partial<ConsulSession> & { Checks?: unknown };
+
+export function normalizeConsulSession(value: ConsulSessionWire): ConsulSession {
+ const nodeChecks = Array.isArray(value.NodeChecks) ? value.NodeChecks.filter((item): item is string => typeof item === "string") : Array.isArray(value.Checks) ? value.Checks.filter((item): item is string => typeof item === "string") : [];
+ const serviceChecks = Array.isArray(value.ServiceChecks) ? value.ServiceChecks.filter((item): item is ConsulSessionServiceCheck => Boolean(item) && typeof item.ID === "string").map((item) => ({ ID: item.ID, Namespace: typeof item.Namespace === "string" ? item.Namespace : "" })) : [];
+ return {
+ ID: typeof value.ID === "string" ? value.ID : "",
+ Name: typeof value.Name === "string" ? value.Name : "",
+ Node: typeof value.Node === "string" ? value.Node : "",
+ LockDelay: Number(value.LockDelay || 0),
+ Behavior: typeof value.Behavior === "string" ? value.Behavior : "release",
+ TTL: typeof value.TTL === "string" ? value.TTL : "",
+ NodeChecks: nodeChecks,
+ ServiceChecks: serviceChecks,
+ Namespace: typeof value.Namespace === "string" ? value.Namespace : "",
+ Partition: typeof value.Partition === "string" ? value.Partition : "",
+ CreateIndex: Number(value.CreateIndex || 0),
+ ModifyIndex: Number(value.ModifyIndex || value.CreateIndex || 0),
+ };
+}
diff --git a/apps/desktop/src/lib/consul/sessionRenew.ts b/apps/desktop/src/lib/consul/sessionRenew.ts
new file mode 100644
index 0000000000..5f5ac1622b
--- /dev/null
+++ b/apps/desktop/src/lib/consul/sessionRenew.ts
@@ -0,0 +1,21 @@
+const DURATION_PART = /(\d+(?:\.\d+)?)(ms|s|m|h)/gy;
+
+export function parseConsulDurationMs(value: string): number | null {
+ const input = value.trim();
+ if (!input) return null;
+ let total = 0;
+ let offset = 0;
+ for (const match of input.matchAll(DURATION_PART)) {
+ if (match.index !== offset) return null;
+ const amount = Number(match[1]);
+ const multiplier = match[2] === "h" ? 3_600_000 : match[2] === "m" ? 60_000 : match[2] === "s" ? 1_000 : 1;
+ total += amount * multiplier;
+ offset += match[0].length;
+ }
+ return offset === input.length && Number.isFinite(total) && total >= 0 ? total : null;
+}
+
+export function consulSessionRenewDelayMs(ttl: string): number {
+ const ttlMs = parseConsulDurationMs(ttl) ?? 20_000;
+ return Math.max(1_000, Math.min(30_000, Math.floor(ttlMs / 2)));
+}
diff --git a/apps/desktop/src/lib/consul/watchState.ts b/apps/desktop/src/lib/consul/watchState.ts
new file mode 100644
index 0000000000..6fad006bab
--- /dev/null
+++ b/apps/desktop/src/lib/consul/watchState.ts
@@ -0,0 +1,34 @@
+import type { KvInt64 } from "@/lib/backend/tauri";
+import type { ConsulWatchEvent } from "@/types/consul";
+
+export interface ConsulWatchState {
+ index: KvInt64 | null;
+ connected: boolean;
+ paused: boolean;
+ generation: number;
+}
+
+export interface ConsulWatchIdentity {
+ connectionId: string;
+ operationId: string;
+ generation: number;
+}
+
+export function isCurrentWatchEvent(identity: ConsulWatchIdentity, event: ConsulWatchEvent): boolean {
+ return event.connectionId === identity.connectionId && event.operationId === identity.operationId && event.generation === identity.generation;
+}
+
+export function nextWatchIndex(current: KvInt64 | null, returned: KvInt64 | null): { index: KvInt64; reset: boolean } {
+ const currentValue = parseIndex(current) || 1n;
+ const returnedValue = parseIndex(returned);
+ if (returnedValue === 0n || returnedValue < currentValue) return { index: "1" as KvInt64, reset: true };
+ return { index: returned ?? ("1" as KvInt64), reset: false };
+}
+
+function parseIndex(index: KvInt64 | null): bigint {
+ try {
+ return BigInt(index ?? "0");
+ } catch {
+ return 0n;
+ }
+}
diff --git a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
index 94ef769326..d283c5a20f 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
@@ -25,7 +25,7 @@ export function isColumnNameCopySeparator(value: unknown): value is ColumnNameCo
}
// SQL 执行能力是产品能力,不代表数据库支持 SQL 标识符引用。
-const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "victoriametrics"]);
+const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "victoriametrics"]);
// quoteTableIdentifier 对 jdbc/iotdb 原样返回(无引用字符可用)。
const UNQUOTABLE_DATABASE_TYPES = new Set<DatabaseType>(["jdbc", "iotdb"]);
diff --git a/apps/desktop/src/lib/database/databaseFeatureSupport.ts b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
index df288d5135..4552c75c34 100644
--- a/apps/desktop/src/lib/database/databaseFeatureSupport.ts
+++ b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
@@ -79,7 +79,7 @@ export function supportsClearableQuerySchema(dbType?: DatabaseType): boolean {
}
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
- return dbType !== "nacos" && dbType !== "hbase";
+ return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase";
}
/**
diff --git a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
index b6dc94c832..ba4fc4bae2 100644
--- a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
+++ b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
@@ -85,6 +85,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
jdbc: { deferred: "generic JDBC does not expose a reliable dialect-specific create target" },
mq: { deferred: "message queue namespaces are handled by MQ admin panels" },
nacos: { deferred: "Nacos namespace creation already uses the Nacos admin flow" },
+ consul: { deferred: "Consul namespaces and partitions are connection scopes, not KV resources" },
mqtt: { deferred: "MQTT topics are managed via the MQTT console" },
} satisfies Record<DatabaseType, DatabaseNamespaceCreationMatrixEntry>;
diff --git a/apps/desktop/src/lib/database/databasePropertyEditing.ts b/apps/desktop/src/lib/database/databasePropertyEditing.ts
index 50955e74bc..255aca8b52 100644
--- a/apps/desktop/src/lib/database/databasePropertyEditing.ts
+++ b/apps/desktop/src/lib/database/databasePropertyEditing.ts
@@ -85,6 +85,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
jdbc: { deferred: "generic JDBC does not expose reliable dialect-specific properties" },
mq: { deferred: "message queue namespaces are handled by MQ admin panels" },
nacos: { deferred: "Nacos namespace editing already uses the Nacos admin flow" },
+ consul: { deferred: "Consul KV scopes are configured on the connection" },
mqtt: { deferred: "MQTT topics are managed via the MQTT console" },
} satisfies Record<DatabaseType, DatabasePropertyEditingEntry>;
diff --git a/apps/desktop/src/lib/kv/kvMutationError.ts b/apps/desktop/src/lib/kv/kvMutationError.ts
index 4f95a86803..801ec6de5b 100644
--- a/apps/desktop/src/lib/kv/kvMutationError.ts
+++ b/apps/desktop/src/lib/kv/kvMutationError.ts
@@ -24,13 +24,13 @@ export function classifyKvMutationError(error: unknown, creating: boolean, messa
const sanitized = sanitizeKvMutationError(error);
const normalized = sanitized.toLowerCase();
- if (normalized.includes("etcd_key_already_exists") || (creating && normalized.includes("etcd_cas_conflict"))) {
+ if (normalized.includes("etcd_key_already_exists") || normalized.includes("consul_key_already_exists") || (creating && (normalized.includes("etcd_cas_conflict") || normalized.includes("consul_cas_conflict")))) {
return {
kind: "keyAlreadyExists",
message: messages.keyAlreadyExists || "A Key with this name already exists. Choose another name or edit the existing Key.",
};
}
- if (normalized.includes("etcd_cas_conflict")) {
+ if (normalized.includes("etcd_cas_conflict") || normalized.includes("consul_cas_conflict")) {
return {
kind: "conflict",
message: messages.conflict || "The Key changed after it was loaded. Refresh it and try again.",
diff --git a/apps/desktop/src/lib/kv/kvRootPresentation.ts b/apps/desktop/src/lib/kv/kvRootPresentation.ts
index a3e9276ac3..4feba9d13a 100644
--- a/apps/desktop/src/lib/kv/kvRootPresentation.ts
+++ b/apps/desktop/src/lib/kv/kvRootPresentation.ts
@@ -1,4 +1,4 @@
-export type KvRootKind = "etcd" | "zookeeper";
+export type KvRootKind = "etcd" | "zookeeper" | "consul";
export function kvRootNodeLabel(kind: KvRootKind): string {
return kind === "zookeeper" ? "/" : "Keys";
diff --git a/apps/desktop/src/lib/kv/slashPrefixLazyKeyTree.ts b/apps/desktop/src/lib/kv/slashPrefixLazyKeyTree.ts
new file mode 100644
index 0000000000..8992ab1dac
--- /dev/null
+++ b/apps/desktop/src/lib/kv/slashPrefixLazyKeyTree.ts
@@ -0,0 +1,242 @@
+import type { KvKeyMetadata, KvKeySummary } from "@/lib/backend/api";
+
+export interface LazyKvKeyTreeNode extends KvKeyMetadata {
+ kind: "lazy";
+ id: string;
+ label: string;
+ key: string;
+ pathSegments: string[];
+ /**
+ * `null` means that a separator-based Consul listing returned a path ending
+ * in `/`, so an exact GET is still required to distinguish a real Key from a
+ * virtual prefix. ZooKeeper nodes and non-directory Consul Keys are known
+ * values immediately.
+ */
+ hasValue: boolean | null;
+ hasChildren: boolean;
+ children: LazyKvKeyTreeNode[];
+ loaded: boolean;
+ loading: boolean;
+ continuation: string | null;
+}
+
+export interface LazyKvKeyTreeState {
+ pathStyle: LazyKvPathStyle;
+ rootPath: string;
+ roots: LazyKvKeyTreeNode[];
+ rootContinuation: string | null;
+ nodeByKey: Map<string, LazyKvKeyTreeNode>;
+}
+
+export type LazyKvPathStyle = "absolute" | "relative";
+
+export type LazyKvKeySummary = KvKeySummary & { hasValue?: boolean | null };
+
+export function lazyKvRootPath(pathStyle: LazyKvPathStyle): string {
+ return pathStyle === "absolute" ? "/" : "";
+}
+
+export function normalizeLazyKvPath(path: string, pathStyle: LazyKvPathStyle): string {
+ if (pathStyle === "absolute") return normalizeZooKeeperPath(path);
+ return path.trim().replace(/^\/+/, "");
+}
+
+export function parentLazyKvPath(path: string, pathStyle: LazyKvPathStyle): string {
+ if (pathStyle === "absolute") return parentZooKeeperPath(path);
+ const normalized = normalizeLazyKvPath(path, pathStyle);
+ const withoutTrailingSlash = normalized.replace(/\/+$/, "");
+ const separator = withoutTrailingSlash.lastIndexOf("/");
+ return separator < 0 ? "" : `${withoutTrailingSlash.slice(0, separator)}/`;
+}
+
+export function createLazyKvChildPathDraft(parentPath: string, pathStyle: LazyKvPathStyle): string {
+ if (pathStyle === "absolute") return createZooKeeperChildPathDraft(parentPath);
+ const normalized = normalizeLazyKvPath(parentPath, pathStyle);
+ return normalized ? (normalized.endsWith("/") ? normalized : `${normalized}/`) : "";
+}
+
+export type LazyKvKeyTreeRow =
+ | {
+ type: "node";
+ node: LazyKvKeyTreeNode;
+ depth: number;
+ }
+ | {
+ type: "loadMore";
+ id: string;
+ parentKey: string | null;
+ depth: number;
+ loading: boolean;
+ };
+
+export function normalizeZooKeeperPath(path: string): string {
+ const trimmed = path.trim();
+ if (!trimmed || trimmed === "/") return "/";
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ return withSlash.replace(/\/+$/, "") || "/";
+}
+
+export function parentZooKeeperPath(path: string): string {
+ const normalized = normalizeZooKeeperPath(path);
+ if (normalized === "/") return "/";
+ const parent = normalized.slice(0, normalized.lastIndexOf("/"));
+ return parent || "/";
+}
+
+export function createZooKeeperChildPathDraft(parentPath: string): string {
+ const normalized = normalizeZooKeeperPath(parentPath);
+ if (normalized === "/") return "";
+ return `${normalized}/`;
+}
+
+export function createLazyKvKeyTreeState(rootPath = "/", pathStyle: LazyKvPathStyle = "absolute"): LazyKvKeyTreeState {
+ return {
+ pathStyle,
+ rootPath: normalizeLazyKvPath(rootPath, pathStyle),
+ roots: [],
+ rootContinuation: null,
+ nodeByKey: new Map(),
+ };
+}
+
+export function resetLazyKvKeyTree(state: LazyKvKeyTreeState, rootPath = lazyKvRootPath(state.pathStyle)) {
+ state.rootPath = normalizeLazyKvPath(rootPath, state.pathStyle);
+ state.roots = [];
+ state.rootContinuation = null;
+ state.nodeByKey.clear();
+}
+
+export function replaceLazyKvChildren(state: LazyKvKeyTreeState, parentKey: string | null, keys: LazyKvKeySummary[], continuation: string | null | undefined, options: { append?: boolean; filteredByAcls?: boolean | null } = {}) {
+ const previous = new Map(state.nodeByKey);
+ const nextChildren = keys.map((key) => lazyNodeFromSummary(key, state.pathStyle, previous.get(key.key)));
+ const children = options.append ? mergeLazyChildren(parentKey ? state.nodeByKey.get(parentKey)?.children || [] : state.roots, nextChildren) : nextChildren;
+
+ if (parentKey) {
+ const parent = state.nodeByKey.get(parentKey);
+ if (!parent) return;
+ parent.children = children;
+ parent.loaded = true;
+ parent.continuation = continuation || null;
+ // A separator listing cannot initially distinguish a real `key/` from a
+ // virtual directory. Once its complete, unfiltered child listing is empty,
+ // it is known to be a leaf and must no longer render an expander.
+ if (children.length > 0 || continuation) parent.hasChildren = true;
+ else if (!options.filteredByAcls) parent.hasChildren = false;
+ } else {
+ state.roots = children;
+ state.rootContinuation = continuation || null;
+ }
+
+ rebuildLazyNodeIndex(state);
+}
+
+export function replaceLazyKvFocusedRoot(state: LazyKvKeyTreeState, root: LazyKvKeySummary, keys: LazyKvKeySummary[], continuation: string | null | undefined) {
+ const previous = new Map(state.nodeByKey);
+ const focusedPath = normalizeLazyKvPath(root.key, state.pathStyle);
+ const childNodes = keys.map((key) => lazyNodeFromSummary(key, state.pathStyle, previous.get(key.key)));
+ const chain = focusedPathChain(focusedPath, state.pathStyle);
+ let rootNode: LazyKvKeyTreeNode | null = null;
+ let parentNode: LazyKvKeyTreeNode | null = null;
+
+ for (const path of chain) {
+ const isFocusedPath = path === focusedPath;
+ const node = lazyNodeFromSummary(isFocusedPath ? { ...root, key: focusedPath } : { key: path, numChildren: 1, hasValue: false }, state.pathStyle, previous.get(path));
+ // Ancestors are directories, but an exact focused Key with no children must
+ // remain a leaf. Otherwise searching for that Key renders it as a folder.
+ node.hasChildren = !isFocusedPath || (node.numChildren ?? 0) > 0;
+ node.loaded = true;
+ node.continuation = null;
+ node.children = [];
+
+ if (parentNode) parentNode.children = [node];
+ else rootNode = node;
+ parentNode = node;
+ }
+
+ if (parentNode) {
+ parentNode.children = childNodes;
+ parentNode.hasChildren = parentNode.hasChildren || childNodes.length > 0 || !!continuation;
+ parentNode.continuation = continuation || null;
+ }
+
+ state.roots = rootNode ? [rootNode] : [];
+ state.rootContinuation = null;
+ rebuildLazyNodeIndex(state);
+}
+
+export function flattenLazyKvKeyTree(state: LazyKvKeyTreeState, expandedIds: ReadonlySet<string>): LazyKvKeyTreeRow[] {
+ const rows = flattenLazyNodes(state.roots, expandedIds, 0);
+ if (state.rootContinuation) {
+ rows.push({ type: "loadMore", id: "lazy-load-more:root", parentKey: null, depth: 0, loading: false });
+ }
+ return rows;
+}
+
+export function lazyExpandedKeyFromId(id: string): string | null {
+ return id.startsWith("lazy:") ? id.slice("lazy:".length) : null;
+}
+
+function flattenLazyNodes(nodes: LazyKvKeyTreeNode[], expandedIds: ReadonlySet<string>, depth: number): LazyKvKeyTreeRow[] {
+ const rows: LazyKvKeyTreeRow[] = [];
+ for (const node of nodes) {
+ rows.push({ type: "node", node, depth });
+ if (node.hasChildren && expandedIds.has(node.id)) {
+ rows.push(...flattenLazyNodes(node.children, expandedIds, depth + 1));
+ if (node.continuation) {
+ rows.push({ type: "loadMore", id: `lazy-load-more:${node.key}`, parentKey: node.key, depth: depth + 1, loading: node.loading });
+ }
+ }
+ }
+ return rows;
+}
+
+function lazyNodeFromSummary(summary: LazyKvKeySummary, pathStyle: LazyKvPathStyle, previous?: LazyKvKeyTreeNode): LazyKvKeyTreeNode {
+ const pathSegments = keySegments(summary.key);
+ const hasValue = summary.hasValue !== undefined ? summary.hasValue : pathStyle === "absolute" || !summary.key.endsWith("/") ? true : (previous?.hasValue ?? null);
+ return {
+ ...summary,
+ kind: "lazy",
+ id: `lazy:${summary.key}`,
+ label: pathSegments[pathSegments.length - 1] || summary.key || "/",
+ key: summary.key,
+ pathSegments,
+ hasValue,
+ hasChildren: (summary.numChildren ?? 0) > 0 || summary.key.endsWith("/"),
+ children: previous?.children || [],
+ loaded: previous?.loaded || false,
+ loading: previous?.loading || false,
+ continuation: previous?.continuation || null,
+ };
+}
+
+function mergeLazyChildren(existing: LazyKvKeyTreeNode[], incoming: LazyKvKeyTreeNode[]): LazyKvKeyTreeNode[] {
+ const seen = new Set(existing.map((node) => node.key));
+ return [...existing, ...incoming.filter((node) => !seen.has(node.key))];
+}
+
+function rebuildLazyNodeIndex(state: LazyKvKeyTreeState) {
+ state.nodeByKey.clear();
+ const visit = (nodes: LazyKvKeyTreeNode[]) => {
+ for (const node of nodes) {
+ state.nodeByKey.set(node.key, node);
+ visit(node.children);
+ }
+ };
+ visit(state.roots);
+}
+
+function keySegments(key: string): string[] {
+ return key.split("/").filter(Boolean);
+}
+
+function focusedPathChain(path: string, pathStyle: LazyKvPathStyle): string[] {
+ const segments = keySegments(path);
+ const trailingSlash = pathStyle === "relative" && path.endsWith("/");
+ const chain: string[] = [];
+ for (let index = 0; index < segments.length; index++) {
+ const joined = segments.slice(0, index + 1).join("/");
+ const isLeaf = index === segments.length - 1;
+ chain.push(pathStyle === "absolute" ? `/${joined}` : isLeaf && !trailingSlash ? joined : `${joined}/`);
+ }
+ return chain;
+}
diff --git a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
index c7a2a08d5d..54e8c7bdbe 100644
--- a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
@@ -48,6 +48,14 @@ export type ActiveTabSidebarTarget =
type: "zookeeper-root";
connectionId: string;
}
+ | {
+ type: "consul-root";
+ connectionId: string;
+ }
+ | {
+ type: "consul-overview";
+ connectionId: string;
+ }
| {
type: "mq-tenant";
connectionId: string;
@@ -147,6 +155,12 @@ export function activeTabSidebarTarget(tab: QueryTab | undefined | null): Active
if (tab.mode === "zookeeper") {
return { type: "zookeeper-root", connectionId: tab.connectionId };
}
+ if (tab.mode === "consul") {
+ return { type: "consul-root", connectionId: tab.connectionId };
+ }
+ if (tab.mode === "consul-overview") {
+ return { type: "consul-overview", connectionId: tab.connectionId };
+ }
if (tab.mode === "mq" && tab.mqTenant) {
return { type: "mq-tenant", connectionId: tab.connectionId, tenant: tab.mqTenant };
@@ -226,6 +240,12 @@ export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): b
if (target.type === "zookeeper-root") {
return node.type === "zookeeper-root" && node.connectionId === target.connectionId;
}
+ if (target.type === "consul-root") {
+ return node.type === "consul-root" && node.connectionId === target.connectionId;
+ }
+ if (target.type === "consul-overview") {
+ return node.type === "consul-overview" && node.connectionId === target.connectionId;
+ }
if (target.type === "mq-tenant") {
return node.type === "mq-tenant" && node.connectionId === target.connectionId && (node.mqTenant || node.label) === target.tenant;
diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeItemLayout.ts b/apps/desktop/src/lib/sidebar/sidebarTreeItemLayout.ts
index 034a43ab10..9cf5b3d608 100644
--- a/apps/desktop/src/lib/sidebar/sidebarTreeItemLayout.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarTreeItemLayout.ts
@@ -19,6 +19,8 @@ const leafTypes: Set<TreeNodeType> = new Set([
"etcd-dashboard",
"etcd-access-control",
"zookeeper-root",
+ "consul-root",
+ "consul-overview",
"mongo-gridfs",
"mongo-bucket",
"vector-collection",
diff --git a/apps/desktop/src/lib/sidebar/treeNodeClick.ts b/apps/desktop/src/lib/sidebar/treeNodeClick.ts
index 3817699f9c..020264f043 100644
--- a/apps/desktop/src/lib/sidebar/treeNodeClick.ts
+++ b/apps/desktop/src/lib/sidebar/treeNodeClick.ts
@@ -8,7 +8,35 @@ export type SidebarActivation = "single" | "double";
const dataNodeTypes = new Set<TreeNodeType>(["table", "view", "materialized_view"]);
const documentBrowserNodeTypes = new Set<TreeNodeType>(["mongo-collection", "mongo-bucket"]);
-const toggleLeafNodeTypes = new Set<TreeNodeType>(["redis-db", "mq-tenant", "mqtt-topic", "etcd-root", "etcd-dashboard", "etcd-access-control", "zookeeper-root", "mongo-gridfs", "mongo-collection", "mongo-bucket", "vector-collection", "elasticsearch-index", "user-admin"]);
+const toggleLeafNodeTypes = new Set<TreeNodeType>([
+ "redis-db",
+ "mq-tenant",
+ "mqtt-topic",
+ "etcd-root",
+ "etcd-dashboard",
+ "etcd-access-control",
+ "zookeeper-root",
+ "consul-root",
+ "consul-overview",
+ "mongo-gridfs",
+ "mongo-collection",
+ "mongo-bucket",
+ "vector-collection",
+ "elasticsearch-index",
+ "user-admin",
+]);
+// These are application entry points rather than database objects. They should
+// always navigate on a single click, even when the user prefers double-click
+// activation for ordinary tree objects.
+const directNavigationTreeNodeTypes = new Set<TreeNodeType>(["consul-root", "consul-overview"]);
+
+export function isDirectNavigationTreeNode(type: TreeNodeType): boolean {
+ return directNavigationTreeNodeTypes.has(type);
+}
+
+export function shouldActivateTreeNodeOnSingleClick(type: TreeNodeType, activation: SidebarActivation = "single"): boolean {
+ return activation !== "double" || isDirectNavigationTreeNode(type);
+}
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
const sourceNodeTypes = new Set<TreeNodeType>(["materialized_view", "procedure", "function", "trigger", "sequence", "synonym", "package", "package-body", "type", "type-body"]);
const savedSqlNodeTypes = new Set<TreeNodeType>(["saved-sql-file"]);
@@ -35,7 +63,7 @@ export function isDocumentBrowserTreeNode(type: TreeNodeType): boolean {
}
export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single"): TreeNodeRowAction {
- if (activation === "double") return "none";
+ if (!shouldActivateTreeNodeOnSingleClick(type, activation)) return "none";
if (type === "extension") return "open-extension-details";
if (dataNodeTypes.has(type)) return "open-data";
if (sourceNodeTypes.has(type)) return "open-source";
diff --git a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
index f33f82ef0b..a48766d83b 100644
--- a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
+++ b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
@@ -36,6 +36,7 @@ export function getTreeNodeIconInfo(node: TreeNode): TreeNodeIconInfo | null {
case "etcd-access-control":
return { icon: ShieldCheck, colorClass: "text-sky-500" };
case "zookeeper-root":
+ case "consul-root":
return { icon: Database, colorClass: "text-blue-500" };
case "table":
return { icon: Table, colorClass: "text-green-500" };
diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
index 7bf61f707e..74f7bece5a 100644
--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts
+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
@@ -22,7 +22,7 @@ export function elasticsearchRestRequestRanges(sql: string, databaseType?: Datab
return requests.length > 0 && requests.every((request) => ELASTICSEARCH_REST_REQUEST.test(request.sql)) ? requests : [];
}
-const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "neo4j", "victoriametrics"]);
+const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "neo4j", "victoriametrics"]);
export function supportsExecutionTargetPicker(databaseType?: DatabaseType): boolean {
return !!databaseType && (databaseType === "redis" || isElasticsearchCompatibleDatabaseType(databaseType) || !NON_SQL_EXECUTION_TARGET_TYPES.has(databaseType));
diff --git a/apps/desktop/src/lib/tabs/tabPresentation.ts b/apps/desktop/src/lib/tabs/tabPresentation.ts
index e1cf08606a..6f6a06e262 100644
--- a/apps/desktop/src/lib/tabs/tabPresentation.ts
+++ b/apps/desktop/src/lib/tabs/tabPresentation.ts
@@ -119,6 +119,14 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
if (compact) return connectionDisplayName(tab.connectionId);
return `${connectionDisplayName(tab.connectionId)}@keys`;
}
+ if (tab.mode === "consul") {
+ if (compact) return connectionDisplayName(tab.connectionId);
+ return `${connectionDisplayName(tab.connectionId)}@keys`;
+ }
+ if (tab.mode === "consul-overview") {
+ if (compact) return connectionDisplayName(tab.connectionId);
+ return `${connectionDisplayName(tab.connectionId)}@${t("consul.ui.overview")}`;
+ }
if (tab.mode === "objects") {
const schema = tab.objectBrowser?.schema;
if (compact) return schema || tab.title;
@@ -418,6 +426,8 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
if (tab.mode === "etcd-dashboard") return t("tabs.etcdDashboard");
if (tab.mode === "etcd-access-control") return t("tabs.etcdAccessControl");
if (tab.mode === "zookeeper") return t("tabs.zookeeper");
+ if (tab.mode === "consul") return t("tabs.consul");
+ if (tab.mode === "consul-overview") return t("consul.ui.overview");
if (tab.mode === "nacos") return "Nacos";
if (tab.mode === "objects") return t("tabs.objects");
if (tab.mode === "users") return t("tabs.users");
diff --git a/apps/desktop/src/lib/zookeeper/zookeeperLazyKeyTree.ts b/apps/desktop/src/lib/zookeeper/zookeeperLazyKeyTree.ts
index 41fc58de86..f36c913bd4 100644
--- a/apps/desktop/src/lib/zookeeper/zookeeperLazyKeyTree.ts
+++ b/apps/desktop/src/lib/zookeeper/zookeeperLazyKeyTree.ts
@@ -1,193 +1 @@
-import type { KvKeyMetadata, KvKeySummary } from "@/lib/backend/api";
-
-export interface LazyKvKeyTreeNode extends KvKeyMetadata {
- kind: "lazy";
- id: string;
- label: string;
- key: string;
- pathSegments: string[];
- hasChildren: boolean;
- children: LazyKvKeyTreeNode[];
- loaded: boolean;
- loading: boolean;
- continuation: string | null;
-}
-
-export interface LazyKvKeyTreeState {
- rootPath: string;
- roots: LazyKvKeyTreeNode[];
- rootContinuation: string | null;
- nodeByKey: Map<string, LazyKvKeyTreeNode>;
-}
-
-export type LazyKvKeyTreeRow =
- | {
- type: "node";
- node: LazyKvKeyTreeNode;
- depth: number;
- }
- | {
- type: "loadMore";
- id: string;
- parentKey: string | null;
- depth: number;
- loading: boolean;
- };
-
-export function normalizeZooKeeperPath(path: string): string {
- const trimmed = path.trim();
- if (!trimmed || trimmed === "/") return "/";
- const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
- return withSlash.replace(/\/+$/, "") || "/";
-}
-
-export function parentZooKeeperPath(path: string): string {
- const normalized = normalizeZooKeeperPath(path);
- if (normalized === "/") return "/";
- const parent = normalized.slice(0, normalized.lastIndexOf("/"));
- return parent || "/";
-}
-
-export function createZooKeeperChildPathDraft(parentPath: string): string {
- const normalized = normalizeZooKeeperPath(parentPath);
- if (normalized === "/") return "";
- return `${normalized}/`;
-}
-
-export function createLazyKvKeyTreeState(rootPath = "/"): LazyKvKeyTreeState {
- return {
- rootPath: normalizeZooKeeperPath(rootPath),
- roots: [],
- rootContinuation: null,
- nodeByKey: new Map(),
- };
-}
-
-export function resetLazyKvKeyTree(state: LazyKvKeyTreeState, rootPath = "/") {
- state.rootPath = normalizeZooKeeperPath(rootPath);
- state.roots = [];
- state.rootContinuation = null;
- state.nodeByKey.clear();
-}
-
-export function replaceLazyKvChildren(state: LazyKvKeyTreeState, parentKey: string | null, keys: KvKeySummary[], continuation: string | null | undefined, options: { append?: boolean } = {}) {
- const previous = new Map(state.nodeByKey);
- const nextChildren = keys.map((key) => lazyNodeFromSummary(key, previous.get(key.key)));
- const children = options.append ? mergeLazyChildren(parentKey ? state.nodeByKey.get(parentKey)?.children || [] : state.roots, nextChildren) : nextChildren;
-
- if (parentKey) {
- const parent = state.nodeByKey.get(parentKey);
- if (!parent) return;
- parent.children = children;
- parent.loaded = true;
- parent.continuation = continuation || null;
- } else {
- state.roots = children;
- state.rootContinuation = continuation || null;
- }
-
- rebuildLazyNodeIndex(state);
-}
-
-export function replaceLazyKvFocusedRoot(state: LazyKvKeyTreeState, root: KvKeySummary, keys: KvKeySummary[], continuation: string | null | undefined) {
- const previous = new Map(state.nodeByKey);
- const focusedPath = normalizeZooKeeperPath(root.key);
- const childNodes = keys.map((key) => lazyNodeFromSummary(key, previous.get(key.key)));
- const chain = focusedPathChain(focusedPath);
- let rootNode: LazyKvKeyTreeNode | null = null;
- let parentNode: LazyKvKeyTreeNode | null = null;
-
- for (const path of chain) {
- const node = lazyNodeFromSummary(path === focusedPath ? { ...root, key: focusedPath } : { key: path, numChildren: 1 }, previous.get(path));
- node.hasChildren = true;
- node.loaded = true;
- node.continuation = null;
- node.children = [];
-
- if (parentNode) parentNode.children = [node];
- else rootNode = node;
- parentNode = node;
- }
-
- if (parentNode) {
- parentNode.children = childNodes;
- parentNode.hasChildren = parentNode.hasChildren || childNodes.length > 0 || !!continuation;
- parentNode.continuation = continuation || null;
- }
-
- state.roots = rootNode ? [rootNode] : [];
- state.rootContinuation = null;
- rebuildLazyNodeIndex(state);
-}
-
-export function flattenLazyKvKeyTree(state: LazyKvKeyTreeState, expandedIds: ReadonlySet<string>): LazyKvKeyTreeRow[] {
- const rows = flattenLazyNodes(state.roots, expandedIds, 0);
- if (state.rootContinuation) {
- rows.push({ type: "loadMore", id: "lazy-load-more:root", parentKey: null, depth: 0, loading: false });
- }
- return rows;
-}
-
-export function lazyExpandedKeyFromId(id: string): string | null {
- return id.startsWith("lazy:") ? id.slice("lazy:".length) : null;
-}
-
-function flattenLazyNodes(nodes: LazyKvKeyTreeNode[], expandedIds: ReadonlySet<string>, depth: number): LazyKvKeyTreeRow[] {
- const rows: LazyKvKeyTreeRow[] = [];
- for (const node of nodes) {
- rows.push({ type: "node", node, depth });
- if (node.hasChildren && expandedIds.has(node.id)) {
- rows.push(...flattenLazyNodes(node.children, expandedIds, depth + 1));
- if (node.continuation) {
- rows.push({ type: "loadMore", id: `lazy-load-more:${node.key}`, parentKey: node.key, depth: depth + 1, loading: node.loading });
- }
- }
- }
- return rows;
-}
-
-function lazyNodeFromSummary(summary: KvKeySummary, previous?: LazyKvKeyTreeNode): LazyKvKeyTreeNode {
- const pathSegments = keySegments(summary.key);
- return {
- ...summary,
- kind: "lazy",
- id: `lazy:${summary.key}`,
- label: pathSegments[pathSegments.length - 1] || summary.key || "/",
- key: summary.key,
- pathSegments,
- hasChildren: (summary.numChildren ?? 0) > 0,
- children: previous?.children || [],
- loaded: previous?.loaded || false,
- loading: previous?.loading || false,
- continuation: previous?.continuation || null,
- };
-}
-
-function mergeLazyChildren(existing: LazyKvKeyTreeNode[], incoming: LazyKvKeyTreeNode[]): LazyKvKeyTreeNode[] {
- const seen = new Set(existing.map((node) => node.key));
- return [...existing, ...incoming.filter((node) => !seen.has(node.key))];
-}
-
-function rebuildLazyNodeIndex(state: LazyKvKeyTreeState) {
- state.nodeByKey.clear();
- const visit = (nodes: LazyKvKeyTreeNode[]) => {
- for (const node of nodes) {
- state.nodeByKey.set(node.key, node);
- visit(node.children);
- }
- };
- visit(state.roots);
-}
-
-function keySegments(key: string): string[] {
- return key.split("/").filter(Boolean);
-}
-
-function focusedPathChain(path: string): string[] {
- const segments = keySegments(path);
- const chain: string[] = [];
- for (let index = 0; index < segments.length; index++) {
- chain.push(`/${segments.slice(0, index + 1).join("/")}`);
- }
- return chain;
-}
+export * from "@/lib/kv/slashPrefixLazyKeyTree";
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index bb4b04369f..ba9d4ca89a 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -985,6 +985,7 @@ export const useConnectionStore = defineStore("connection", () => {
redis: "Redis",
etcd: "etcd",
zookeeper: "Apache ZooKeeper",
+ consul: "Consul",
duckdb: "DuckDB",
clickhouse: "ClickHouse",
sqlserver: "SQL Server",
@@ -2744,6 +2745,8 @@ export const useConnectionStore = defineStore("connection", () => {
await loadEtcdRoot(connectionId);
} else if (config.db_type === "zookeeper") {
await loadZooKeeperRoot(connectionId);
+ } else if (config.db_type === "consul") {
+ await loadConsulRoot(connectionId);
} else if (config.db_type === "mongodb") {
await loadMongoDatabases(connectionId);
} else if (config.db_type === "elasticsearch" || config.db_type === "easysearch") {
@@ -3291,7 +3294,7 @@ export const useConnectionStore = defineStore("connection", () => {
async function loadConnectedConnectionRootForSidebarSearch(connectionId: string) {
if (!connectedIds.value.has(connectionId)) return;
const config = getConfig(connectionId);
- if (!config || ["redis", "etcd", "zookeeper", "mongodb", "elasticsearch", "easysearch", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos"].includes(config.db_type)) return;
+ if (!config || ["redis", "etcd", "zookeeper", "consul", "mongodb", "elasticsearch", "easysearch", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos"].includes(config.db_type)) return;
const node = findConnectionNode(connectionId);
if (!node || node.type !== "connection" || node.isLoading || hasConnectionMetadataChildren(node.children)) return;
const scope = { kind: "connection-databases" as const, connectionId, driverProfile: metadataDriverProfile(config) };
@@ -3450,6 +3453,52 @@ export const useConnectionStore = defineStore("connection", () => {
}
}
+ async function loadConsulRoot(connectionId: string) {
+ const node = findConnectionNode(connectionId);
+ if (!node) return;
+
+ let load = beginTreeNodeLoad(node);
+ try {
+ await ensureConnected(connectionId);
+ load = reclaimTreeNodeLoad(load, node);
+ const targetNode = treeNodeLoadTarget(load);
+ if (!targetNode) return;
+ setChildren(
+ targetNode,
+ withSavedSqlRoot(
+ connectionId,
+ [
+ {
+ id: `${connectionId}:consul`,
+ label: kvRootNodeLabel("consul"),
+ type: "consul-root" as const,
+ connectionId,
+ database: "",
+ isExpanded: false,
+ children: [],
+ },
+ {
+ id: `${connectionId}:consul-overview`,
+ label: i18n.global.t("consul.ui.overview"),
+ type: "consul-overview" as const,
+ connectionId,
+ database: "",
+ isExpanded: false,
+ children: [],
+ },
+ ],
+ targetNode,
+ ),
+ );
+ targetNode.isExpanded = true;
+ } catch (e) {
+ recordMetadataLoadError(connectionId, e, load);
+ throw e;
+ } finally {
+ finishTreeNodeLoad(load);
+ }
+ }
+
async function loadMqttTopics(connectionId: string) {
const node = findConnectionNode(connectionId);
if (!node) return;
@@ -5238,6 +5287,8 @@ export const useConnectionStore = defineStore("connection", () => {
await loadEtcdRoot(node.connectionId);
} else if (config?.db_type === "zookeeper") {
await loadZooKeeperRoot(node.connectionId);
+ } else if (config?.db_type === "consul") {
+ await loadConsulRoot(node.connectionId);
} else if (config?.db_type === "mongodb") {
await loadMongoDatabases(node.connectionId);
} else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch") {
@@ -7152,6 +7203,7 @@ export const useConnectionStore = defineStore("connection", () => {
refreshRedisDbKeyCounts,
loadEtcdRoot,
loadZooKeeperRoot,
+ loadConsulRoot,
loadMqTenants,
loadMqttTopics,
loadNacosNamespaces,
diff --git a/apps/desktop/src/stores/consulStore.ts b/apps/desktop/src/stores/consulStore.ts
new file mode 100644
index 0000000000..5812c74ac8
--- /dev/null
+++ b/apps/desktop/src/stores/consulStore.ts
@@ -0,0 +1,67 @@
+import { defineStore } from "pinia";
+import { computed, reactive, ref } from "vue";
+import * as api from "@/lib/backend/api";
+import type { ConsulScope } from "@/types/consul";
+
+function emptyScope(): ConsulScope {
+ return { datacenter: "", namespace: "", partition: "" };
+}
+
+export const useConsulStore = defineStore("consul", () => {
+ const activeConnectionId = ref("");
+ const scope = reactive<ConsulScope>(emptyScope());
+ const generation = ref(0);
+ const activeOperations = reactive(new Map<string, { connectionId: string; scope: ConsulScope; generation: number }>());
+
+ const scopeKey = computed(() => `${scope.datacenter}\0${scope.partition}\0${scope.namespace}`);
+
+ function bindConnection(connectionId: string, nextScope: ConsulScope = emptyScope()) {
+ if (activeConnectionId.value === connectionId && scopeKey.value === scopeIdentity(nextScope)) return;
+ invalidate();
+ activeConnectionId.value = connectionId;
+ Object.assign(scope, nextScope);
+ }
+
+ function switchScope(nextScope: ConsulScope) {
+ if (scopeKey.value === scopeIdentity(nextScope)) return;
+ invalidate();
+ Object.assign(scope, nextScope);
+ }
+
+ function registerOperation(operationId: string) {
+ if (activeOperations.has(operationId)) throw new Error("CONSUL_OPERATION_ALREADY_RUNNING");
+ activeOperations.set(operationId, {
+ connectionId: activeConnectionId.value,
+ scope: { ...scope },
+ generation: generation.value,
+ });
+ }
+
+ function completeOperation(operationId: string) {
+ activeOperations.delete(operationId);
+ }
+
+ function invalidate() {
+ for (const [operationId, operation] of activeOperations) {
+ void api.consulCancelBlocking(operation.connectionId, operation.scope, operation.generation, operationId).catch(() => undefined);
+ }
+ activeOperations.clear();
+ generation.value += 1;
+ }
+
+ return {
+ activeConnectionId,
+ scope,
+ scopeKey,
+ generation,
+ bindConnection,
+ switchScope,
+ registerOperation,
+ completeOperation,
+ invalidate,
+ };
+});
+
+function scopeIdentity(scope: ConsulScope): string {
+ return `${scope.datacenter}\0${scope.partition}\0${scope.namespace}`;
+}
diff --git a/apps/desktop/src/types/consul.ts b/apps/desktop/src/types/consul.ts
new file mode 100644
index 0000000000..5c6c1a5231
--- /dev/null
+++ b/apps/desktop/src/types/consul.ts
@@ -0,0 +1,944 @@
+import type { KvInt64, KvValue } from "@/lib/backend/tauri";
+
+export type ConsulCapabilityStatus = "supported" | "unsupported" | "disabled" | "forbidden" | "unknown";
+
+export interface ConsulScope {
+ datacenter: string;
+ namespace: string;
+ partition: string;
+}
+
+export interface ConsulResponseMetadata {
+ index: KvInt64 | null;
+ filteredByAcls: boolean | null;
+ knownLeader: boolean | null;
+ lastContact: KvInt64 | null;
+ queryBackend: string | null;
+}
+
+export interface ConsulCapabilities {
+ version: string | null;
+ datacenter: string | null;
+ nodeName: string | null;
+ server: boolean | null;
+ edition: string | null;
+ agent: ConsulCapabilityStatus;
+ catalog: ConsulCapabilityStatus;
+ health: ConsulCapabilityStatus;
+ sessions: ConsulCapabilityStatus;
+ acl: ConsulCapabilityStatus;
+ authMethods: ConsulCapabilityStatus;
+ bindingRules: ConsulCapabilityStatus;
+ templatedPolicies: ConsulCapabilityStatus;
+ namespaces: ConsulCapabilityStatus;
+ partitions: ConsulCapabilityStatus;
+ configEntries: ConsulCapabilityStatus;
+ intentions: ConsulCapabilityStatus;
+ peering: ConsulCapabilityStatus;
+ exportedServices: ConsulCapabilityStatus;
+ preparedQueries: ConsulCapabilityStatus;
+ events: ConsulCapabilityStatus;
+ coordinates: ConsulCapabilityStatus;
+ operatorAutopilot: ConsulCapabilityStatus;
+ operatorRaft: ConsulCapabilityStatus;
+ operatorKeyring: ConsulCapabilityStatus;
+ operatorUsage: ConsulCapabilityStatus;
+ operatorLicense: ConsulCapabilityStatus;
+ audit: ConsulCapabilityStatus;
+}
+
+export interface ConsulKvRecord {
+ key: string;
+ value: KvValue;
+ flags: KvInt64;
+ createIndex: KvInt64;
+ modifyIndex: KvInt64;
+ lockIndex: KvInt64;
+ session: string | null;
+}
+
+export interface ConsulRecursiveListResponse {
+ entries: ConsulKvRecord[];
+ index: KvInt64 | null;
+ filteredByAcls: boolean | null;
+ totalValueBytes: number;
+ complete: boolean;
+}
+
+export interface ConsulSearchRequest {
+ requestId: string;
+ prefix: string;
+ query: string;
+ searchKeys: boolean;
+ searchValues: boolean;
+ caseSensitive: boolean;
+ limit: number;
+ maxScan: number;
+ generation: number;
+}
+
+export interface ConsulSearchMatch extends ConsulKvRecord {
+ matchesKey: boolean;
+ matchesValue: boolean;
+}
+
+export interface ConsulSearchResponse {
+ matches: ConsulSearchMatch[];
+ scanned: number;
+ matched: number;
+ limited: boolean;
+ filteredByAcls: boolean | null;
+}
+
+export interface ConsulSearchProgress {
+ running: boolean;
+ scanned: number;
+ cancelled: boolean;
+}
+
+export type ConsulExportScopeKind = "key" | "prefix";
+
+export interface ConsulExportRequest {
+ path: string;
+ kind: ConsulExportScopeKind;
+}
+
+export interface ConsulBundleScope {
+ datacenter: string;
+ namespace: string;
+ partition: string;
+}
+
+export interface ConsulBundleEntry {
+ key: string;
+ value: KvValue;
+ flags: KvInt64;
+ createIndex: KvInt64 | null;
+ modifyIndex: KvInt64 | null;
+}
+
+export interface ConsulKvBundle {
+ format: "dbx-consul-kv-bundle";
+ version: 1;
+ exportedAtUnixMs: number;
+ prefix: string;
+ scopeKind: ConsulExportScopeKind;
+ source: ConsulBundleScope;
+ entries: ConsulBundleEntry[];
+}
+
+export type ConsulImportConflictPolicy = "abort" | "skip" | "cas";
+export type ConsulImportOperation = "create" | "update" | "unchanged" | "skipped" | "conflict" | "locked";
+
+export interface ConsulImportRequest {
+ bundle: ConsulKvBundle;
+ policy: ConsulImportConflictPolicy;
+ previewId?: string | null;
+}
+
+export interface ConsulImportPreviewRow {
+ key: string;
+ operation: ConsulImportOperation;
+ expectedModifyIndex: KvInt64 | null;
+ targetSession: string | null;
+ reason: string | null;
+}
+
+export interface ConsulImportPreview {
+ previewId: string;
+ rows: ConsulImportPreviewRow[];
+ canApply: boolean;
+ creates: number;
+ updates: number;
+ unchanged: number;
+ skipped: number;
+ conflicts: number;
+}
+
+export type ConsulImportOutcome = "succeeded" | "conflicted" | "skipped" | "failed";
+
+export interface ConsulImportResultItem {
+ key: string;
+ outcome: ConsulImportOutcome;
+ message: string | null;
+ batch: number | null;
+ opIndex: number | null;
+}
+
+export interface ConsulImportReport {
+ items: ConsulImportResultItem[];
+ succeeded: number;
+ conflicted: number;
+ skipped: number;
+ failed: number;
+ atomic: boolean;
+}
+
+export interface ConsulDeleteCandidate {
+ key: string;
+ modifyIndex: KvInt64;
+ session: string | null;
+}
+
+export interface ConsulDeletePrefixPreview {
+ prefix: string;
+ candidates: ConsulDeleteCandidate[];
+ filteredByAcls: boolean | null;
+ complete: boolean;
+ canExecute: boolean;
+ locked: number;
+}
+
+export interface ConsulDeletePrefixRequest {
+ prefix: string;
+ expected: ConsulDeleteCandidate[];
+}
+
+export type ConsulDeleteOutcome = "succeeded" | "conflicted" | "failed";
+
+export interface ConsulDeleteResultItem {
+ key: string;
+ outcome: ConsulDeleteOutcome;
+ message: string | null;
+ batch: number | null;
+ opIndex: number | null;
+}
+
+export type ConsulTxnVerb = "get" | "get-tree" | "set" | "cas" | "delete" | "delete-cas" | "delete-tree" | "lock" | "unlock" | "check-index" | "check-not-exists" | "check-session";
+
+export interface ConsulTxnKvOperation {
+ verb: ConsulTxnVerb;
+ key: string;
+ value: KvValue | null;
+ flags: KvInt64 | null;
+ index: KvInt64 | null;
+ session: string | null;
+}
+
+export interface ConsulTxnRequest {
+ operations: ConsulTxnKvOperation[];
+}
+export interface ConsulTxnError {
+ opIndex: number;
+ message: string;
+}
+export interface ConsulTxnKvResult {
+ key: string;
+ value: KvValue | null;
+ flags: KvInt64;
+ createIndex: KvInt64;
+ modifyIndex: KvInt64;
+ lockIndex: KvInt64;
+ session: string | null;
+}
+export interface ConsulTxnResult {
+ committed: boolean;
+ errors: ConsulTxnError[];
+ results: ConsulTxnKvResult[];
+}
+
+export interface ConsulBlockingRequest {
+ operationId: string;
+ generation: number;
+ key: string;
+ prefix: boolean;
+ index: KvInt64 | null;
+ waitSeconds: number;
+}
+
+export interface ConsulBlockingResponse {
+ entries: ConsulKvRecord[];
+ metadata: ConsulResponseMetadata;
+ changed: boolean;
+ timedOut: boolean;
+ indexReset: boolean;
+}
+
+export type ConsulDomainWatchTarget =
+ | { kind: "catalogNodes" }
+ | { kind: "catalogServices" }
+ | { kind: "catalogServiceNodes"; service: string }
+ | { kind: "catalogNodeServices"; node: string }
+ | { kind: "healthNode"; node: string }
+ | { kind: "healthServiceChecks"; service: string }
+ | { kind: "healthServiceInstances"; service: string; passing: boolean | null }
+ | { kind: "healthState"; state: string };
+
+export interface ConsulDomainWatchRequest {
+ operationId: string;
+ generation: number;
+ target: ConsulDomainWatchTarget;
+ index: KvInt64 | null;
+ waitSeconds: number;
+}
+
+export type ConsulDomainWatchItems = ConsulCatalogNode[] | Record<string, string[]> | ConsulCatalogServiceNode[] | ConsulNodeServices | ConsulHealthCheck[] | ConsulServiceInstance[];
+
+export interface ConsulDomainWatchResponse<T extends ConsulDomainWatchItems> {
+ items: T;
+ metadata: ConsulResponseMetadata;
+ changed: boolean;
+ timedOut: boolean;
+ indexReset: boolean;
+}
+
+export interface ConsulWatchEvent {
+ connectionId: string;
+ operationId: string;
+ generation: number;
+ result: ConsulBlockingResponse | null;
+ error: string | null;
+}
+
+export interface ConsulPreparedQueryService {
+ Service: string;
+ Near: string;
+ OnlyPassing: boolean;
+ Tags: string[];
+}
+export interface ConsulPreparedQuery {
+ ID: string;
+ Name: string;
+ Session: string;
+ Service: ConsulPreparedQueryService;
+ CreateIndex: KvInt64;
+ ModifyIndex: KvInt64;
+}
+export interface ConsulPreparedQueryInput {
+ name: string;
+ session: string;
+ service: ConsulPreparedQueryService;
+}
+export interface ConsulPreparedQueryExecuteRequest {
+ query: string;
+ limit: number;
+ connect: boolean;
+}
+export interface ConsulPreparedNodeIdentity {
+ Node: string;
+ Address: string;
+ Datacenter: string;
+}
+export interface ConsulPreparedServiceIdentity {
+ ID: string;
+ Service: string;
+ Address: string;
+ Port: number;
+ Tags: string[];
+}
+export interface ConsulPreparedQueryNode {
+ Node: ConsulPreparedNodeIdentity;
+ Service: ConsulPreparedServiceIdentity;
+}
+export interface ConsulPreparedQueryExecuteResponse {
+ Service: string;
+ Nodes: ConsulPreparedQueryNode[];
+ DNS: { TTL: string };
+ Datacenter: string;
+}
+export interface ConsulEventFireRequest {
+ name: string;
+ payloadBase64: string;
+ nodeFilter: string;
+ serviceFilter: string;
+ tagFilter: string;
+}
+export interface ConsulEvent {
+ ID: string;
+ Name: string;
+ Payload: string | null;
+ NodeFilter: string;
+ ServiceFilter: string;
+ TagFilter: string;
+ LTime: KvInt64;
+}
+export interface ConsulCoordinate {
+ Node: string;
+ Segment: string;
+ Coord: { Vec: number[]; Error: number; Adjustment: number; Height: number };
+}
+
+export type ConsulOperatorReadKind = "autopilot_configuration" | "autopilot_health" | "autopilot_state" | "raft_configuration" | "usage" | "license" | "audit";
+export interface ConsulOperatorDocument {
+ kind: string;
+ fields: Array<{ name: string; value: string }>;
+}
+export interface ConsulAutopilotUpdate {
+ CleanupDeadServers?: boolean | null;
+ LastContactThreshold?: string | null;
+ MaxTrailingLogs?: number | null;
+ MinQuorum?: number | null;
+ ServerStabilizationTime?: string | null;
+ RedundancyZoneTag?: string | null;
+ DisableUpgradeMigration?: boolean | null;
+ UpgradeVersionTag?: string | null;
+}
+export interface ConsulSnapshot {
+ dataBase64: string;
+ sizeBytes: number;
+ datacenter: string;
+}
+export interface ConsulSnapshotRestoreRequest {
+ snapshotBase64: string;
+ targetDatacenter: string;
+ confirmation: string;
+}
+export interface ConsulRaftWriteRequest {
+ serverId: string | null;
+ address: string | null;
+ confirmation: string;
+}
+export interface ConsulKeyringWriteRequest {
+ operation: "install" | "use" | "remove";
+ key: string;
+ confirmation: string;
+}
+export interface ConsulLicenseWriteRequest {
+ license: string;
+ confirmation: string;
+}
+
+export interface ConsulDeletePrefixReport {
+ items: ConsulDeleteResultItem[];
+ succeeded: number;
+ conflicted: number;
+ failed: number;
+ atomic: boolean;
+}
+
+export interface ConsulResponseMetadata {
+ index: KvInt64 | null;
+ filteredByAcls: boolean | null;
+ knownLeader: boolean | null;
+ lastContact: KvInt64 | null;
+ queryBackend: string | null;
+}
+
+export interface ConsulListResponse<T> {
+ items: T;
+ metadata: ConsulResponseMetadata;
+}
+
+export interface ConsulReadOptions {
+ filter?: string | null;
+ near?: string | null;
+ index?: string | null;
+ wait?: string | null;
+}
+
+export interface ConsulAgentIdentity {
+ node: string;
+ address: string;
+ datacenter: string;
+ version: string | null;
+ server: boolean | null;
+ revision: string | null;
+ segment: string | null;
+}
+
+export interface ConsulAgentMember {
+ Name: string;
+ Addr: string;
+ Port: number;
+ Tags: Record<string, string>;
+ Status: number;
+}
+
+export interface ConsulCatalogNode {
+ ID: string;
+ Node: string;
+ Address: string;
+ Datacenter: string;
+ TaggedAddresses: Record<string, string>;
+ NodeMeta: Record<string, string>;
+ CreateIndex: number;
+ ModifyIndex: number;
+}
+
+export interface ConsulServiceAddress {
+ Address: string;
+ Port: number;
+}
+
+export interface ConsulServiceWeights {
+ Passing: number;
+ Warning: number;
+}
+
+export interface ConsulCatalogServiceNode {
+ ID: string;
+ Node: string;
+ Address: string;
+ Datacenter: string;
+ TaggedAddresses: Record<string, string>;
+ NodeMeta: Record<string, string>;
+ ServiceKind: string;
+ ServiceID: string;
+ ServiceName: string;
+ ServiceTags: string[];
+ ServiceAddress: string;
+ ServicePort: number;
+ ServiceMeta: Record<string, string>;
+ ServiceTaggedAddresses: Record<string, ConsulServiceAddress>;
+ ServiceWeights: ConsulServiceWeights;
+ CreateIndex: number;
+ ModifyIndex: number;
+}
+
+export interface ConsulCatalogService {
+ ID: string;
+ Service: string;
+ Tags: string[];
+ Address: string;
+ TaggedAddresses: Record<string, ConsulServiceAddress>;
+ Meta: Record<string, string>;
+ Port: number;
+ Weights: ConsulServiceWeights;
+}
+
+export interface ConsulNodeServices {
+ Node: ConsulCatalogNode;
+ Services: Record<string, ConsulCatalogService>;
+}
+
+export interface ConsulHealthCheckDefinition {
+ HTTP: string;
+ TCP: string;
+ GRPC: string;
+ Interval: string;
+ Timeout: string;
+ TTL: string;
+}
+
+export interface ConsulHealthCheck {
+ Node: string;
+ CheckID: string;
+ Name: string;
+ Status: "passing" | "warning" | "critical" | string;
+ Notes: string;
+ Output: string;
+ ServiceID: string;
+ ServiceName: string;
+ ServiceTags: string[];
+ Type: string;
+ ExposedPort: number;
+ Definition: ConsulHealthCheckDefinition;
+ CreateIndex: number;
+ ModifyIndex: number;
+ Maintenance: boolean;
+}
+
+export interface ConsulHealthService {
+ ID: string;
+ Service: string;
+ Tags: string[];
+ Address: string;
+ TaggedAddresses: Record<string, ConsulServiceAddress>;
+ Meta: Record<string, string>;
+ Port: number;
+ Weights: ConsulServiceWeights;
+ Kind: string;
+}
+
+export interface ConsulServiceInstance {
+ Node: ConsulCatalogNode;
+ Service: ConsulHealthService;
+ Checks: ConsulHealthCheck[];
+}
+
+export interface ConsulAgentService {
+ Kind: string;
+ ID: string;
+ Service: string;
+ Tags: string[];
+ Meta: Record<string, string>;
+ Port: number;
+ Address: string;
+ TaggedAddresses: Record<string, ConsulServiceAddress>;
+ Weights: ConsulServiceWeights;
+ EnableTagOverride: boolean;
+ Datacenter: string;
+}
+
+export interface ConsulAgentProxyRegistration {
+ destinationServiceName: string;
+ destinationServiceId: string;
+ localServiceAddress: string;
+ localServicePort: number;
+ localServicePorts?: string[];
+ localServiceSocketPath?: string;
+ mode?: string;
+ transparentProxy?: ConsulAgentTransparentProxy | null;
+ config?: Record<string, unknown>;
+ upstreams: ConsulAgentUpstream[];
+ meshGateway?: ConsulAgentMeshGateway | null;
+ expose?: ConsulAgentExpose | null;
+}
+
+export interface ConsulAgentTransparentProxy {
+ outboundListenerPort: number;
+ dialedDirectly: boolean;
+}
+
+export interface ConsulAgentMeshGateway {
+ mode: "" | "local" | "remote" | "none" | string;
+}
+
+export interface ConsulAgentExposePath {
+ path: string;
+ protocol: "http" | "http2" | string;
+ localPathPort: number;
+ listenerPort: number;
+}
+
+export interface ConsulAgentExpose {
+ checks: boolean;
+ paths: ConsulAgentExposePath[];
+}
+
+export interface ConsulAgentUpstream {
+ destinationType: "service" | "prepared_query" | string;
+ destinationName: string;
+ destinationPort?: number;
+ destinationNamespace?: string;
+ destinationPartition?: string;
+ destinationPeer?: string;
+ localBindAddress: string;
+ localBindPort: number;
+ localBindSocketPath?: string;
+ localBindSocketMode?: string;
+ datacenter: string;
+ meshGateway?: ConsulAgentMeshGateway | null;
+ config?: Record<string, unknown>;
+}
+
+export interface ConsulAgentServicePort {
+ name: string;
+ port: number;
+ default: boolean;
+}
+
+export interface ConsulAgentConnectRegistration {
+ native: boolean;
+ sidecarService?: ConsulAgentServiceRegistration | null;
+}
+
+export type ConsulAgentCheckDefinition =
+ | { type: "http"; url: string; method: string; interval: string; timeout: string; tlsSkipVerify: boolean }
+ | { type: "tcp"; address: string; interval: string; timeout: string }
+ | { type: "grpc"; address: string; interval: string; timeout: string; tls: boolean }
+ | { type: "ttl"; ttl: string }
+ | { type: "docker"; containerId: string; shell: string; args: string[]; interval: string; timeout: string }
+ | { type: "script"; args: string[]; interval: string; timeout: string };
+
+export interface ConsulAgentCheckRegistration {
+ id: string;
+ name: string;
+ notes: string;
+ serviceId: string;
+ status: string;
+ definition: ConsulAgentCheckDefinition;
+}
+
+export interface ConsulAgentServiceRegistration {
+ id: string;
+ name: string;
+ tags: string[];
+ address: string;
+ port: number;
+ meta: Record<string, string>;
+ weights: ConsulServiceWeights;
+ kind: string;
+ enableTagOverride: boolean;
+ taggedAddresses?: Record<string, ConsulServiceAddress>;
+ ports?: ConsulAgentServicePort[];
+ proxy: ConsulAgentProxyRegistration | null;
+ connect?: ConsulAgentConnectRegistration | null;
+ checks: ConsulAgentCheckRegistration[];
+}
+
+export interface ConsulAgentWriteResult {
+ target: ConsulAgentIdentity;
+}
+
+export type ConsulCheckStatus = "passing" | "warning" | "critical";
+
+export interface ConsulSession {
+ ID: string;
+ Name: string;
+ Node: string;
+ LockDelay: number;
+ Behavior: "release" | "delete" | string;
+ TTL: string;
+ NodeChecks: string[];
+ ServiceChecks: ConsulSessionServiceCheck[];
+ Namespace: string;
+ Partition: string;
+ CreateIndex: number;
+ ModifyIndex: number;
+}
+
+export interface ConsulSessionServiceCheck {
+ ID: string;
+ Namespace: string;
+}
+
+export interface ConsulSessionCreateRequest {
+ name: string;
+ node: string;
+ lockDelay?: string | null;
+ behavior: "release" | "delete";
+ ttl?: string | null;
+ nodeChecks: string[];
+ serviceChecks: ConsulSessionServiceCheck[];
+}
+
+export interface ConsulSessionHeldKey {
+ key: string;
+ modifyIndex: KvInt64;
+}
+export interface ConsulSessionKeysResponse {
+ items: ConsulKvRecord[];
+ complete: boolean;
+ filteredByAcls: boolean;
+}
+export interface ConsulSessionDestroyImpact {
+ session: ConsulSession;
+ heldKeys: ConsulSessionHeldKey[];
+ complete: boolean;
+ filteredByAcls: boolean;
+}
+export interface ConsulSessionDestroyRequest {
+ id: string;
+ expectedBehavior: string;
+ expectedHeldKeys: ConsulSessionHeldKey[];
+}
+
+export interface ConsulLockRequest {
+ key: string;
+ session: string;
+ value: KvValue;
+ flags?: KvInt64 | null;
+ expectedModifyIndex?: KvInt64 | null;
+}
+
+export interface ConsulLockResponse {
+ acquired: boolean;
+ key: string;
+ session: string;
+}
+
+export type ConsulAclKind = "token" | "policy" | "role" | "authMethod" | "bindingRule" | "templatedPolicy";
+export interface ConsulAclLink {
+ ID?: string;
+ Name?: string;
+}
+export interface ConsulAclToken {
+ AccessorID?: string;
+ SecretID?: string;
+ Description?: string;
+ Local?: boolean;
+ AuthMethod?: string;
+ Policies?: ConsulAclLink[];
+ Roles?: ConsulAclLink[];
+ ServiceIdentities?: unknown[];
+ NodeIdentities?: unknown[];
+ TemplatedPolicies?: unknown[];
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulAclPolicy {
+ ID?: string;
+ Name?: string;
+ Description?: string;
+ Rules?: string;
+ Datacenters?: string[];
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulAclRole {
+ ID?: string;
+ Name?: string;
+ Description?: string;
+ Policies?: ConsulAclLink[];
+ ServiceIdentities?: unknown[];
+ NodeIdentities?: unknown[];
+ TemplatedPolicies?: unknown[];
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulAclAuthMethod {
+ Name?: string;
+ Type?: string;
+ DisplayName?: string;
+ Description?: string;
+ MaxTokenTTL?: string;
+ TokenLocality?: string;
+ Config?: unknown;
+}
+export interface ConsulAclBindingRule {
+ ID?: string;
+ Description?: string;
+ AuthMethod?: string;
+ Selector?: string;
+ BindType?: string;
+ BindName?: string;
+ BindVars?: unknown;
+}
+export interface ConsulAclTemplatedPolicy {
+ TemplateName?: string;
+ Schema?: unknown;
+}
+export type ConsulAclList =
+ | { kind: "token"; items: ConsulAclToken[] }
+ | { kind: "policy"; items: ConsulAclPolicy[] }
+ | { kind: "role"; items: ConsulAclRole[] }
+ | { kind: "authMethod"; items: ConsulAclAuthMethod[] }
+ | { kind: "bindingRule"; items: ConsulAclBindingRule[] }
+ | { kind: "templatedPolicy"; items: ConsulAclTemplatedPolicy[] };
+export type ConsulAclItem =
+ | { kind: "token"; item: ConsulAclToken }
+ | { kind: "policy"; item: ConsulAclPolicy }
+ | { kind: "role"; item: ConsulAclRole }
+ | { kind: "authMethod"; item: ConsulAclAuthMethod }
+ | { kind: "bindingRule"; item: ConsulAclBindingRule }
+ | { kind: "templatedPolicy"; item: ConsulAclTemplatedPolicy };
+export type ConsulAclWrite = Exclude<ConsulAclItem, { kind: "templatedPolicy" }>;
+export interface ConsulAclReferences {
+ tokenAccessorIds: string[];
+ roleIds: string[];
+ bindingRuleIds: string[];
+ complete: boolean;
+ filteredByAcls: boolean;
+}
+
+export type ConsulEnterpriseKind = "namespace" | "partition";
+export interface ConsulNamespaceAcls {
+ PolicyDefaults?: unknown[];
+ RoleDefaults?: unknown[];
+}
+export interface ConsulNamespace {
+ Name?: string;
+ Partition?: string;
+ Description?: string;
+ Meta?: Record<string, string>;
+ ACLs?: ConsulNamespaceAcls;
+ DeletedAt?: string | null;
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulPartition {
+ Name?: string;
+ Description?: string;
+ Meta?: Record<string, string>;
+ DeletedAt?: string | null;
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export type ConsulEnterpriseList = { kind: "namespace"; items: ConsulNamespace[] } | { kind: "partition"; items: ConsulPartition[] };
+export type ConsulEnterpriseItem = { kind: "namespace"; item: ConsulNamespace } | { kind: "partition"; item: ConsulPartition };
+export type ConsulEnterpriseWrite = ConsulEnterpriseItem;
+export interface ConsulScopeImpact {
+ services: number;
+ nodes: number;
+ kvKeys: number;
+ healthChecks: number;
+ sessions: number;
+ configEntries: number;
+ intentions: number;
+ peerings: number;
+ namespaces: number;
+ aclTokens: number;
+ aclPolicies: number;
+ aclRoles: number;
+ aclAuthMethods: number;
+ aclBindingRules: number;
+ complete: boolean;
+ filteredByAcls: boolean;
+ unavailableResources: string[];
+}
+
+export interface ConsulConfigEntry {
+ kind: string;
+ name: string;
+ modifyIndex: number;
+ raw: Record<string, unknown>;
+}
+export interface ConsulConfigEntryApply {
+ kind: string;
+ name: string;
+ expectedModifyIndex: number;
+ raw: Record<string, unknown>;
+}
+export interface ConsulIntention {
+ ID?: string;
+ Description?: string;
+ SourceName?: string;
+ DestinationName?: string;
+ SourceNamespace?: string;
+ DestinationNamespace?: string;
+ SourcePartition?: string;
+ DestinationPartition?: string;
+ Action?: string;
+ Permissions?: unknown[];
+ Precedence?: number;
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulIntentionMatchRequest {
+ by: "source" | "destination";
+ name: string;
+}
+export interface ConsulIntentionExactRequest {
+ source: string;
+ destination: string;
+}
+export interface ConsulIntentionCheckRequest {
+ source: string;
+ destination: string;
+}
+export interface ConsulIntentionCheckResponse {
+ Allowed: boolean;
+}
+export interface ConsulDiscoveryChain {
+ ServiceName?: string;
+ Namespace?: string;
+ Partition?: string;
+ Datacenter?: string;
+ Protocol?: string;
+ StartNode?: string;
+ Nodes?: Record<string, unknown>;
+ Targets?: Record<string, unknown>;
+}
+export interface ConsulPeering {
+ ID?: string;
+ Name?: string;
+ Partition?: string;
+ State?: string;
+ PeerID?: string;
+ PeerServerName?: string;
+ PeerServerAddresses?: string[];
+ ImportedServices?: string[];
+ ExportedServices?: string[];
+ CreateIndex?: number;
+ ModifyIndex?: number;
+}
+export interface ConsulPeeringGenerateRequest {
+ PeerName: string;
+ Partition?: string;
+ Meta?: unknown;
+}
+export interface ConsulPeeringToken {
+ PeeringToken: string;
+}
+export interface ConsulPeeringEstablishRequest {
+ PeerName: string;
+ PeeringToken: string;
+ Partition?: string;
+}
+export interface ConsulExportedService {
+ Service?: string;
+ Namespace?: string;
+ Partition?: string;
+ Consumers?: unknown[];
+}
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 2ed3409db3..30cf2a9d1e 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -71,7 +71,8 @@ export type DatabaseType =
| "jdbc"
| "mq"
| "mqtt"
- | "nacos";
+ | "nacos"
+ | "consul";
export function isElasticsearchCompatibleDatabaseType(dbType?: DatabaseType): boolean {
return dbType === "elasticsearch" || dbType === "easysearch";
@@ -841,6 +842,8 @@ export type TreeNodeType =
| "etcd-dashboard"
| "etcd-access-control"
| "zookeeper-root"
+ | "consul-root"
+ | "consul-overview"
| "mongo-db"
| "mongo-gridfs"
| "mongo-buckets"
@@ -1045,6 +1048,8 @@ export interface QueryTab {
| "etcd-dashboard"
| "etcd-access-control"
| "zookeeper"
+ | "consul"
+ | "consul-overview"
| "mq"
| "mqtt"
| "nacos"
diff --git a/crates/dbx-core/src/agent_kv.rs b/crates/dbx-core/src/agent_kv.rs
index bb85468c5b..fb2920fd0b 100644
--- a/crates/dbx-core/src/agent_kv.rs
+++ b/crates/dbx-core/src/agent_kv.rs
@@ -103,6 +103,12 @@ pub struct KvKeyMetadata {
pub ephemeral_owner: Option<i64>,
pub data_length: Option<u64>,
pub num_children: Option<i64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub flags: Option<KvInt64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub lock_index: Option<KvInt64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub session: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -138,6 +144,8 @@ pub struct KvListPrefixResponse {
pub keys: Vec<KvKeySummary>,
pub continuation: Option<String>,
pub revision: Option<KvInt64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub filtered_by_acls: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -205,6 +213,8 @@ pub struct KvPutOptions {
pub expected_mod_revision: Option<KvInt64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expected_create_revision: Option<KvInt64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub flags: Option<KvInt64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index 7c752c97cb..6ac48970db 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -118,6 +118,7 @@ pub enum PoolKind {
MessageQueue,
/// Nacos admin connection marker.
Nacos,
+ Consul(crate::consul::ConsulClient),
/// MQTT broker connection with an active client.
#[cfg(feature = "mq-admin")]
Mqtt(Arc<super::mqtt::client::MqttClient>),
@@ -2039,6 +2040,17 @@ impl AppState {
adapter.test_connection().await?;
PoolKind::Nacos
}
+ DatabaseType::Consul => {
+ let mut consul_config = crate::consul::ConsulConfig::from_connection(&db_config)?;
+ let original_host = consul_config.base_url.host_str().unwrap_or_default();
+ let original_port = consul_config.base_url.port_or_known_default().unwrap_or(db_config.port);
+ if host != original_host || port != original_port {
+ consul_config = consul_config.with_connect_override(&host, port);
+ }
+ let client = crate::consul::ConsulClient::new(consul_config).await?;
+ client.probe().await?;
+ PoolKind::Consul(client)
+ }
agent_connection_pool_database_type!() => {
let connect_params = agent_connect_params_with_role(
&db_config,
@@ -3077,7 +3089,8 @@ impl AppState {
| PoolKind::DuckDbWorker(_)
| PoolKind::ExternalDriver { .. }
| PoolKind::MessageQueue
- | PoolKind::Nacos => false,
+ | PoolKind::Nacos
+ | PoolKind::Consul(_) => false,
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => false,
}
@@ -3969,7 +3982,8 @@ impl AppState {
| PoolKind::DuckDbWorker(_)
| PoolKind::ExternalDriver { .. }
| PoolKind::MessageQueue
- | PoolKind::Nacos => true,
+ | PoolKind::Nacos
+ | PoolKind::Consul(_) => true,
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => true,
PoolKind::Redis(_) => unreachable!("Redis handled separately"),
@@ -4396,6 +4410,8 @@ fn connection_remote_endpoint(config: &ConnectionConfig) -> (String, u16) {
parse_mqtt_broker_host_port(config).unwrap_or_else(|| (config.host.clone(), config.port))
} else if config.db_type == DatabaseType::Nacos {
parse_nacos_server_host_port(config).unwrap_or_else(|| (config.host.clone(), config.port))
+ } else if config.db_type == DatabaseType::Consul {
+ parse_consul_server_host_port(config).unwrap_or_else(|| (config.host.clone(), config.port))
} else {
(config.host.clone(), config.port)
}
@@ -4467,6 +4483,21 @@ fn parse_nacos_server_host_port(config: &ConnectionConfig) -> Option<(String, u1
Some((host, port))
}
+fn parse_consul_server_host_port(config: &ConnectionConfig) -> Option<(String, u16)> {
+ let value = config
+ .external_config
+ .as_ref()?
+ .get("serverAddr")
+ .or_else(|| config.external_config.as_ref()?.get("server_addr"))?
+ .as_str()?
+ .trim();
+ if value.is_empty() {
+ return None;
+ }
+ let url = reqwest::Url::parse(value).ok()?;
+ Some((url.host_str()?.to_string(), url.port_or_known_default()?))
+}
+
fn parse_mqtt_broker_host_port(config: &ConnectionConfig) -> Option<(String, u16)> {
let value = config
.external_config
@@ -4618,6 +4649,7 @@ fn clone_pool_kind(pool: &PoolKind) -> PoolKind {
}
PoolKind::MessageQueue => PoolKind::MessageQueue,
PoolKind::Nacos => PoolKind::Nacos,
+ PoolKind::Consul(client) => PoolKind::Consul(client.clone()),
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(client) => PoolKind::Mqtt(Arc::clone(client)),
PoolKind::Redis(_) => panic!("clone_pool_kind not supported for Redis — handled separately"),
@@ -4679,6 +4711,7 @@ async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
}
PoolKind::MessageQueue => {}
PoolKind::Nacos => {}
+ PoolKind::Consul(_) => {}
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(client) => {
// 发送 DISCONNECT 并等待事件循环任务结束
diff --git a/crates/dbx-core/src/consul/acl.rs b/crates/dbx-core/src/consul/acl.rs
new file mode 100644
index 0000000000..462be2781d
--- /dev/null
+++ b/crates/dbx-core/src/consul/acl.rs
@@ -0,0 +1,587 @@
+use std::fmt;
+
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ConsulClient};
+use super::response::{decode_json_response, ConsulResponseMetadata};
+
+/// Sensitive Consul value. Deliberately does not implement `Debug`.
+#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct ConsulSecret(String);
+
+impl ConsulSecret {
+ pub fn expose_once(self) -> String {
+ self.0
+ }
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ConsulAclKind {
+ Token,
+ Policy,
+ Role,
+ AuthMethod,
+ BindingRule,
+ TemplatedPolicy,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclLink {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+}
+
+#[derive(Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclToken {
+ #[serde(rename = "AccessorID", default)]
+ pub accessor_id: String,
+ #[serde(rename = "SecretID", default, skip_serializing_if = "Option::is_none")]
+ pub secret_id: Option<ConsulSecret>,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub local: bool,
+ #[serde(default)]
+ pub auth_method: String,
+ #[serde(default)]
+ pub policies: Vec<ConsulAclLink>,
+ #[serde(default)]
+ pub roles: Vec<ConsulAclLink>,
+ #[serde(default)]
+ pub service_identities: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub node_identities: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub templated_policies: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclPolicy {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub rules: String,
+ #[serde(default)]
+ pub datacenters: Vec<String>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclRole {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub policies: Vec<ConsulAclLink>,
+ #[serde(default)]
+ pub service_identities: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub node_identities: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub templated_policies: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclAuthMethod {
+ #[serde(default)]
+ pub name: String,
+ #[serde(rename = "Type", default)]
+ pub method_type: String,
+ #[serde(default)]
+ pub display_name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(rename = "MaxTokenTTL", default)]
+ pub max_token_ttl: String,
+ #[serde(default)]
+ pub token_locality: String,
+ #[serde(default)]
+ pub config: serde_json::Value,
+}
+
+impl fmt::Debug for ConsulAclAuthMethod {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_struct("ConsulAclAuthMethod")
+ .field("name", &self.name)
+ .field("method_type", &self.method_type)
+ .field("display_name", &self.display_name)
+ .field("description", &self.description)
+ .field("max_token_ttl", &self.max_token_ttl)
+ .field("token_locality", &self.token_locality)
+ .field("config", &"[REDACTED]")
+ .finish()
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclBindingRule {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub auth_method: String,
+ #[serde(default)]
+ pub selector: String,
+ #[serde(default)]
+ pub bind_type: String,
+ #[serde(default)]
+ pub bind_name: String,
+ #[serde(default)]
+ pub bind_vars: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclTemplatedPolicy {
+ #[serde(default)]
+ pub template_name: String,
+ #[serde(default)]
+ pub schema: serde_json::Value,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "items", rename_all = "camelCase")]
+pub enum ConsulAclList {
+ Token(Vec<ConsulAclToken>),
+ Policy(Vec<ConsulAclPolicy>),
+ Role(Vec<ConsulAclRole>),
+ AuthMethod(Vec<ConsulAclAuthMethod>),
+ BindingRule(Vec<ConsulAclBindingRule>),
+ TemplatedPolicy(Vec<ConsulAclTemplatedPolicy>),
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "item", rename_all = "camelCase")]
+pub enum ConsulAclItem {
+ Token(ConsulAclToken),
+ Policy(ConsulAclPolicy),
+ Role(ConsulAclRole),
+ AuthMethod(ConsulAclAuthMethod),
+ BindingRule(ConsulAclBindingRule),
+ TemplatedPolicy(ConsulAclTemplatedPolicy),
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "item", rename_all = "camelCase")]
+pub enum ConsulAclWrite {
+ Token(ConsulAclToken),
+ Policy(ConsulAclPolicy),
+ Role(ConsulAclRole),
+ AuthMethod(ConsulAclAuthMethod),
+ BindingRule(ConsulAclBindingRule),
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAclReferences {
+ pub token_accessor_ids: Vec<String>,
+ pub role_ids: Vec<String>,
+ pub binding_rule_ids: Vec<String>,
+ pub complete: bool,
+ pub filtered_by_acls: bool,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAclTokenClone {
+ #[serde(default)]
+ pub description: String,
+}
+
+pub async fn consul_acl_token_self_core(state: &AppState, connection_id: &str) -> Result<ConsulAclToken, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/acl/token/self")?;
+ client.request_json(Method::GET, url, None::<&()>, true, "read current ACL token").await.map(without_token_secret)
+}
+
+pub async fn consul_acl_token_clone_core(
+ state: &AppState,
+ connection_id: &str,
+ accessor_id: &str,
+ request: ConsulAclTokenClone,
+) -> Result<ConsulAclToken, String> {
+ super::ensure_writable(state, connection_id, "ACL token clone").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let accessor_id = percent_encoding::utf8_percent_encode(accessor_id, percent_encoding::NON_ALPHANUMERIC);
+ let url = client.api_url(&format!("/v1/acl/token/{accessor_id}/clone"))?;
+ client.request_json(Method::PUT, url, Some(&request), false, "clone ACL token").await
+}
+
+pub async fn consul_acl_list_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulAclKind,
+) -> Result<ConsulAclList, String> {
+ let client = client_for_state(state, connection_id).await?;
+ match kind {
+ ConsulAclKind::Token => Ok(ConsulAclList::Token(
+ list::<ConsulAclToken>(&client, "/v1/acl/tokens", "list ACL tokens")
+ .await?
+ .into_iter()
+ .map(without_token_secret)
+ .collect(),
+ )),
+ ConsulAclKind::Policy => {
+ Ok(ConsulAclList::Policy(list(&client, "/v1/acl/policies", "list ACL policies").await?))
+ }
+ ConsulAclKind::Role => Ok(ConsulAclList::Role(list(&client, "/v1/acl/roles", "list ACL roles").await?)),
+ ConsulAclKind::AuthMethod => Ok(ConsulAclList::AuthMethod(
+ list::<ConsulAclAuthMethod>(&client, "/v1/acl/auth-methods", "list ACL auth methods")
+ .await?
+ .into_iter()
+ .map(without_auth_method_secrets)
+ .collect(),
+ )),
+ ConsulAclKind::BindingRule => {
+ Ok(ConsulAclList::BindingRule(list(&client, "/v1/acl/binding-rules", "list ACL binding rules").await?))
+ }
+ ConsulAclKind::TemplatedPolicy => Ok(ConsulAclList::TemplatedPolicy(
+ list(&client, "/v1/acl/templated-policies", "list ACL templated policies").await?,
+ )),
+ }
+}
+
+pub async fn consul_acl_get_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulAclKind,
+ id: &str,
+) -> Result<ConsulAclItem, String> {
+ let client = client_for_state(state, connection_id).await?;
+ if kind == ConsulAclKind::TemplatedPolicy {
+ return list::<ConsulAclTemplatedPolicy>(&client, "/v1/acl/templated-policies", "list ACL templated policies")
+ .await?
+ .into_iter()
+ .find(|policy| policy.template_name == id)
+ .map(ConsulAclItem::TemplatedPolicy)
+ .ok_or_else(|| "CONSUL_ACL_NOT_FOUND: Templated policy not found".to_string());
+ }
+ let url = client.api_url(&item_path(kind, id)?)?;
+ match kind {
+ ConsulAclKind::Token => Ok(ConsulAclItem::Token(without_token_secret(
+ client.request_json(Method::GET, url, None::<&()>, true, "read ACL token").await?,
+ ))),
+ ConsulAclKind::Policy => Ok(ConsulAclItem::Policy(
+ client.request_json(Method::GET, url, None::<&()>, true, "read ACL policy").await?,
+ )),
+ ConsulAclKind::Role => {
+ Ok(ConsulAclItem::Role(client.request_json(Method::GET, url, None::<&()>, true, "read ACL role").await?))
+ }
+ ConsulAclKind::AuthMethod => Ok(ConsulAclItem::AuthMethod(without_auth_method_secrets(
+ client.request_json(Method::GET, url, None::<&()>, true, "read ACL auth method").await?,
+ ))),
+ ConsulAclKind::BindingRule => Ok(ConsulAclItem::BindingRule(
+ client.request_json(Method::GET, url, None::<&()>, true, "read ACL binding rule").await?,
+ )),
+ ConsulAclKind::TemplatedPolicy => unreachable!("templated policy reads are handled by the collection"),
+ }
+}
+
+pub async fn consul_acl_apply_core(
+ state: &AppState,
+ connection_id: &str,
+ id: Option<&str>,
+ value: ConsulAclWrite,
+) -> Result<ConsulAclItem, String> {
+ super::ensure_writable(state, connection_id, "ACL write").await?;
+ let client = client_for_state(state, connection_id).await?;
+ match value {
+ ConsulAclWrite::Token(item) => Ok(ConsulAclItem::Token(apply(&client, ConsulAclKind::Token, id, &item).await?)),
+ ConsulAclWrite::Policy(item) => {
+ Ok(ConsulAclItem::Policy(apply(&client, ConsulAclKind::Policy, id, &item).await?))
+ }
+ ConsulAclWrite::Role(item) => Ok(ConsulAclItem::Role(apply(&client, ConsulAclKind::Role, id, &item).await?)),
+ ConsulAclWrite::AuthMethod(mut item) => {
+ if let Some(id) = id {
+ let url = client.api_url(&item_path(ConsulAclKind::AuthMethod, id)?)?;
+ let existing: ConsulAclAuthMethod = client
+ .request_json(Method::GET, url, None::<&()>, true, "read ACL auth method before update")
+ .await?;
+ merge_missing_sensitive_config(&mut item.config, &existing.config);
+ }
+ Ok(ConsulAclItem::AuthMethod(without_auth_method_secrets(
+ apply(&client, ConsulAclKind::AuthMethod, id, &item).await?,
+ )))
+ }
+ ConsulAclWrite::BindingRule(item) => {
+ Ok(ConsulAclItem::BindingRule(apply(&client, ConsulAclKind::BindingRule, id, &item).await?))
+ }
+ }
+}
+
+pub async fn consul_acl_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulAclKind,
+ id: &str,
+) -> Result<ConsulAclReferences, String> {
+ super::ensure_writable(state, connection_id, "ACL delete").await?;
+ let references = consul_acl_references_core(state, connection_id, kind, id).await?;
+ if !references.complete {
+ return Err("CONSUL_IMPACT_INCOMPLETE: ACL references could not be enumerated completely".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&item_path(kind, id)?)?;
+ client.send_json(Method::DELETE, url, None::<&()>, false, "delete ACL resource").await?;
+ Ok(references)
+}
+
+pub async fn consul_acl_references_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulAclKind,
+ id: &str,
+) -> Result<ConsulAclReferences, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let tokens = if matches!(kind, ConsulAclKind::Policy | ConsulAclKind::Role | ConsulAclKind::AuthMethod) {
+ list_with_meta::<ConsulAclToken>(&client, "/v1/acl/tokens", "list ACL token references").await
+ } else {
+ Ok((Vec::new(), false))
+ };
+ let roles = if kind == ConsulAclKind::Policy {
+ list_with_meta::<ConsulAclRole>(&client, "/v1/acl/roles", "list ACL role references").await
+ } else {
+ Ok((Vec::new(), false))
+ };
+ let binding_rules = if kind == ConsulAclKind::AuthMethod {
+ list_with_meta::<ConsulAclBindingRule>(&client, "/v1/acl/binding-rules", "list ACL binding rule references")
+ .await
+ } else {
+ Ok((Vec::new(), false))
+ };
+ let complete = tokens.is_ok() && roles.is_ok() && binding_rules.is_ok();
+ let (tokens, token_filtered) = tokens.unwrap_or_default();
+ let (roles, role_filtered) = roles.unwrap_or_default();
+ let (binding_rules, binding_rule_filtered) = binding_rules.unwrap_or_default();
+ let mut result = ConsulAclReferences {
+ complete: complete && !(token_filtered || role_filtered || binding_rule_filtered),
+ filtered_by_acls: token_filtered || role_filtered || binding_rule_filtered,
+ ..Default::default()
+ };
+ match kind {
+ ConsulAclKind::Policy => {
+ result.token_accessor_ids = tokens
+ .iter()
+ .filter(|token| token.policies.iter().any(|link| link.id == id || link.name == id))
+ .map(|token| token.accessor_id.clone())
+ .collect();
+ result.role_ids = roles
+ .iter()
+ .filter(|role| role.policies.iter().any(|link| link.id == id || link.name == id))
+ .map(|role| role.id.clone())
+ .collect();
+ }
+ ConsulAclKind::Role => {
+ result.token_accessor_ids = tokens
+ .iter()
+ .filter(|token| token.roles.iter().any(|link| link.id == id || link.name == id))
+ .map(|token| token.accessor_id.clone())
+ .collect()
+ }
+ ConsulAclKind::AuthMethod => {
+ result.token_accessor_ids =
+ tokens.iter().filter(|token| token.auth_method == id).map(|token| token.accessor_id.clone()).collect();
+ result.binding_rule_ids =
+ binding_rules.iter().filter(|rule| rule.auth_method == id).map(|rule| rule.id.clone()).collect();
+ }
+ _ => {}
+ }
+ Ok(result)
+}
+
+async fn list<T: serde::de::DeserializeOwned>(
+ client: &ConsulClient,
+ path: &str,
+ action: &str,
+) -> Result<Vec<T>, String> {
+ let url = client.api_url(path)?;
+ client.request_json(Method::GET, url, None::<&()>, true, action).await
+}
+
+async fn list_with_meta<T: serde::de::DeserializeOwned>(
+ client: &ConsulClient,
+ path: &str,
+ action: &str,
+) -> Result<(Vec<T>, bool), String> {
+ let url = client.api_url(path)?;
+ let response = client.send_json(Method::GET, url, None::<&()>, true, action).await?;
+ let filtered = ConsulResponseMetadata::from_response(&response).filtered_by_acls.unwrap_or(false);
+ let items = decode_json_response(response, action).await?;
+ Ok((items, filtered))
+}
+
+async fn apply<T: Serialize + serde::de::DeserializeOwned>(
+ client: &ConsulClient,
+ kind: ConsulAclKind,
+ id: Option<&str>,
+ item: &T,
+) -> Result<T, String> {
+ let (method, path) = if let Some(id) = id {
+ (Method::PUT, item_path(kind, id)?)
+ } else {
+ (Method::PUT, collection_create_path(kind)?.to_string())
+ };
+ let url = client.api_url(&path)?;
+ client.request_json(method, url, Some(item), false, "write ACL resource").await
+}
+
+fn without_token_secret(mut token: ConsulAclToken) -> ConsulAclToken {
+ token.secret_id = None;
+ token
+}
+
+fn without_auth_method_secrets(mut method: ConsulAclAuthMethod) -> ConsulAclAuthMethod {
+ redact_sensitive_config(&mut method.config);
+ method
+}
+
+fn redact_sensitive_config(value: &mut serde_json::Value) {
+ match value {
+ serde_json::Value::Object(object) => {
+ object.retain(|key, _| !is_sensitive_config_key(key));
+ for value in object.values_mut() {
+ redact_sensitive_config(value);
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for value in values {
+ redact_sensitive_config(value);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn is_sensitive_config_key(key: &str) -> bool {
+ let key = key.to_ascii_lowercase();
+ key.contains("secret")
+ || key.contains("password")
+ || key.contains("passphrase")
+ || key.contains("token")
+ || key == "jwt"
+ || key.ends_with("jwt")
+ || key == "bootstrap"
+}
+
+fn merge_missing_sensitive_config(target: &mut serde_json::Value, existing: &serde_json::Value) {
+ let (serde_json::Value::Object(target), serde_json::Value::Object(existing)) = (target, existing) else {
+ return;
+ };
+ for (key, existing_value) in existing {
+ if is_sensitive_config_key(key) {
+ target.entry(key.clone()).or_insert_with(|| existing_value.clone());
+ } else if let Some(target_value) = target.get_mut(key) {
+ merge_missing_sensitive_config(target_value, existing_value);
+ }
+ }
+}
+
+fn collection_create_path(kind: ConsulAclKind) -> Result<&'static str, String> {
+ match kind {
+ ConsulAclKind::Token => Ok("/v1/acl/token"),
+ ConsulAclKind::Policy => Ok("/v1/acl/policy"),
+ ConsulAclKind::Role => Ok("/v1/acl/role"),
+ ConsulAclKind::AuthMethod => Ok("/v1/acl/auth-method"),
+ ConsulAclKind::BindingRule => Ok("/v1/acl/binding-rule"),
+ ConsulAclKind::TemplatedPolicy => Err("CONSUL_UNSUPPORTED: templated policies are read-only".to_string()),
+ }
+}
+
+fn item_path(kind: ConsulAclKind, id: &str) -> Result<String, String> {
+ let segment = percent_encoding::utf8_percent_encode(id, percent_encoding::NON_ALPHANUMERIC);
+ Ok(format!("{}/{}", collection_create_path(kind)?, segment))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn acl_paths_are_safe() {
+ assert_eq!(item_path(ConsulAclKind::Policy, "team/a").unwrap(), "/v1/acl/policy/team%2Fa");
+ assert!(item_path(ConsulAclKind::TemplatedPolicy, "x").is_err());
+ }
+
+ #[test]
+ fn ordinary_token_reads_do_not_serialize_secret_id() {
+ let token = without_token_secret(ConsulAclToken {
+ accessor_id: "accessor".into(),
+ secret_id: Some(ConsulSecret("connection-token".into())),
+ ..Default::default()
+ });
+ let serialized = serde_json::to_string(&token).unwrap();
+ assert!(!serialized.contains("connection-token"));
+ assert!(!serialized.contains("SecretID"));
+ }
+
+ #[test]
+ fn auth_method_output_and_debug_redact_nested_secrets() {
+ let method = without_auth_method_secrets(ConsulAclAuthMethod {
+ name: "oidc".into(),
+ config: serde_json::json!({
+ "OIDCClientID": "public-client",
+ "OIDCClientSecret": "top-secret",
+ "ServiceAccountJWT": "kubernetes-jwt",
+ "Nested": { "bearer_token": "nested-secret", "JWKSURL": "https://issuer.example/jwks" }
+ }),
+ ..Default::default()
+ });
+ let serialized = serde_json::to_string(&method).unwrap();
+ let debug = format!("{method:?}");
+ assert!(!serialized.contains("top-secret"));
+ assert!(!serialized.contains("nested-secret"));
+ assert!(!serialized.contains("kubernetes-jwt"));
+ assert!(serialized.contains("public-client"));
+ assert!(!debug.contains("public-client"));
+ assert!(debug.contains("[REDACTED]"));
+ }
+
+ #[test]
+ fn auth_method_update_preserves_omitted_sensitive_config() {
+ let existing = serde_json::json!({
+ "Host": "https://kubernetes.example",
+ "ServiceAccountJWT": "keep-me",
+ "Nested": { "OIDCClientSecret": "also-keep", "Issuer": "old" }
+ });
+ let mut update = serde_json::json!({
+ "Host": "https://new.example",
+ "Nested": { "Issuer": "new" }
+ });
+ merge_missing_sensitive_config(&mut update, &existing);
+ assert_eq!(update["ServiceAccountJWT"], "keep-me");
+ assert_eq!(update["Nested"]["OIDCClientSecret"], "also-keep");
+ assert_eq!(update["Nested"]["Issuer"], "new");
+ }
+}
diff --git a/crates/dbx-core/src/consul/agent.rs b/crates/dbx-core/src/consul/agent.rs
new file mode 100644
index 0000000000..4534b84da8
--- /dev/null
+++ b/crates/dbx-core/src/consul/agent.rs
@@ -0,0 +1,1118 @@
+use std::collections::BTreeMap;
+use std::net::IpAddr;
+
+use reqwest::{Method, StatusCode};
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::catalog::{encode_segment, ConsulServiceAddress, ConsulServiceWeights};
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::config::ConsulAgentTarget;
+use super::health::ConsulHealthCheck;
+use super::response::{decode_json_response, ensure_success};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentIdentity {
+ pub node: String,
+ pub address: String,
+ pub datacenter: String,
+ pub version: Option<String>,
+ pub server: Option<bool>,
+ pub revision: Option<String>,
+ pub segment: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct AgentSelfWire {
+ #[serde(rename = "Config")]
+ config: AgentSelfConfigWire,
+ #[serde(rename = "Member")]
+ member: AgentMemberWire,
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct AgentSelfConfigWire {
+ #[serde(default)]
+ node_name: String,
+ #[serde(default)]
+ datacenter: String,
+ version: Option<String>,
+ server: Option<bool>,
+ revision: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAgentMember {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub addr: String,
+ #[serde(default)]
+ pub port: u16,
+ #[serde(default)]
+ pub tags: BTreeMap<String, String>,
+ #[serde(default)]
+ pub status: u8,
+ #[serde(default)]
+ pub protocol_min: u8,
+ #[serde(default)]
+ pub protocol_max: u8,
+ #[serde(default)]
+ pub protocol_cur: u8,
+ #[serde(default)]
+ pub delegate_min: u8,
+ #[serde(default)]
+ pub delegate_max: u8,
+ #[serde(default)]
+ pub delegate_cur: u8,
+}
+
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct AgentMemberWire {
+ #[serde(default)]
+ addr: String,
+ #[serde(default)]
+ tags: BTreeMap<String, String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAgentMetric {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub value: f64,
+ #[serde(default)]
+ pub labels: BTreeMap<String, String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAgentMetrics {
+ #[serde(default)]
+ pub timestamp: String,
+ #[serde(default)]
+ pub gauges: Vec<ConsulAgentMetric>,
+ #[serde(default)]
+ pub counters: Vec<ConsulAgentMetric>,
+ #[serde(default)]
+ pub samples: Vec<ConsulAgentMetric>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAgentService {
+ #[serde(default)]
+ pub kind: String,
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub service: String,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub port: u16,
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
+ #[serde(default)]
+ pub weights: ConsulServiceWeights,
+ #[serde(default)]
+ pub enable_tag_override: bool,
+ #[serde(default)]
+ pub datacenter: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentServiceRegistration {
+ pub id: String,
+ pub name: String,
+ pub tags: Vec<String>,
+ pub address: String,
+ pub port: u16,
+ pub meta: BTreeMap<String, String>,
+ pub weights: ConsulServiceWeights,
+ pub kind: String,
+ pub enable_tag_override: bool,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
+ #[serde(default)]
+ pub ports: Vec<ConsulAgentServicePort>,
+ pub proxy: Option<ConsulAgentProxyRegistration>,
+ #[serde(default)]
+ pub connect: Option<ConsulAgentConnectRegistration>,
+ pub checks: Vec<ConsulAgentCheckRegistration>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentServicePort {
+ pub name: String,
+ pub port: u16,
+ pub default: bool,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentConnectRegistration {
+ pub native: bool,
+ #[serde(default)]
+ pub sidecar_service: Option<Box<ConsulAgentServiceRegistration>>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentProxyRegistration {
+ pub destination_service_name: String,
+ pub destination_service_id: String,
+ pub local_service_address: String,
+ pub local_service_port: u16,
+ #[serde(default)]
+ pub local_service_ports: Vec<String>,
+ #[serde(default)]
+ pub local_service_socket_path: String,
+ #[serde(default)]
+ pub mode: String,
+ #[serde(default)]
+ pub transparent_proxy: Option<ConsulAgentTransparentProxy>,
+ #[serde(default)]
+ pub config: BTreeMap<String, serde_json::Value>,
+ pub upstreams: Vec<ConsulAgentUpstream>,
+ #[serde(default)]
+ pub mesh_gateway: Option<ConsulAgentMeshGateway>,
+ #[serde(default)]
+ pub expose: Option<ConsulAgentExpose>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentTransparentProxy {
+ pub outbound_listener_port: u16,
+ pub dialed_directly: bool,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentMeshGateway {
+ pub mode: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentExpose {
+ pub checks: bool,
+ #[serde(default)]
+ pub paths: Vec<ConsulAgentExposePath>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentExposePath {
+ pub path: String,
+ pub protocol: String,
+ pub local_path_port: u16,
+ pub listener_port: u16,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentUpstream {
+ pub destination_type: String,
+ pub destination_name: String,
+ #[serde(default)]
+ pub destination_port: u16,
+ #[serde(default)]
+ pub destination_namespace: String,
+ #[serde(default)]
+ pub destination_partition: String,
+ #[serde(default)]
+ pub destination_peer: String,
+ pub local_bind_address: String,
+ pub local_bind_port: u16,
+ #[serde(default)]
+ pub local_bind_socket_path: String,
+ #[serde(default)]
+ pub local_bind_socket_mode: String,
+ pub datacenter: String,
+ #[serde(default)]
+ pub mesh_gateway: Option<ConsulAgentMeshGateway>,
+ #[serde(default)]
+ pub config: BTreeMap<String, serde_json::Value>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentCheckRegistration {
+ pub id: String,
+ pub name: String,
+ pub notes: String,
+ pub service_id: String,
+ pub status: String,
+ pub definition: ConsulAgentCheckDefinition,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
+pub enum ConsulAgentCheckDefinition {
+ Http { url: String, method: String, interval: String, timeout: String, tls_skip_verify: bool },
+ Tcp { address: String, interval: String, timeout: String },
+ Grpc { address: String, interval: String, timeout: String, tls: bool },
+ Ttl { ttl: String },
+ Docker { container_id: String, shell: String, args: Vec<String>, interval: String, timeout: String },
+ Script { args: Vec<String>, interval: String, timeout: String },
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum ConsulCheckStatus {
+ Passing,
+ Warning,
+ Critical,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentWriteResult {
+ pub target: ConsulAgentIdentity,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum AgentWritePermission {
+ Service,
+ Node,
+}
+
+impl ConsulClient {
+ pub async fn agent_self(&self) -> Result<ConsulAgentIdentity, String> {
+ let url = self.api_url("/v1/agent/self")?;
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read Consul agent identity", self.token())
+ .await?;
+ let wire = decode_json_response::<AgentSelfWire>(response, "read Consul agent identity").await?;
+ Ok(ConsulAgentIdentity {
+ node: wire.config.node_name,
+ address: wire.member.addr,
+ datacenter: wire.config.datacenter,
+ version: wire.config.version,
+ server: wire.config.server,
+ revision: wire.config.revision,
+ segment: wire.member.tags.get("segment").cloned(),
+ })
+ }
+
+ pub async fn agent_members(&self, wan: bool, segment: Option<&str>) -> Result<Vec<ConsulAgentMember>, String> {
+ let mut url = self.api_url("/v1/agent/members")?;
+ {
+ let mut query = url.query_pairs_mut();
+ if wan {
+ query.append_pair("wan", "true");
+ }
+ if let Some(segment) = segment.map(str::trim).filter(|value| !value.is_empty()) {
+ query.append_pair("segment", segment);
+ }
+ }
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "list Consul agent members", self.token()).await?;
+ decode_json_response(response, "list Consul agent members").await
+ }
+
+ pub async fn agent_metrics(&self) -> Result<ConsulAgentMetrics, String> {
+ let url = self.api_url("/v1/agent/metrics")?;
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read Consul agent metrics", self.token()).await?;
+ decode_json_response(response, "read Consul agent metrics").await
+ }
+
+ pub async fn agent_services(&self) -> Result<BTreeMap<String, ConsulAgentService>, String> {
+ let mut url = self.api_url("/v1/agent/services")?;
+ self.append_scope(&mut url, true);
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "list local Consul services", self.token())
+ .await?;
+ decode_json_response(response, "list local Consul services").await
+ }
+
+ pub async fn agent_service(&self, id: &str) -> Result<ConsulAgentService, String> {
+ let mut url = self.api_url(&format!("/v1/agent/service/{}", encode_segment(required(id, "service id")?)))?;
+ self.append_scope(&mut url, true);
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read local Consul service", self.token()).await?;
+ decode_json_response(response, "read local Consul service").await
+ }
+
+ pub async fn agent_checks(&self) -> Result<BTreeMap<String, ConsulHealthCheck>, String> {
+ let mut url = self.api_url("/v1/agent/checks")?;
+ self.append_scope(&mut url, true);
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "list local Consul checks", self.token()).await?;
+ decode_json_response(response, "list local Consul checks").await
+ }
+
+ pub async fn validate_configured_agent_target(&self) -> Result<ConsulAgentIdentity, String> {
+ if self.config().connect_override.is_some() {
+ return Err(
+ "CONSUL_AGENT_TARGET_TRANSPORT_UNSAFE: Agent writes are disabled through Transport Layer routing"
+ .to_string(),
+ );
+ }
+ let ConsulAgentTarget { node, address } = self.config().agent_target.as_ref().ok_or(
+ "CONSUL_AGENT_TARGET_REQUIRED: Configure an explicit Agent node and direct address before writing",
+ )?;
+ let request_host = self.config().base_url.host_str().unwrap_or_default();
+ if request_host != "localhost" && request_host.parse::<IpAddr>().is_err() {
+ return Err("CONSUL_AGENT_TARGET_LOAD_BALANCED: Agent writes require a literal IP or localhost endpoint, not a DNS/load-balanced host".to_string());
+ }
+ if !same_address(request_host, address) {
+ return Err(
+ "CONSUL_AGENT_TARGET_MISMATCH: Configured Agent address does not match the direct connection endpoint"
+ .to_string(),
+ );
+ }
+ let identity = self.agent_self().await?;
+ if identity.node != *node {
+ return Err(format!(
+ "CONSUL_AGENT_TARGET_MISMATCH: Expected Agent node '{node}', but the endpoint returned '{}'",
+ identity.node
+ ));
+ }
+ Ok(identity)
+ }
+
+ async fn agent_write_json(
+ &self,
+ path: &str,
+ body: Option<serde_json::Value>,
+ action: &str,
+ permission: AgentWritePermission,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ let body = encode_agent_write_body(body, action)?;
+ let target = self.validate_configured_agent_target().await?;
+ self.agent_write_body_for_target(path, body, action, permission, target).await
+ }
+
+ async fn agent_write_json_for_target(
+ &self,
+ path: &str,
+ body: Option<serde_json::Value>,
+ action: &str,
+ permission: AgentWritePermission,
+ target: ConsulAgentIdentity,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ let body = encode_agent_write_body(body, action)?;
+ self.agent_write_body_for_target(path, body, action, permission, target).await
+ }
+
+ async fn agent_write_body_for_target(
+ &self,
+ path: &str,
+ body: Option<Vec<u8>>,
+ action: &str,
+ permission: AgentWritePermission,
+ target: ConsulAgentIdentity,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ let mut url = self.api_url(path)?;
+ self.append_scope(&mut url, false);
+ ensure_agent_write_success(self.send(Method::PUT, url, body).await?, action, permission, self.token()).await?;
+ Ok(ConsulAgentWriteResult { target })
+ }
+
+ pub(super) async fn register_agent_service(
+ &self,
+ registration: ConsulAgentServiceRegistration,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ required(&registration.name, "service name")?;
+ if registration.port > 0 && registration.address.trim().is_empty() {
+ // Empty is valid and means the agent address. Keep it explicit in the generated DTO.
+ }
+ let body = service_registration_json(registration)?;
+ self.agent_write_json(
+ "/v1/agent/service/register",
+ Some(body),
+ "register local Consul service",
+ AgentWritePermission::Service,
+ )
+ .await
+ }
+
+ pub(super) async fn deregister_agent_service(&self, id: &str) -> Result<ConsulAgentWriteResult, String> {
+ self.agent_write_json(
+ &format!("/v1/agent/service/deregister/{}", encode_segment(required(id, "service id")?)),
+ None,
+ "deregister local Consul service",
+ AgentWritePermission::Service,
+ )
+ .await
+ }
+
+ pub(super) async fn set_agent_service_maintenance(
+ &self,
+ id: &str,
+ enable: bool,
+ reason: Option<&str>,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ let target = self.validate_configured_agent_target().await?;
+ let mut url =
+ self.api_url(&format!("/v1/agent/service/maintenance/{}", encode_segment(required(id, "service id")?)))?;
+ self.append_scope(&mut url, false);
+ url.query_pairs_mut().append_pair("enable", if enable { "true" } else { "false" });
+ if let Some(reason) = reason.map(str::trim).filter(|value| !value.is_empty()) {
+ url.query_pairs_mut().append_pair("reason", reason);
+ }
+ ensure_agent_write_success(
+ self.send(Method::PUT, url, None).await?,
+ "change Consul service maintenance",
+ AgentWritePermission::Service,
+ self.token(),
+ )
+ .await?;
+ Ok(ConsulAgentWriteResult { target })
+ }
+
+ pub(super) async fn register_agent_check(
+ &self,
+ registration: ConsulAgentCheckRegistration,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ required(&registration.name, "check name")?;
+ let permission = agent_write_permission_for_service_id(&registration.service_id);
+ let body = check_registration_json(registration)?;
+ self.agent_write_json("/v1/agent/check/register", Some(body), "register local Consul check", permission).await
+ }
+
+ pub(super) async fn deregister_agent_check(&self, id: &str) -> Result<ConsulAgentWriteResult, String> {
+ let id = required(id, "check id")?;
+ let target = self.validate_configured_agent_target().await?;
+ let Some(permission) = self.existing_check_write_permission(id).await? else {
+ return Ok(ConsulAgentWriteResult { target });
+ };
+ self.agent_write_json_for_target(
+ &format!("/v1/agent/check/deregister/{}", encode_segment(id)),
+ None,
+ "deregister local Consul check",
+ permission,
+ target,
+ )
+ .await
+ }
+
+ pub(super) async fn update_ttl_check(
+ &self,
+ id: &str,
+ status: ConsulCheckStatus,
+ output: Option<&str>,
+ ) -> Result<ConsulAgentWriteResult, String> {
+ let status = match status {
+ ConsulCheckStatus::Passing => "passing",
+ ConsulCheckStatus::Warning => "warning",
+ ConsulCheckStatus::Critical => "critical",
+ };
+ let id = required(id, "check id")?;
+ let target = self.validate_configured_agent_target().await?;
+ let permission = self
+ .existing_check_write_permission(id)
+ .await?
+ .ok_or_else(|| "CONSUL_AGENT_CHECK_NOT_FOUND: Local Consul check does not exist".to_string())?;
+ self.agent_write_json_for_target(
+ &format!("/v1/agent/check/update/{}", encode_segment(id)),
+ Some(serde_json::json!({ "Status": status, "Output": output.unwrap_or_default() })),
+ "update Consul TTL check",
+ permission,
+ target,
+ )
+ .await
+ }
+
+ async fn existing_check_write_permission(&self, id: &str) -> Result<Option<AgentWritePermission>, String> {
+ let checks = self.agent_checks().await.map_err(|error| {
+ format!("CONSUL_AGENT_CHECK_SCOPE_UNAVAILABLE: Failed to determine local check ownership: {error}")
+ })?;
+ Ok(checks
+ .get(id)
+ .or_else(|| checks.values().find(|check| check.check_id == id))
+ .map(|check| agent_write_permission_for_service_id(&check.service_id)))
+ }
+}
+
+const MAX_AGENT_WRITE_BODY_BYTES: usize = 512 * 1024;
+
+fn encode_agent_write_body(body: Option<serde_json::Value>, action: &str) -> Result<Option<Vec<u8>>, String> {
+ let body = body
+ .map(|value| serde_json::to_vec(&value).map_err(|error| format!("Failed to encode {action}: {error}")))
+ .transpose()?;
+ if body.as_ref().is_some_and(|body| body.len() > MAX_AGENT_WRITE_BODY_BYTES) {
+ return Err(format!(
+ "CONSUL_AGENT_REQUEST_TOO_LARGE: {action} request exceeds the {} KiB limit",
+ MAX_AGENT_WRITE_BODY_BYTES / 1024
+ ));
+ }
+ Ok(body)
+}
+
+async fn ensure_agent_write_success(
+ response: reqwest::Response,
+ action: &str,
+ permission: AgentWritePermission,
+ token: &str,
+) -> Result<(), String> {
+ let forbidden = response.status() == StatusCode::FORBIDDEN;
+ match ensure_success(response, action, token).await {
+ Ok(_) => Ok(()),
+ Err(error) if forbidden => Err(agent_permission_error(permission, action, &error)),
+ Err(error) => Err(error),
+ }
+}
+
+fn agent_write_permission_for_service_id(service_id: &str) -> AgentWritePermission {
+ if service_id.trim().is_empty() {
+ AgentWritePermission::Node
+ } else {
+ AgentWritePermission::Service
+ }
+}
+
+fn agent_permission_error(permission: AgentWritePermission, action: &str, detail: &str) -> String {
+ match permission {
+ AgentWritePermission::Service => {
+ format!("CONSUL_AGENT_SERVICE_WRITE_DENIED: {action} requires Consul service:write permission; {detail}")
+ }
+ AgentWritePermission::Node => {
+ format!("CONSUL_AGENT_NODE_WRITE_DENIED: {action} requires Consul node:write permission; {detail}")
+ }
+ }
+}
+
+fn same_address(left: &str, right: &str) -> bool {
+ let left = left.trim().trim_matches(['[', ']']);
+ let right = right.trim().trim_matches(['[', ']']);
+ left.eq_ignore_ascii_case(right)
+ || (left.eq_ignore_ascii_case("localhost") && is_loopback_address(right))
+ || (right.eq_ignore_ascii_case("localhost") && is_loopback_address(left))
+}
+
+fn is_loopback_address(value: &str) -> bool {
+ value.eq_ignore_ascii_case("localhost") || value.parse::<IpAddr>().is_ok_and(|address| address.is_loopback())
+}
+
+fn required<'a>(value: &'a str, field: &str) -> Result<&'a str, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ Err(format!("CONSUL_INVALID_REQUEST: {field} is required"))
+ } else {
+ Ok(value)
+ }
+}
+
+fn service_registration_json(registration: ConsulAgentServiceRegistration) -> Result<serde_json::Value, String> {
+ validate_service_registration(&registration, 0)?;
+ service_registration_json_inner(registration)
+}
+
+fn service_registration_json_inner(registration: ConsulAgentServiceRegistration) -> Result<serde_json::Value, String> {
+ let checks = registration.checks.into_iter().map(check_registration_json).collect::<Result<Vec<_>, _>>()?;
+ let proxy = registration.proxy.map(proxy_registration_json);
+ let connect = registration
+ .connect
+ .map(|connect| {
+ let sidecar =
+ connect.sidecar_service.map(|sidecar| service_registration_json_inner(*sidecar)).transpose()?;
+ Ok::<_, String>(serde_json::json!({
+ "Native": connect.native,
+ "SidecarService": sidecar,
+ }))
+ })
+ .transpose()?;
+ Ok(serde_json::json!({
+ "ID": registration.id,
+ "Name": registration.name,
+ "Tags": registration.tags,
+ "Address": registration.address,
+ "TaggedAddresses": registration.tagged_addresses,
+ "Port": registration.port,
+ "Ports": registration.ports.into_iter().map(|port| serde_json::json!({
+ "Name": port.name,
+ "Port": port.port,
+ "Default": port.default,
+ })).collect::<Vec<_>>(),
+ "Meta": registration.meta,
+ "Weights": registration.weights,
+ "Kind": registration.kind,
+ "EnableTagOverride": registration.enable_tag_override,
+ "Proxy": proxy,
+ "Connect": connect,
+ "Checks": checks,
+ }))
+}
+
+fn proxy_registration_json(proxy: ConsulAgentProxyRegistration) -> serde_json::Value {
+ serde_json::json!({
+ "DestinationServiceName": proxy.destination_service_name,
+ "DestinationServiceID": proxy.destination_service_id,
+ "LocalServiceAddress": proxy.local_service_address,
+ "LocalServicePort": proxy.local_service_port,
+ "LocalServicePorts": proxy.local_service_ports,
+ "LocalServiceSocketPath": proxy.local_service_socket_path,
+ "Mode": proxy.mode,
+ "TransparentProxy": proxy.transparent_proxy.map(|transparent| serde_json::json!({
+ "OutboundListenerPort": transparent.outbound_listener_port,
+ "DialedDirectly": transparent.dialed_directly,
+ })),
+ "Config": proxy.config,
+ "Upstreams": proxy.upstreams.into_iter().map(|upstream| serde_json::json!({
+ "DestinationType": upstream.destination_type,
+ "DestinationName": upstream.destination_name,
+ "DestinationPort": upstream.destination_port,
+ "DestinationNamespace": upstream.destination_namespace,
+ "DestinationPartition": upstream.destination_partition,
+ "DestinationPeer": upstream.destination_peer,
+ "LocalBindAddress": upstream.local_bind_address,
+ "LocalBindPort": upstream.local_bind_port,
+ "LocalBindSocketPath": upstream.local_bind_socket_path,
+ "LocalBindSocketMode": upstream.local_bind_socket_mode,
+ "Datacenter": upstream.datacenter,
+ "MeshGateway": mesh_gateway_json(upstream.mesh_gateway),
+ "Config": upstream.config,
+ })).collect::<Vec<_>>(),
+ "MeshGateway": mesh_gateway_json(proxy.mesh_gateway),
+ "Expose": proxy.expose.map(|expose| serde_json::json!({
+ "Checks": expose.checks,
+ "Paths": expose.paths.into_iter().map(|path| serde_json::json!({
+ "Path": path.path,
+ "Protocol": path.protocol,
+ "LocalPathPort": path.local_path_port,
+ "ListenerPort": path.listener_port,
+ })).collect::<Vec<_>>(),
+ })),
+ })
+}
+
+fn mesh_gateway_json(mesh_gateway: Option<ConsulAgentMeshGateway>) -> Option<serde_json::Value> {
+ mesh_gateway.map(|gateway| serde_json::json!({ "Mode": gateway.mode }))
+}
+
+const MAX_AGENT_SIDECAR_DEPTH: usize = 4;
+const MAX_AGENT_COLLECTION_ITEMS: usize = 1_000;
+const MAX_AGENT_CONFIG_DEPTH: usize = 16;
+const MAX_AGENT_CONFIG_NODES: usize = 10_000;
+
+fn validate_service_registration(registration: &ConsulAgentServiceRegistration, depth: usize) -> Result<(), String> {
+ required(&registration.name, "service name")?;
+ if depth > MAX_AGENT_SIDECAR_DEPTH {
+ return Err(format!(
+ "CONSUL_AGENT_REGISTRATION_DEPTH_EXCEEDED: Connect.SidecarService exceeds {MAX_AGENT_SIDECAR_DEPTH} nested levels"
+ ));
+ }
+ for (field, length) in [
+ ("Tags", registration.tags.len()),
+ ("TaggedAddresses", registration.tagged_addresses.len()),
+ ("Ports", registration.ports.len()),
+ ("Meta", registration.meta.len()),
+ ("Checks", registration.checks.len()),
+ ] {
+ ensure_agent_collection_limit(field, length)?;
+ }
+ if registration.port != 0 && !registration.ports.is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: Agent service Port and Ports are mutually exclusive".to_string());
+ }
+ if registration.ports.iter().filter(|port| port.default).count() > 1 {
+ return Err("CONSUL_INVALID_REQUEST: Agent service Ports may contain at most one default port".to_string());
+ }
+ if let Some(proxy) = &registration.proxy {
+ validate_proxy_registration(proxy)?;
+ }
+ if let Some(sidecar) = registration.connect.as_ref().and_then(|connect| connect.sidecar_service.as_deref()) {
+ validate_service_registration(sidecar, depth + 1)?;
+ }
+ Ok(())
+}
+
+fn validate_proxy_registration(proxy: &ConsulAgentProxyRegistration) -> Result<(), String> {
+ for (field, length) in [
+ ("Proxy.LocalServicePorts", proxy.local_service_ports.len()),
+ ("Proxy.Upstreams", proxy.upstreams.len()),
+ ("Proxy.Config", proxy.config.len()),
+ ("Proxy.Expose.Paths", proxy.expose.as_ref().map_or(0, |expose| expose.paths.len())),
+ ] {
+ ensure_agent_collection_limit(field, length)?;
+ }
+ validate_opaque_config(&proxy.config, "Proxy.Config")?;
+ for (index, upstream) in proxy.upstreams.iter().enumerate() {
+ if !upstream.local_bind_socket_path.is_empty()
+ && (upstream.local_bind_port != 0 || !upstream.local_bind_address.is_empty())
+ {
+ return Err(format!(
+ "CONSUL_INVALID_REQUEST: Proxy.Upstreams[{index}] socket path conflicts with bind address or port"
+ ));
+ }
+ ensure_agent_collection_limit(&format!("Proxy.Upstreams[{index}].Config"), upstream.config.len())?;
+ validate_opaque_config(&upstream.config, &format!("Proxy.Upstreams[{index}].Config"))?;
+ }
+ Ok(())
+}
+
+fn validate_opaque_config(config: &BTreeMap<String, serde_json::Value>, field: &str) -> Result<(), String> {
+ let mut stack = config.values().map(|value| (value, 1_usize)).collect::<Vec<_>>();
+ let mut nodes = config.len();
+ while let Some((value, depth)) = stack.pop() {
+ if depth > MAX_AGENT_CONFIG_DEPTH {
+ return Err(format!(
+ "CONSUL_AGENT_CONFIG_DEPTH_EXCEEDED: {field} exceeds {MAX_AGENT_CONFIG_DEPTH} nested levels"
+ ));
+ }
+ match value {
+ serde_json::Value::Array(items) => {
+ ensure_agent_collection_limit(field, items.len())?;
+ nodes = nodes.saturating_add(items.len());
+ stack.extend(items.iter().map(|item| (item, depth + 1)));
+ }
+ serde_json::Value::Object(items) => {
+ ensure_agent_collection_limit(field, items.len())?;
+ nodes = nodes.saturating_add(items.len());
+ stack.extend(items.values().map(|item| (item, depth + 1)));
+ }
+ _ => {}
+ }
+ if nodes > MAX_AGENT_CONFIG_NODES {
+ return Err(format!(
+ "CONSUL_AGENT_CONFIG_TOO_COMPLEX: {field} exceeds {MAX_AGENT_CONFIG_NODES} JSON nodes"
+ ));
+ }
+ }
+ Ok(())
+}
+
+fn ensure_agent_collection_limit(field: &str, length: usize) -> Result<(), String> {
+ if length > MAX_AGENT_COLLECTION_ITEMS {
+ return Err(format!(
+ "CONSUL_AGENT_COLLECTION_LIMIT_EXCEEDED: {field} contains {length} items; maximum is {MAX_AGENT_COLLECTION_ITEMS}"
+ ));
+ }
+ Ok(())
+}
+
+fn check_registration_json(registration: ConsulAgentCheckRegistration) -> Result<serde_json::Value, String> {
+ let mut object = serde_json::Map::new();
+ object.insert("ID".to_string(), registration.id.into());
+ object.insert("Name".to_string(), registration.name.into());
+ object.insert("Notes".to_string(), registration.notes.into());
+ object.insert("ServiceID".to_string(), registration.service_id.into());
+ object.insert("Status".to_string(), registration.status.into());
+ match registration.definition {
+ ConsulAgentCheckDefinition::Http { url, method, interval, timeout, tls_skip_verify } => {
+ required(&url, "HTTP check URL")?;
+ object.insert("HTTP".to_string(), url.into());
+ object.insert("Method".to_string(), method.into());
+ object.insert("Interval".to_string(), interval.into());
+ object.insert("Timeout".to_string(), timeout.into());
+ object.insert("TLSSkipVerify".to_string(), tls_skip_verify.into());
+ }
+ ConsulAgentCheckDefinition::Tcp { address, interval, timeout } => {
+ required(&address, "TCP check address")?;
+ object.insert("TCP".to_string(), address.into());
+ object.insert("Interval".to_string(), interval.into());
+ object.insert("Timeout".to_string(), timeout.into());
+ }
+ ConsulAgentCheckDefinition::Grpc { address, interval, timeout, tls } => {
+ required(&address, "gRPC check address")?;
+ object.insert("GRPC".to_string(), address.into());
+ object.insert("GRPCUseTLS".to_string(), tls.into());
+ object.insert("Interval".to_string(), interval.into());
+ object.insert("Timeout".to_string(), timeout.into());
+ }
+ ConsulAgentCheckDefinition::Ttl { ttl } => {
+ required(&ttl, "TTL")?;
+ object.insert("TTL".to_string(), ttl.into());
+ }
+ ConsulAgentCheckDefinition::Docker { container_id, shell, args, interval, timeout } => {
+ required(&container_id, "Docker container id")?;
+ object.insert("DockerContainerID".to_string(), container_id.into());
+ object.insert("Shell".to_string(), shell.into());
+ object.insert("Args".to_string(), args.into());
+ object.insert("Interval".to_string(), interval.into());
+ object.insert("Timeout".to_string(), timeout.into());
+ }
+ ConsulAgentCheckDefinition::Script { args, interval, timeout } => {
+ if args.is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: script check args are required".to_string());
+ }
+ object.insert("Args".to_string(), args.into());
+ object.insert("Interval".to_string(), interval.into());
+ object.insert("Timeout".to_string(), timeout.into());
+ }
+ }
+ Ok(object.into())
+}
+
+pub async fn consul_agent_self_core(state: &AppState, connection_id: &str) -> Result<ConsulAgentIdentity, String> {
+ client_for_state(state, connection_id).await?.agent_self().await
+}
+
+pub async fn consul_agent_members_core(
+ state: &AppState,
+ connection_id: &str,
+ wan: bool,
+ segment: Option<&str>,
+) -> Result<Vec<ConsulAgentMember>, String> {
+ client_for_state(state, connection_id).await?.agent_members(wan, segment).await
+}
+
+pub async fn consul_agent_metrics_core(state: &AppState, connection_id: &str) -> Result<ConsulAgentMetrics, String> {
+ client_for_state(state, connection_id).await?.agent_metrics().await
+}
+
+pub async fn consul_agent_services_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<BTreeMap<String, ConsulAgentService>, String> {
+ client_for_state(state, connection_id).await?.agent_services().await
+}
+
+pub async fn consul_agent_service_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulAgentService, String> {
+ client_for_state(state, connection_id).await?.agent_service(id).await
+}
+
+pub async fn consul_agent_checks_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<BTreeMap<String, ConsulHealthCheck>, String> {
+ client_for_state(state, connection_id).await?.agent_checks().await
+}
+
+pub async fn consul_agent_register_service_core(
+ state: &AppState,
+ connection_id: &str,
+ registration: ConsulAgentServiceRegistration,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "register Consul Agent service").await?;
+ client_for_state(state, connection_id).await?.register_agent_service(registration).await
+}
+
+pub async fn consul_agent_deregister_service_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "deregister Consul Agent service").await?;
+ client_for_state(state, connection_id).await?.deregister_agent_service(id).await
+}
+
+pub async fn consul_agent_service_maintenance_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+ enable: bool,
+ reason: Option<&str>,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "change Consul Agent service maintenance").await?;
+ client_for_state(state, connection_id).await?.set_agent_service_maintenance(id, enable, reason).await
+}
+
+pub async fn consul_agent_register_check_core(
+ state: &AppState,
+ connection_id: &str,
+ registration: ConsulAgentCheckRegistration,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "register Consul Agent check").await?;
+ client_for_state(state, connection_id).await?.register_agent_check(registration).await
+}
+
+pub async fn consul_agent_deregister_check_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "deregister Consul Agent check").await?;
+ client_for_state(state, connection_id).await?.deregister_agent_check(id).await
+}
+
+pub async fn consul_agent_update_ttl_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+ status: ConsulCheckStatus,
+ output: Option<&str>,
+) -> Result<ConsulAgentWriteResult, String> {
+ ensure_writable_core(state, connection_id, "update Consul Agent TTL check").await?;
+ client_for_state(state, connection_id).await?.update_ttl_check(id, status, output).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn check_definition_is_discriminated() {
+ let value = serde_json::to_value(ConsulAgentCheckDefinition::Ttl { ttl: "30s".to_string() }).unwrap();
+ assert_eq!(value["type"], "ttl");
+ assert_eq!(value["ttl"], "30s");
+ }
+
+ #[test]
+ fn agent_service_id_uses_consul_uppercase_acronym() {
+ let service: ConsulAgentService = serde_json::from_value(serde_json::json!({
+ "ID": "api-1",
+ "Service": "api",
+ "Port": 8080
+ }))
+ .unwrap();
+ assert_eq!(service.id, "api-1");
+ assert_eq!(serde_json::to_value(service).unwrap()["ID"], "api-1");
+ }
+
+ #[test]
+ fn target_address_matching_is_exact() {
+ assert!(same_address("127.0.0.1", "127.0.0.1"));
+ assert!(same_address("::1", "[::1]"));
+ assert!(same_address("localhost", "127.0.0.1"));
+ assert!(same_address("localhost", "::1"));
+ assert!(!same_address("127.0.0.1", "127.0.0.2"));
+ }
+
+ #[test]
+ fn service_registration_wire_includes_stable_mesh_fields() {
+ let registration = ConsulAgentServiceRegistration {
+ name: "api".into(),
+ tagged_addresses: BTreeMap::from([(
+ "lan".into(),
+ ConsulServiceAddress { address: "127.0.0.1".into(), port: 8080 },
+ )]),
+ ports: vec![ConsulAgentServicePort { name: "http".into(), port: 8080, default: true }],
+ connect: Some(ConsulAgentConnectRegistration {
+ native: true,
+ sidecar_service: Some(Box::new(ConsulAgentServiceRegistration {
+ name: "api-sidecar".into(),
+ kind: "connect-proxy".into(),
+ ..Default::default()
+ })),
+ }),
+ proxy: Some(ConsulAgentProxyRegistration {
+ destination_service_name: "api".into(),
+ destination_service_id: "api-1".into(),
+ local_service_address: "127.0.0.1".into(),
+ local_service_port: 8080,
+ mode: "transparent".into(),
+ transparent_proxy: Some(ConsulAgentTransparentProxy {
+ outbound_listener_port: 22500,
+ dialed_directly: true,
+ }),
+ config: BTreeMap::from([("protocol".into(), serde_json::json!("http2"))]),
+ upstreams: vec![ConsulAgentUpstream {
+ destination_type: "service".into(),
+ destination_name: "db".into(),
+ destination_port: 5432,
+ destination_namespace: "payments".into(),
+ destination_partition: "prod".into(),
+ destination_peer: "west".into(),
+ local_bind_address: "127.0.0.1".into(),
+ local_bind_port: 9191,
+ datacenter: "dc2".into(),
+ mesh_gateway: Some(ConsulAgentMeshGateway { mode: "remote".into() }),
+ config: BTreeMap::from([("connect_timeout_ms".into(), serde_json::json!(2500))]),
+ ..Default::default()
+ }],
+ mesh_gateway: Some(ConsulAgentMeshGateway { mode: "local".into() }),
+ expose: Some(ConsulAgentExpose {
+ checks: true,
+ paths: vec![ConsulAgentExposePath {
+ path: "/healthz".into(),
+ protocol: "http".into(),
+ local_path_port: 8080,
+ listener_port: 21500,
+ }],
+ }),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ let value = service_registration_json(registration).unwrap();
+ assert_eq!(value["TaggedAddresses"]["lan"]["Address"], "127.0.0.1");
+ assert_eq!(value["Ports"][0]["Default"], true);
+ assert_eq!(value["Connect"]["Native"], true);
+ assert_eq!(value["Connect"]["SidecarService"]["Name"], "api-sidecar");
+ assert_eq!(value["Proxy"]["TransparentProxy"]["OutboundListenerPort"], 22500);
+ assert_eq!(value["Proxy"]["Expose"]["Paths"][0]["ListenerPort"], 21500);
+ assert_eq!(value["Proxy"]["MeshGateway"]["Mode"], "local");
+ assert_eq!(value["Proxy"]["Config"]["protocol"], "http2");
+ assert_eq!(value["Proxy"]["Upstreams"][0]["DestinationPort"], 5432);
+ assert_eq!(value["Proxy"]["Upstreams"][0]["DestinationNamespace"], "payments");
+ assert_eq!(value["Proxy"]["Upstreams"][0]["DestinationPartition"], "prod");
+ assert_eq!(value["Proxy"]["Upstreams"][0]["DestinationPeer"], "west");
+ assert_eq!(value["Proxy"]["Upstreams"][0]["MeshGateway"]["Mode"], "remote");
+ assert_eq!(value["Proxy"]["Upstreams"][0]["Config"]["connect_timeout_ms"], 2500);
+ }
+
+ #[test]
+ fn registration_safety_limits_cover_depth_collections_and_bytes() {
+ let mut within_limit = ConsulAgentServiceRegistration { name: "leaf".into(), ..Default::default() };
+ for depth in 0..MAX_AGENT_SIDECAR_DEPTH {
+ within_limit = ConsulAgentServiceRegistration {
+ name: format!("sidecar-{depth}"),
+ connect: Some(ConsulAgentConnectRegistration {
+ native: false,
+ sidecar_service: Some(Box::new(within_limit)),
+ }),
+ ..Default::default()
+ };
+ }
+ assert!(service_registration_json(within_limit.clone()).is_ok());
+ let too_deep = ConsulAgentServiceRegistration {
+ name: "too-deep".into(),
+ connect: Some(ConsulAgentConnectRegistration {
+ native: false,
+ sidecar_service: Some(Box::new(within_limit)),
+ }),
+ ..Default::default()
+ };
+ assert!(service_registration_json(too_deep).unwrap_err().contains("REGISTRATION_DEPTH_EXCEEDED"));
+
+ let too_many = ConsulAgentServiceRegistration {
+ name: "too-many".into(),
+ tags: vec!["tag".into(); MAX_AGENT_COLLECTION_ITEMS + 1],
+ ..Default::default()
+ };
+ assert!(service_registration_json(too_many).unwrap_err().contains("COLLECTION_LIMIT_EXCEEDED"));
+
+ let mut nested_config = serde_json::json!(true);
+ for _ in 0..MAX_AGENT_CONFIG_DEPTH {
+ nested_config = serde_json::json!({ "next": nested_config });
+ }
+ let config_too_deep = ConsulAgentServiceRegistration {
+ name: "deep-config".into(),
+ proxy: Some(ConsulAgentProxyRegistration {
+ config: BTreeMap::from([("root".into(), nested_config)]),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ assert!(service_registration_json(config_too_deep).unwrap_err().contains("CONFIG_DEPTH_EXCEEDED"));
+
+ let oversized = serde_json::json!({ "blob": "x".repeat(MAX_AGENT_WRITE_BODY_BYTES) });
+ assert!(encode_agent_write_body(Some(oversized), "register service")
+ .unwrap_err()
+ .contains("AGENT_REQUEST_TOO_LARGE"));
+ }
+
+ #[test]
+ fn agent_write_permission_errors_are_stable_and_scope_specific() {
+ assert_eq!(agent_write_permission_for_service_id(""), AgentWritePermission::Node);
+ assert_eq!(agent_write_permission_for_service_id("api-1"), AgentWritePermission::Service);
+ let service = agent_permission_error(AgentWritePermission::Service, "register check", "forbidden");
+ let node = agent_permission_error(AgentWritePermission::Node, "register check", "forbidden");
+ assert!(service.starts_with("CONSUL_AGENT_SERVICE_WRITE_DENIED:"));
+ assert!(service.contains("service:write"));
+ assert!(node.starts_with("CONSUL_AGENT_NODE_WRITE_DENIED:"));
+ assert!(node.contains("node:write"));
+ }
+}
diff --git a/crates/dbx-core/src/consul/archive.rs b/crates/dbx-core/src/consul/archive.rs
new file mode 100644
index 0000000000..0b5a5fa0aa
--- /dev/null
+++ b/crates/dbx-core/src/consul/archive.rs
@@ -0,0 +1,617 @@
+use std::collections::HashSet;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::{KvInt64, KvValue};
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::kv::{ConsulKvRecord, MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES};
+use super::txn::{cas_operation, ConsulTxnRequest, MAX_TXN_OPERATIONS};
+
+const CONSUL_BUNDLE_FORMAT: &str = "dbx-consul-kv-bundle";
+const CONSUL_BUNDLE_VERSION: u32 = 1;
+const MAX_VALUE_BYTES: usize = 512 * 1024;
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulExportScopeKind {
+ Key,
+ Prefix,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulExportRequest {
+ pub path: String,
+ pub kind: ConsulExportScopeKind,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulBundleScope {
+ pub datacenter: String,
+ pub namespace: String,
+ pub partition: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulBundleEntry {
+ pub key: String,
+ pub value: KvValue,
+ pub flags: KvInt64,
+ pub create_index: Option<KvInt64>,
+ pub modify_index: Option<KvInt64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulKvBundle {
+ pub format: String,
+ pub version: u32,
+ pub exported_at_unix_ms: u64,
+ pub prefix: String,
+ pub scope_kind: ConsulExportScopeKind,
+ pub source: ConsulBundleScope,
+ pub entries: Vec<ConsulBundleEntry>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulImportConflictPolicy {
+ Abort,
+ Skip,
+ Cas,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulImportOperation {
+ Create,
+ Update,
+ Unchanged,
+ Skipped,
+ Conflict,
+ Locked,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportPreviewRow {
+ pub key: String,
+ pub operation: ConsulImportOperation,
+ pub expected_modify_index: Option<KvInt64>,
+ pub target_session: Option<String>,
+ pub reason: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportPreview {
+ pub preview_id: String,
+ pub rows: Vec<ConsulImportPreviewRow>,
+ pub can_apply: bool,
+ pub creates: usize,
+ pub updates: usize,
+ pub unchanged: usize,
+ pub skipped: usize,
+ pub conflicts: usize,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportRequest {
+ pub bundle: ConsulKvBundle,
+ pub policy: ConsulImportConflictPolicy,
+ #[serde(default)]
+ pub preview_id: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulImportOutcome {
+ Succeeded,
+ Conflicted,
+ Skipped,
+ Failed,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportResultItem {
+ pub key: String,
+ pub outcome: ConsulImportOutcome,
+ pub message: Option<String>,
+ pub batch: Option<usize>,
+ pub op_index: Option<usize>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportReport {
+ pub items: Vec<ConsulImportResultItem>,
+ pub succeeded: usize,
+ pub conflicted: usize,
+ pub skipped: usize,
+ pub failed: usize,
+ pub atomic: bool,
+}
+
+pub async fn consul_export_bundle_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulExportRequest,
+) -> Result<ConsulKvBundle, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let entries = match request.kind {
+ ConsulExportScopeKind::Key => {
+ let value = client.get_key(&request.path).await?;
+ if !value.found {
+ return Err("CONSUL_KEY_NOT_FOUND: The Consul KV key no longer exists".to_string());
+ }
+ let metadata = value.metadata.unwrap_or_else(empty_metadata);
+ vec![ConsulBundleEntry {
+ key: value.key.unwrap_or(request.path.clone()),
+ value: value.value.ok_or("Consul returned a KV key without a value")?,
+ flags: metadata.flags.unwrap_or_else(|| KvInt64("0".to_string())),
+ create_index: metadata.create_revision,
+ modify_index: metadata.mod_revision,
+ }]
+ }
+ ConsulExportScopeKind::Prefix => {
+ let recursive =
+ client.list_recursive(&request.path, MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES).await?;
+ if recursive.filtered_by_acls == Some(true) {
+ return Err(
+ "CONSUL_EXPORT_ACL_FILTERED: Export is blocked because ACL policies hide part of the prefix"
+ .to_string(),
+ );
+ }
+ recursive.entries.into_iter().map(bundle_entry_from_record).collect()
+ }
+ };
+ Ok(ConsulKvBundle {
+ format: CONSUL_BUNDLE_FORMAT.to_string(),
+ version: CONSUL_BUNDLE_VERSION,
+ exported_at_unix_ms: SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as u64,
+ prefix: request.path,
+ scope_kind: request.kind,
+ source: ConsulBundleScope {
+ datacenter: client.datacenter().to_string(),
+ namespace: client.namespace().to_string(),
+ partition: client.partition().to_string(),
+ },
+ entries,
+ })
+}
+
+pub async fn consul_import_preview_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulImportRequest,
+) -> Result<ConsulImportPreview, String> {
+ validate_bundle(&request.bundle)?;
+ let client = client_for_state(state, connection_id).await?;
+ build_preview(&client, connection_id, &request.bundle, request.policy).await
+}
+
+pub async fn consul_import_execute_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulImportRequest,
+) -> Result<ConsulImportReport, String> {
+ ensure_writable_core(state, connection_id, "import Consul KV bundle").await?;
+ validate_bundle(&request.bundle)?;
+ let client = client_for_state(state, connection_id).await?;
+ let preview = build_preview(&client, connection_id, &request.bundle, request.policy).await?;
+ if request.preview_id.as_deref() != Some(preview.preview_id.as_str()) {
+ return Err(
+ "CONSUL_IMPORT_PREVIEW_STALE: Target state changed after preview; refresh before importing".to_string()
+ );
+ }
+ if !preview.can_apply {
+ return Ok(report_from_blocked_preview(preview));
+ }
+
+ let preview_by_key =
+ preview.rows.into_iter().map(|row| (row.key.clone(), row)).collect::<std::collections::HashMap<_, _>>();
+ let mut items = Vec::with_capacity(request.bundle.entries.len());
+ let mut sources = request.bundle.entries;
+ sources.sort_by(|left, right| left.key.cmp(&right.key));
+ let mut pending = Vec::new();
+ for source in sources {
+ let Some(row) = preview_by_key.get(&source.key) else {
+ continue;
+ };
+ match row.operation {
+ ConsulImportOperation::Unchanged | ConsulImportOperation::Skipped => {
+ items.push(result_item(source.key, ConsulImportOutcome::Skipped, row.reason.clone(), None, None));
+ }
+ ConsulImportOperation::Conflict | ConsulImportOperation::Locked => {
+ items.push(result_item(source.key, ConsulImportOutcome::Conflicted, row.reason.clone(), None, None));
+ }
+ ConsulImportOperation::Create | ConsulImportOperation::Update => {
+ let index = row.expected_modify_index.clone().unwrap_or_else(|| KvInt64("0".to_string()));
+ pending.push((source.key.clone(), cas_operation(source.key, source.value, source.flags, index)));
+ }
+ }
+ }
+ let atomic = pending.len() <= MAX_TXN_OPERATIONS;
+ for (batch_index, chunk) in pending.chunks(MAX_TXN_OPERATIONS).enumerate() {
+ let result = client
+ .txn(ConsulTxnRequest { operations: chunk.iter().map(|(_, operation)| operation.clone()).collect() })
+ .await;
+ match result {
+ Ok(result) if result.committed => {
+ items.extend(chunk.iter().enumerate().map(|(op_index, (key, _))| {
+ result_item(key.clone(), ConsulImportOutcome::Succeeded, None, Some(batch_index), Some(op_index))
+ }));
+ }
+ Ok(result) => {
+ for (op_index, (key, _)) in chunk.iter().enumerate() {
+ let error = result.errors.iter().find(|error| error.op_index == op_index);
+ items.push(result_item(
+ key.clone(),
+ if error.is_some() { ConsulImportOutcome::Conflicted } else { ConsulImportOutcome::Failed },
+ Some(
+ error
+ .map(|error| error.message.clone())
+ .unwrap_or_else(|| "Transaction batch was aborted".to_string()),
+ ),
+ Some(batch_index),
+ Some(op_index),
+ ));
+ }
+ }
+ Err(error) => items.extend(chunk.iter().enumerate().map(|(op_index, (key, _))| {
+ result_item(
+ key.clone(),
+ ConsulImportOutcome::Failed,
+ Some(error.clone()),
+ Some(batch_index),
+ Some(op_index),
+ )
+ })),
+ }
+ }
+ Ok(summarize_report(items, atomic))
+}
+
+async fn build_preview(
+ client: &ConsulClient,
+ connection_id: &str,
+ bundle: &ConsulKvBundle,
+ policy: ConsulImportConflictPolicy,
+) -> Result<ConsulImportPreview, String> {
+ let mut rows = Vec::with_capacity(bundle.entries.len());
+ for source in &bundle.entries {
+ let target = client.get_key(&source.key).await?;
+ let row = if !target.found {
+ ConsulImportPreviewRow {
+ key: source.key.clone(),
+ operation: ConsulImportOperation::Create,
+ expected_modify_index: None,
+ target_session: None,
+ reason: None,
+ }
+ } else {
+ preview_existing(source, target, policy)
+ };
+ rows.push(row);
+ }
+ let creates = count_operation(&rows, ConsulImportOperation::Create);
+ let updates = count_operation(&rows, ConsulImportOperation::Update);
+ let unchanged = count_operation(&rows, ConsulImportOperation::Unchanged);
+ let skipped = count_operation(&rows, ConsulImportOperation::Skipped);
+ let conflicts =
+ count_operation(&rows, ConsulImportOperation::Conflict) + count_operation(&rows, ConsulImportOperation::Locked);
+ let can_apply = conflicts == 0 || policy != ConsulImportConflictPolicy::Abort;
+ let preview_id = preview_id(&rows, bundle, policy, connection_id, client);
+ Ok(ConsulImportPreview { preview_id, rows, can_apply, creates, updates, unchanged, skipped, conflicts })
+}
+
+fn preview_existing(
+ source: &ConsulBundleEntry,
+ target: crate::agent_kv::KvGetResponse,
+ policy: ConsulImportConflictPolicy,
+) -> ConsulImportPreviewRow {
+ let metadata = target.metadata.unwrap_or_else(empty_metadata);
+ let target_session = metadata.session.filter(|session| !session.is_empty());
+ if target_session.is_some() {
+ return ConsulImportPreviewRow {
+ key: source.key.clone(),
+ operation: ConsulImportOperation::Locked,
+ expected_modify_index: metadata.mod_revision,
+ target_session,
+ reason: Some("Target key is held by a Consul Session".to_string()),
+ };
+ }
+ let target_flags = metadata.flags.unwrap_or_else(|| KvInt64("0".to_string()));
+ if target.value.as_ref() == Some(&source.value) && target_flags == source.flags {
+ return ConsulImportPreviewRow {
+ key: source.key.clone(),
+ operation: ConsulImportOperation::Unchanged,
+ expected_modify_index: metadata.mod_revision,
+ target_session: None,
+ reason: None,
+ };
+ }
+ let (operation, reason) = match policy {
+ ConsulImportConflictPolicy::Abort => {
+ (ConsulImportOperation::Conflict, Some("Target key exists with a different value or Flags".to_string()))
+ }
+ ConsulImportConflictPolicy::Skip => {
+ (ConsulImportOperation::Skipped, Some("Existing target key is skipped by the selected policy".to_string()))
+ }
+ ConsulImportConflictPolicy::Cas => (ConsulImportOperation::Update, None),
+ };
+ ConsulImportPreviewRow {
+ key: source.key.clone(),
+ operation,
+ expected_modify_index: metadata.mod_revision,
+ target_session: None,
+ reason,
+ }
+}
+
+fn validate_bundle(bundle: &ConsulKvBundle) -> Result<(), String> {
+ if bundle.format != CONSUL_BUNDLE_FORMAT || bundle.version != CONSUL_BUNDLE_VERSION {
+ return Err("CONSUL_BUNDLE_UNSUPPORTED: Expected DBX Consul KV bundle version 1".to_string());
+ }
+ if bundle.entries.len() > MAX_RECURSIVE_ENTRIES {
+ return Err(format!("CONSUL_BUNDLE_TOO_LARGE: Bundle contains more than {MAX_RECURSIVE_ENTRIES} keys"));
+ }
+ let mut keys = HashSet::with_capacity(bundle.entries.len());
+ let mut total_bytes = 0usize;
+ for entry in &bundle.entries {
+ if entry.key.is_empty() {
+ return Err("CONSUL_BUNDLE_INVALID: Bundle contains an empty key".to_string());
+ }
+ if !keys.insert(&entry.key) {
+ return Err(format!("CONSUL_BUNDLE_INVALID: Duplicate key in bundle: {}", entry.key));
+ }
+ entry
+ .flags
+ .as_str()
+ .parse::<u64>()
+ .map_err(|_| format!("CONSUL_BUNDLE_INVALID: Invalid Flags for key {}", entry.key))?;
+ let value_bytes = value_size(&entry.value)?;
+ if value_bytes > MAX_VALUE_BYTES {
+ return Err(format!("CONSUL_VALUE_TOO_LARGE: Bundle value exceeds 512 KiB for key {}", entry.key));
+ }
+ total_bytes = total_bytes.saturating_add(value_bytes);
+ if total_bytes > MAX_RECURSIVE_VALUE_BYTES {
+ return Err("CONSUL_BUNDLE_TOO_LARGE: Bundle values exceed 32 MiB".to_string());
+ }
+ }
+ Ok(())
+}
+
+fn value_size(value: &KvValue) -> Result<usize, String> {
+ match value.encoding {
+ crate::agent_kv::KvValueEncoding::Utf8 => Ok(value.data.len()),
+ crate::agent_kv::KvValueEncoding::Base64 => {
+ use base64::Engine;
+ base64::engine::general_purpose::STANDARD
+ .decode(value.data.chars().filter(|char| !char.is_whitespace()).collect::<String>())
+ .map(|bytes| bytes.len())
+ .map_err(|error| format!("CONSUL_BUNDLE_INVALID: Invalid Base64 value: {error}"))
+ }
+ }
+}
+
+fn bundle_entry_from_record(record: ConsulKvRecord) -> ConsulBundleEntry {
+ ConsulBundleEntry {
+ key: record.key,
+ value: record.value,
+ flags: record.flags,
+ create_index: Some(record.create_index),
+ modify_index: Some(record.modify_index),
+ }
+}
+
+fn report_from_blocked_preview(preview: ConsulImportPreview) -> ConsulImportReport {
+ let items = preview
+ .rows
+ .into_iter()
+ .map(|row| {
+ let outcome = if matches!(row.operation, ConsulImportOperation::Conflict | ConsulImportOperation::Locked) {
+ ConsulImportOutcome::Conflicted
+ } else {
+ ConsulImportOutcome::Skipped
+ };
+ result_item(row.key, outcome, row.reason, None, None)
+ })
+ .collect();
+ summarize_report(items, false)
+}
+
+fn summarize_report(items: Vec<ConsulImportResultItem>, atomic: bool) -> ConsulImportReport {
+ let succeeded = items.iter().filter(|item| item.outcome == ConsulImportOutcome::Succeeded).count();
+ let conflicted = items.iter().filter(|item| item.outcome == ConsulImportOutcome::Conflicted).count();
+ let skipped = items.iter().filter(|item| item.outcome == ConsulImportOutcome::Skipped).count();
+ let failed = items.iter().filter(|item| item.outcome == ConsulImportOutcome::Failed).count();
+ ConsulImportReport { items, succeeded, conflicted, skipped, failed, atomic }
+}
+
+fn result_item(
+ key: String,
+ outcome: ConsulImportOutcome,
+ message: Option<String>,
+ batch: Option<usize>,
+ op_index: Option<usize>,
+) -> ConsulImportResultItem {
+ ConsulImportResultItem { key, outcome, message, batch, op_index }
+}
+
+fn preview_id(
+ rows: &[ConsulImportPreviewRow],
+ bundle: &ConsulKvBundle,
+ policy: ConsulImportConflictPolicy,
+ connection_id: &str,
+ client: &ConsulClient,
+) -> String {
+ preview_id_for_scope(rows, bundle, policy, connection_id, &client.scope())
+}
+
+fn preview_id_for_scope(
+ rows: &[ConsulImportPreviewRow],
+ bundle: &ConsulKvBundle,
+ policy: ConsulImportConflictPolicy,
+ connection_id: &str,
+ scope: &super::ConsulScope,
+) -> String {
+ let mut hash = 0xcbf29ce484222325u64;
+ let canonical = serde_json::to_vec(&(connection_id, scope, bundle, policy, rows)).unwrap_or_default();
+ for byte in canonical {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ format!("consul-preview-{hash:016x}")
+}
+
+fn count_operation(rows: &[ConsulImportPreviewRow], operation: ConsulImportOperation) -> usize {
+ rows.iter().filter(|row| row.operation == operation).count()
+}
+
+fn empty_metadata() -> crate::agent_kv::KvKeyMetadata {
+ crate::agent_kv::KvKeyMetadata {
+ create_revision: None,
+ mod_revision: None,
+ version: None,
+ lease: None,
+ ttl: None,
+ value_size: None,
+ czxid: None,
+ mzxid: None,
+ pzxid: None,
+ ctime: None,
+ mtime: None,
+ cversion: None,
+ aversion: None,
+ ephemeral_owner: None,
+ data_length: None,
+ num_children: None,
+ flags: None,
+ lock_index: None,
+ session: None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::agent_kv::{KvGetResponse, KvKeyMetadata, KvValueEncoding};
+
+ #[test]
+ fn bundle_validation_rejects_wrong_format_and_duplicate_keys() {
+ let mut bundle = test_bundle();
+ bundle.format = "wrong".to_string();
+ assert!(validate_bundle(&bundle).unwrap_err().contains("CONSUL_BUNDLE_UNSUPPORTED"));
+
+ let mut bundle = test_bundle();
+ bundle.entries.push(bundle.entries[0].clone());
+ assert!(validate_bundle(&bundle).unwrap_err().contains("Duplicate key"));
+ }
+
+ #[test]
+ fn bundle_round_trips_binary_values_and_u64_flags_without_sensitive_fields() {
+ let mut bundle = test_bundle();
+ bundle.entries[0].value = KvValue { encoding: KvValueEncoding::Base64, data: "AP+A".into() };
+ bundle.entries[0].flags = KvInt64(u64::MAX.to_string());
+ let encoded = serde_json::to_string(&bundle).unwrap();
+ for forbidden in ["SecretID", "X-Consul-Token", "session", "lockIndex"] {
+ assert!(!encoded.contains(forbidden));
+ }
+ let decoded: ConsulKvBundle = serde_json::from_str(&encoded).unwrap();
+ assert_eq!(decoded.entries[0].value.data, "AP+A");
+ assert_eq!(decoded.entries[0].flags.as_str(), u64::MAX.to_string());
+ }
+
+ #[test]
+ fn existing_key_policy_is_explicit() {
+ let source = test_bundle().entries.remove(0);
+ let target = || KvGetResponse {
+ key: Some(source.key.clone()),
+ key_bytes: None,
+ found: true,
+ value: Some(KvValue { encoding: KvValueEncoding::Utf8, data: "different".to_string() }),
+ metadata: Some(KvKeyMetadata { mod_revision: Some(KvInt64("9".to_string())), ..empty_metadata() }),
+ };
+
+ assert_eq!(
+ preview_existing(&source, target(), ConsulImportConflictPolicy::Abort).operation,
+ ConsulImportOperation::Conflict
+ );
+ assert_eq!(
+ preview_existing(&source, target(), ConsulImportConflictPolicy::Skip).operation,
+ ConsulImportOperation::Skipped
+ );
+ assert_eq!(
+ preview_existing(&source, target(), ConsulImportConflictPolicy::Cas).operation,
+ ConsulImportOperation::Update
+ );
+ }
+
+ #[test]
+ fn preview_id_binds_target_state_bundle_content_and_policy() {
+ let scope = super::super::ConsulScope {
+ datacenter: "dc1".into(),
+ namespace: "team".into(),
+ partition: "default".into(),
+ };
+ let bundle = test_bundle();
+ let row = |index: &str| ConsulImportPreviewRow {
+ key: "app/key".into(),
+ operation: ConsulImportOperation::Update,
+ expected_modify_index: Some(KvInt64(index.into())),
+ target_session: None,
+ reason: None,
+ };
+
+ let initial = preview_id_for_scope(&[row("9")], &bundle, ConsulImportConflictPolicy::Cas, "target-a", &scope);
+ assert_ne!(
+ initial,
+ preview_id_for_scope(&[row("10")], &bundle, ConsulImportConflictPolicy::Cas, "target-a", &scope)
+ );
+ assert_ne!(
+ initial,
+ preview_id_for_scope(&[row("9")], &bundle, ConsulImportConflictPolicy::Cas, "target-b", &scope)
+ );
+
+ let mut changed_bundle = bundle.clone();
+ changed_bundle.entries[0].value.data = "changed-after-preview".into();
+ assert_ne!(
+ initial,
+ preview_id_for_scope(&[row("9")], &changed_bundle, ConsulImportConflictPolicy::Cas, "target-a", &scope)
+ );
+ assert_ne!(
+ initial,
+ preview_id_for_scope(&[row("9")], &bundle, ConsulImportConflictPolicy::Skip, "target-a", &scope)
+ );
+ }
+
+ fn test_bundle() -> ConsulKvBundle {
+ ConsulKvBundle {
+ format: CONSUL_BUNDLE_FORMAT.into(),
+ version: CONSUL_BUNDLE_VERSION,
+ exported_at_unix_ms: 1,
+ prefix: "app/".into(),
+ scope_kind: ConsulExportScopeKind::Prefix,
+ source: ConsulBundleScope {
+ datacenter: "dc1".into(),
+ namespace: "team".into(),
+ partition: "default".into(),
+ },
+ entries: vec![ConsulBundleEntry {
+ key: "app/key".into(),
+ value: KvValue { encoding: KvValueEncoding::Utf8, data: "value".into() },
+ flags: KvInt64("0".into()),
+ create_index: Some(KvInt64("1".into())),
+ modify_index: Some(KvInt64("2".into())),
+ }],
+ }
+ }
+}
diff --git a/crates/dbx-core/src/consul/blocking.rs b/crates/dbx-core/src/consul/blocking.rs
new file mode 100644
index 0000000000..fa08967408
--- /dev/null
+++ b/crates/dbx-core/src/consul/blocking.rs
@@ -0,0 +1,540 @@
+use std::collections::{BTreeMap, HashMap};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::{KvInt64, KvValue, KvValueEncoding};
+use crate::connection::AppState;
+
+use super::catalog::{ConsulCatalogNode, ConsulCatalogServiceNode, ConsulNodeServices};
+use super::client::client_for_state;
+use super::health::{mark_maintenance, ConsulHealthCheck, ConsulServiceInstance};
+use super::kv::ConsulKvRecord;
+use super::response::{
+ decode_json_body, ensure_success, is_consul_kv_not_found, read_bounded_response, ConsulResponseMetadata,
+};
+use super::types::ConsulKvEntry;
+
+const MIN_QUERY_INTERVAL: Duration = Duration::from_millis(100);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulBlockingRequest {
+ pub operation_id: String,
+ #[serde(default)]
+ pub generation: u64,
+ pub key: String,
+ pub prefix: bool,
+ pub index: Option<KvInt64>,
+ pub wait_seconds: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulBlockingResponse {
+ pub entries: Vec<ConsulKvRecord>,
+ pub metadata: ConsulResponseMetadata,
+ pub changed: bool,
+ pub timed_out: bool,
+ pub index_reset: bool,
+}
+
+/// A non-KV Consul endpoint with blocking-query support.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum ConsulDomainWatchTarget {
+ CatalogNodes,
+ CatalogServices,
+ CatalogServiceNodes { service: String },
+ CatalogNodeServices { node: String },
+ HealthNode { node: String },
+ HealthServiceChecks { service: String },
+ HealthServiceInstances { service: String, passing: Option<bool> },
+ HealthState { state: String },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDomainWatchRequest {
+ pub operation_id: String,
+ #[serde(default)]
+ pub generation: u64,
+ pub target: ConsulDomainWatchTarget,
+ pub index: Option<KvInt64>,
+ pub wait_seconds: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDomainWatchResponse {
+ pub items: ConsulDomainWatchItems,
+ pub metadata: ConsulResponseMetadata,
+ pub changed: bool,
+ pub timed_out: bool,
+ pub index_reset: bool,
+}
+
+/// Each allowed watch target has an explicit response shape. The untagged
+/// representation preserves Consul's native JSON body for the UI transport.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum ConsulDomainWatchItems {
+ CatalogNodes(Vec<ConsulCatalogNode>),
+ CatalogServices(BTreeMap<String, Vec<String>>),
+ CatalogServiceNodes(Vec<ConsulCatalogServiceNode>),
+ CatalogNodeServices(ConsulNodeServices),
+ HealthNode(Vec<ConsulHealthCheck>),
+ HealthServiceChecks(Vec<ConsulHealthCheck>),
+ HealthServiceInstances(Vec<ConsulServiceInstance>),
+ HealthState(Vec<ConsulHealthCheck>),
+}
+
+#[derive(Default)]
+struct BlockingControl {
+ cancelled: AtomicBool,
+}
+
+struct BlockingRegistration(String);
+
+impl Drop for BlockingRegistration {
+ fn drop(&mut self) {
+ if let Ok(mut registry) = blocking_registry().lock() {
+ registry.remove(&self.0);
+ }
+ }
+}
+
+static BLOCKING: OnceLock<Mutex<HashMap<String, Arc<BlockingControl>>>> = OnceLock::new();
+
+pub async fn consul_blocking_query_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulBlockingRequest,
+) -> Result<ConsulBlockingResponse, String> {
+ validate_request(&request)?;
+ let client = client_for_state(state, connection_id).await?;
+ let scope = client.scope();
+ let registry_key = format!(
+ "{connection_id}\0{}\0{}\0{}\0{}\0{}",
+ scope.datacenter, scope.partition, scope.namespace, request.generation, request.operation_id
+ );
+ let control = Arc::new(BlockingControl::default());
+ {
+ let mut registry =
+ blocking_registry().lock().map_err(|_| "Consul blocking registry is unavailable".to_string())?;
+ if registry.contains_key(&registry_key) {
+ return Err("CONSUL_OPERATION_ALREADY_RUNNING: A blocking query with this operation ID is already running"
+ .to_string());
+ }
+ registry.insert(registry_key.clone(), Arc::clone(&control));
+ }
+ let _registration = BlockingRegistration(registry_key);
+
+ let requested_index = request.index.as_ref().map(parse_index).transpose()?.unwrap_or(1).max(1);
+ let started = Instant::now();
+ let future = blocking_request(&client, &request, requested_index);
+ tokio::pin!(future);
+ let mut cancel_tick = tokio::time::interval(Duration::from_millis(50));
+ let mut response = loop {
+ tokio::select! {
+ response = &mut future => break response?,
+ _ = cancel_tick.tick() => {
+ if control.cancelled.load(Ordering::Acquire) {
+ return Err("CONSUL_BLOCKING_CANCELLED: Consul blocking query was cancelled".to_string());
+ }
+ }
+ }
+ };
+ if control.cancelled.load(Ordering::Acquire) {
+ return Err("CONSUL_BLOCKING_CANCELLED: Consul blocking query was cancelled".to_string());
+ }
+
+ let returned_index = response.metadata.index.as_ref().map(parse_index).transpose()?.unwrap_or(0);
+ response.index_reset = returned_index == 0 || returned_index < requested_index;
+ response.changed = !response.index_reset && returned_index > requested_index;
+ response.timed_out =
+ !response.changed && started.elapsed() >= Duration::from_secs(request.wait_seconds.saturating_sub(1));
+ if started.elapsed() < MIN_QUERY_INTERVAL {
+ tokio::time::sleep(MIN_QUERY_INTERVAL - started.elapsed()).await;
+ }
+ Ok(response)
+}
+
+/// Runs a Catalog or Health blocking query under the same cancellable registry as KV watches.
+pub async fn consul_domain_watch_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulDomainWatchRequest,
+) -> Result<ConsulDomainWatchResponse, String> {
+ validate_domain_watch_request(&request)?;
+ let client = client_for_state(state, connection_id).await?;
+ let scope = client.scope();
+ let registry_key = format!(
+ "{connection_id}\0{}\0{}\0{}\0{}\0{}",
+ scope.datacenter, scope.partition, scope.namespace, request.generation, request.operation_id
+ );
+ let control = Arc::new(BlockingControl::default());
+ {
+ let mut registry =
+ blocking_registry().lock().map_err(|_| "Consul blocking registry is unavailable".to_string())?;
+ if registry.contains_key(&registry_key) {
+ return Err("CONSUL_OPERATION_ALREADY_RUNNING: A blocking query with this operation ID is already running"
+ .to_string());
+ }
+ registry.insert(registry_key.clone(), Arc::clone(&control));
+ }
+ let _registration = BlockingRegistration(registry_key);
+ let requested_index = request.index.as_ref().map(parse_index).transpose()?.unwrap_or(1).max(1);
+ let started = Instant::now();
+ let future = domain_watch_request(&client, &request, requested_index);
+ tokio::pin!(future);
+ let mut cancel_tick = tokio::time::interval(Duration::from_millis(50));
+ let mut response = loop {
+ tokio::select! {
+ response = &mut future => break response?,
+ _ = cancel_tick.tick() => {
+ if control.cancelled.load(Ordering::Acquire) {
+ return Err("CONSUL_BLOCKING_CANCELLED: Consul blocking query was cancelled".to_string());
+ }
+ }
+ }
+ };
+ if control.cancelled.load(Ordering::Acquire) {
+ return Err("CONSUL_BLOCKING_CANCELLED: Consul blocking query was cancelled".to_string());
+ }
+ let returned_index = response.metadata.index.as_ref().map(parse_index).transpose()?.unwrap_or(0);
+ response.index_reset = returned_index == 0 || returned_index < requested_index;
+ response.changed = !response.index_reset && returned_index > requested_index;
+ response.timed_out =
+ !response.changed && started.elapsed() >= Duration::from_secs(request.wait_seconds.saturating_sub(1));
+ if started.elapsed() < MIN_QUERY_INTERVAL {
+ tokio::time::sleep(MIN_QUERY_INTERVAL - started.elapsed()).await;
+ }
+ Ok(response)
+}
+
+pub fn consul_cancel_blocking_core(
+ connection_id: &str,
+ scope: &super::ConsulScope,
+ generation: u64,
+ operation_id: &str,
+) -> bool {
+ let key = format!(
+ "{connection_id}\0{}\0{}\0{}\0{generation}\0{operation_id}",
+ scope.datacenter, scope.partition, scope.namespace
+ );
+ let control = blocking_registry().lock().ok().and_then(|registry| registry.get(&key).cloned());
+ control.is_some_and(|control| {
+ control.cancelled.store(true, Ordering::Release);
+ true
+ })
+}
+
+async fn blocking_request(
+ client: &super::ConsulClient,
+ request: &ConsulBlockingRequest,
+ requested_index: u64,
+) -> Result<ConsulBlockingResponse, String> {
+ let encoded = request
+ .key
+ .split('/')
+ .map(|segment| utf8_percent_encode(segment, NON_ALPHANUMERIC).to_string())
+ .collect::<Vec<_>>()
+ .join("/");
+ let mut url = client.api_url(&format!("/v1/kv/{encoded}"))?;
+ client.append_scope(&mut url, true);
+ {
+ let mut query = url.query_pairs_mut();
+ query.append_pair("index", &requested_index.to_string());
+ query.append_pair("wait", &format!("{}s", request.wait_seconds.clamp(1, 600)));
+ if request.prefix {
+ query.append_pair("recurse", "");
+ }
+ }
+ let response = client.send(Method::GET, url, None).await?;
+ let metadata = ConsulResponseMetadata::from_response(&response);
+ if is_consul_kv_not_found(&response) {
+ return Ok(ConsulBlockingResponse {
+ entries: Vec::new(),
+ metadata,
+ changed: false,
+ timed_out: false,
+ index_reset: false,
+ });
+ }
+ if !response.status().is_success() {
+ return ensure_success(response, "watch Consul KV", client.token()).await.map(|_| unreachable!());
+ }
+ let body = read_bounded_response(response, "watch Consul KV").await?;
+ let entries = decode_json_body::<Vec<ConsulKvEntry>>(&body, "watch Consul KV")?
+ .into_iter()
+ .map(record_from_entry)
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(ConsulBlockingResponse { entries, metadata, changed: false, timed_out: false, index_reset: false })
+}
+
+async fn domain_watch_request(
+ client: &super::ConsulClient,
+ request: &ConsulDomainWatchRequest,
+ requested_index: u64,
+) -> Result<ConsulDomainWatchResponse, String> {
+ let (path, action) = match &request.target {
+ ConsulDomainWatchTarget::CatalogNodes => ("/v1/catalog/nodes".to_string(), "watch Consul catalog nodes"),
+ ConsulDomainWatchTarget::CatalogServices => {
+ ("/v1/catalog/services".to_string(), "watch Consul catalog services")
+ }
+ ConsulDomainWatchTarget::CatalogServiceNodes { service } => {
+ (format!("/v1/catalog/service/{}", encode_path_segment(service)), "watch Consul catalog service instances")
+ }
+ ConsulDomainWatchTarget::CatalogNodeServices { node } => {
+ (format!("/v1/catalog/node/{}", encode_path_segment(node)), "watch Consul catalog node services")
+ }
+ ConsulDomainWatchTarget::HealthNode { node } => {
+ (format!("/v1/health/node/{}", encode_path_segment(node)), "watch Consul node health")
+ }
+ ConsulDomainWatchTarget::HealthServiceChecks { service } => {
+ (format!("/v1/health/checks/{}", encode_path_segment(service)), "watch Consul service checks")
+ }
+ ConsulDomainWatchTarget::HealthServiceInstances { service, passing } => {
+ let suffix = passing.map(|value| format!("?passing={value}")).unwrap_or_default();
+ (format!("/v1/health/service/{}{suffix}", encode_path_segment(service)), "watch Consul service instances")
+ }
+ ConsulDomainWatchTarget::HealthState { state } => {
+ (format!("/v1/health/state/{}", state.trim().to_ascii_lowercase()), "watch Consul health state")
+ }
+ };
+ let mut url = client.api_url(&path)?;
+ client.append_scope(&mut url, true);
+ {
+ let mut query = url.query_pairs_mut();
+ query.append_pair("index", &requested_index.to_string());
+ query.append_pair("wait", &format!("{}s", request.wait_seconds.clamp(1, 600)));
+ }
+ let response = client.send(Method::GET, url, None).await?;
+ let metadata = ConsulResponseMetadata::from_response(&response);
+ if !response.status().is_success() {
+ return ensure_success(response, action, client.token()).await.map(|_| unreachable!());
+ }
+ let body = read_bounded_response(response, action).await?;
+ let items = match &request.target {
+ ConsulDomainWatchTarget::CatalogNodes => {
+ ConsulDomainWatchItems::CatalogNodes(decode_json_body::<Vec<ConsulCatalogNode>>(&body, action)?)
+ }
+ ConsulDomainWatchTarget::CatalogServices => {
+ ConsulDomainWatchItems::CatalogServices(decode_json_body::<BTreeMap<String, Vec<String>>>(&body, action)?)
+ }
+ ConsulDomainWatchTarget::CatalogServiceNodes { .. } => ConsulDomainWatchItems::CatalogServiceNodes(
+ decode_json_body::<Vec<ConsulCatalogServiceNode>>(&body, action)?,
+ ),
+ ConsulDomainWatchTarget::CatalogNodeServices { .. } => {
+ ConsulDomainWatchItems::CatalogNodeServices(decode_json_body::<ConsulNodeServices>(&body, action)?)
+ }
+ ConsulDomainWatchTarget::HealthNode { .. } => {
+ ConsulDomainWatchItems::HealthNode(decode_health_checks(&body, action)?)
+ }
+ ConsulDomainWatchTarget::HealthServiceChecks { .. } => {
+ ConsulDomainWatchItems::HealthServiceChecks(decode_health_checks(&body, action)?)
+ }
+ ConsulDomainWatchTarget::HealthServiceInstances { .. } => {
+ let mut instances = decode_json_body::<Vec<ConsulServiceInstance>>(&body, action)?;
+ for instance in &mut instances {
+ mark_maintenance(&mut instance.checks);
+ }
+ ConsulDomainWatchItems::HealthServiceInstances(instances)
+ }
+ ConsulDomainWatchTarget::HealthState { .. } => {
+ ConsulDomainWatchItems::HealthState(decode_health_checks(&body, action)?)
+ }
+ };
+ Ok(ConsulDomainWatchResponse { items, metadata, changed: false, timed_out: false, index_reset: false })
+}
+
+fn decode_health_checks(body: &[u8], action: &str) -> Result<Vec<ConsulHealthCheck>, String> {
+ let mut checks = decode_json_body::<Vec<ConsulHealthCheck>>(body, action)?;
+ mark_maintenance(&mut checks);
+ Ok(checks)
+}
+
+fn record_from_entry(entry: ConsulKvEntry) -> Result<ConsulKvRecord, String> {
+ let bytes = entry
+ .value
+ .as_deref()
+ .filter(|value| !value.is_empty())
+ .map(|value| {
+ STANDARD.decode(value).map_err(|error| format!("Failed to decode Consul KV Base64 value: {error}"))
+ })
+ .transpose()?
+ .unwrap_or_default();
+ let value = match String::from_utf8(bytes.clone()) {
+ Ok(data) => KvValue { encoding: KvValueEncoding::Utf8, data },
+ Err(_) => KvValue { encoding: KvValueEncoding::Base64, data: STANDARD.encode(bytes) },
+ };
+ Ok(ConsulKvRecord {
+ key: entry.key,
+ value,
+ flags: KvInt64(entry.flags.to_string()),
+ create_index: KvInt64(entry.create_index.to_string()),
+ modify_index: KvInt64(entry.modify_index.to_string()),
+ lock_index: KvInt64(entry.lock_index.to_string()),
+ session: entry.session.filter(|session| !session.is_empty()),
+ })
+}
+
+fn validate_request(request: &ConsulBlockingRequest) -> Result<(), String> {
+ if request.operation_id.trim().is_empty() || request.operation_id.len() > 128 {
+ return Err("CONSUL_OPERATION_ID_INVALID: Blocking operation ID is invalid".to_string());
+ }
+ if request.wait_seconds == 0 || request.wait_seconds > 600 {
+ return Err("CONSUL_BLOCKING_WAIT_INVALID: Wait must be between 1 and 600 seconds".to_string());
+ }
+ Ok(())
+}
+
+fn validate_domain_watch_request(request: &ConsulDomainWatchRequest) -> Result<(), String> {
+ if request.operation_id.trim().is_empty() || request.operation_id.len() > 128 {
+ return Err("CONSUL_OPERATION_ID_INVALID: Blocking operation ID is invalid".to_string());
+ }
+ if request.wait_seconds == 0 || request.wait_seconds > 600 {
+ return Err("CONSUL_BLOCKING_WAIT_INVALID: Wait must be between 1 and 600 seconds".to_string());
+ }
+ match &request.target {
+ ConsulDomainWatchTarget::CatalogNodes | ConsulDomainWatchTarget::CatalogServices => Ok(()),
+ ConsulDomainWatchTarget::CatalogServiceNodes { service } if !service.trim().is_empty() => Ok(()),
+ ConsulDomainWatchTarget::CatalogNodeServices { node } | ConsulDomainWatchTarget::HealthNode { node }
+ if !node.trim().is_empty() =>
+ {
+ Ok(())
+ }
+ ConsulDomainWatchTarget::HealthServiceChecks { service }
+ | ConsulDomainWatchTarget::HealthServiceInstances { service, .. }
+ if !service.trim().is_empty() =>
+ {
+ Ok(())
+ }
+ ConsulDomainWatchTarget::HealthState { state }
+ if matches!(state.trim().to_ascii_lowercase().as_str(), "any" | "passing" | "warning" | "critical") =>
+ {
+ Ok(())
+ }
+ ConsulDomainWatchTarget::CatalogServiceNodes { .. }
+ | ConsulDomainWatchTarget::HealthServiceChecks { .. }
+ | ConsulDomainWatchTarget::HealthServiceInstances { .. } => {
+ Err("CONSUL_INVALID_REQUEST: service is required for watch".to_string())
+ }
+ ConsulDomainWatchTarget::CatalogNodeServices { .. } | ConsulDomainWatchTarget::HealthNode { .. } => {
+ Err("CONSUL_INVALID_REQUEST: node is required for watch".to_string())
+ }
+ ConsulDomainWatchTarget::HealthState { .. } => {
+ Err("CONSUL_INVALID_REQUEST: health state must be any, passing, warning, or critical".to_string())
+ }
+ }
+}
+
+fn encode_path_segment(value: &str) -> String {
+ utf8_percent_encode(value.trim(), NON_ALPHANUMERIC).to_string()
+}
+
+fn parse_index(value: &KvInt64) -> Result<u64, String> {
+ value
+ .as_str()
+ .parse::<u64>()
+ .map_err(|_| "CONSUL_BLOCKING_INDEX_INVALID: Index must be an unsigned 64-bit integer".to_string())
+}
+
+fn blocking_registry() -> &'static Mutex<HashMap<String, Arc<BlockingControl>>> {
+ BLOCKING.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::consul::test_support::{serve_once, test_client};
+
+ #[test]
+ fn rejects_zero_wait_and_invalid_index() {
+ let mut request = ConsulBlockingRequest {
+ operation_id: "watch".to_string(),
+ generation: 1,
+ key: "a".to_string(),
+ prefix: false,
+ index: Some(KvInt64("-1".to_string())),
+ wait_seconds: 0,
+ };
+ assert!(validate_request(&request).is_err());
+ request.wait_seconds = 10;
+ assert!(parse_index(request.index.as_ref().unwrap()).is_err());
+ }
+
+ #[test]
+ fn validates_catalog_and_health_watch_targets() {
+ let request = ConsulDomainWatchRequest {
+ operation_id: "catalog-watch".to_string(),
+ generation: 4,
+ target: ConsulDomainWatchTarget::CatalogServiceNodes { service: "web/api".to_string() },
+ index: Some(KvInt64("0".to_string())),
+ wait_seconds: 300,
+ };
+ assert!(validate_domain_watch_request(&request).is_ok());
+ assert_eq!(parse_index(request.index.as_ref().unwrap()).unwrap(), 0);
+
+ let invalid = ConsulDomainWatchRequest {
+ target: ConsulDomainWatchTarget::HealthState { state: "unknown".to_string() },
+ ..request
+ };
+ assert!(validate_domain_watch_request(&invalid).is_err());
+ }
+
+ #[test]
+ fn cancellation_is_bound_to_connection_scope_generation_and_operation() {
+ let scope = super::super::ConsulScope {
+ datacenter: "dc1".to_string(),
+ partition: "partition-a".to_string(),
+ namespace: "team-a".to_string(),
+ };
+ let key = format!("connection-a\0{}\0{}\0{}\0{}\0{}", "dc1", "partition-a", "team-a", 7, "watch-a");
+ let control = Arc::new(BlockingControl::default());
+ blocking_registry().lock().unwrap().insert(key.clone(), Arc::clone(&control));
+
+ assert!(!consul_cancel_blocking_core("connection-a", &scope, 8, "watch-a"));
+ assert!(!control.cancelled.load(Ordering::Acquire));
+ assert!(consul_cancel_blocking_core("connection-a", &scope, 7, "watch-a"));
+ assert!(control.cancelled.load(Ordering::Acquire));
+ blocking_registry().lock().unwrap().remove(&key);
+ }
+
+ #[tokio::test]
+ async fn blocking_kv_wire_uses_minimum_index_wait_scope_and_encoded_key() {
+ let body = r#"[{"Key":"app/a b","Value":"dmFsdWU=","Flags":0,"CreateIndex":1,"ModifyIndex":9,"LockIndex":0}]"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Consul-Index: 9\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let (url, request_rx) = serve_once(response).await;
+ let client = test_client(url).await;
+ let request = ConsulBlockingRequest {
+ operation_id: "watch-1".to_string(),
+ generation: 3,
+ key: "app/a b".to_string(),
+ prefix: true,
+ index: None,
+ wait_seconds: 10,
+ };
+ let result = blocking_request(&client, &request, 1).await.unwrap();
+
+ assert_eq!(result.metadata.index.as_ref().unwrap().as_str(), "9");
+ assert_eq!(result.entries[0].value.data, "value");
+ let raw = request_rx.await.unwrap();
+ let headers = raw.split_once("\r\n\r\n").unwrap().0;
+ assert!(headers.starts_with("GET /proxy/v1/kv/app/a%20b?"));
+ for query in ["dc=dc1", "ns=team-a", "partition=partition-a", "consistent", "index=1", "wait=10s", "recurse"] {
+ assert!(headers.contains(query), "missing query component {query}: {headers}");
+ }
+ assert!(headers.to_ascii_lowercase().contains("x-consul-token: fixture-token"));
+ }
+}
diff --git a/crates/dbx-core/src/consul/bulk.rs b/crates/dbx-core/src/consul/bulk.rs
new file mode 100644
index 0000000000..3ca4236177
--- /dev/null
+++ b/crates/dbx-core/src/consul/bulk.rs
@@ -0,0 +1,187 @@
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::KvInt64;
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core};
+use super::kv::{MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES};
+use super::txn::{delete_cas_operation, ConsulTxnRequest, MAX_TXN_OPERATIONS};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeleteCandidate {
+ pub key: String,
+ pub modify_index: KvInt64,
+ pub session: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeletePrefixPreview {
+ pub prefix: String,
+ pub candidates: Vec<ConsulDeleteCandidate>,
+ pub filtered_by_acls: Option<bool>,
+ pub complete: bool,
+ pub can_execute: bool,
+ pub locked: usize,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeletePrefixRequest {
+ pub prefix: String,
+ pub expected: Vec<ConsulDeleteCandidate>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulDeleteOutcome {
+ Succeeded,
+ Conflicted,
+ Failed,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeleteResultItem {
+ pub key: String,
+ pub outcome: ConsulDeleteOutcome,
+ pub message: Option<String>,
+ pub batch: Option<usize>,
+ pub op_index: Option<usize>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeletePrefixReport {
+ pub items: Vec<ConsulDeleteResultItem>,
+ pub succeeded: usize,
+ pub conflicted: usize,
+ pub failed: usize,
+ pub atomic: bool,
+}
+
+pub async fn consul_delete_prefix_preview_core(
+ state: &AppState,
+ connection_id: &str,
+ prefix: &str,
+) -> Result<ConsulDeletePrefixPreview, String> {
+ validate_prefix(prefix)?;
+ let client = client_for_state(state, connection_id).await?;
+ let recursive = client.list_recursive(prefix, MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES).await?;
+ let candidates = recursive
+ .entries
+ .into_iter()
+ .map(|entry| ConsulDeleteCandidate { key: entry.key, modify_index: entry.modify_index, session: entry.session })
+ .collect::<Vec<_>>();
+ let locked = candidates.iter().filter(|candidate| candidate.session.is_some()).count();
+ let can_execute =
+ recursive.complete && recursive.filtered_by_acls != Some(true) && locked == 0 && !candidates.is_empty();
+ Ok(ConsulDeletePrefixPreview {
+ prefix: prefix.to_string(),
+ candidates,
+ filtered_by_acls: recursive.filtered_by_acls,
+ complete: recursive.complete,
+ can_execute,
+ locked,
+ })
+}
+
+pub async fn consul_delete_prefix_execute_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulDeletePrefixRequest,
+) -> Result<ConsulDeletePrefixReport, String> {
+ ensure_writable_core(state, connection_id, "delete Consul KV prefix").await?;
+ validate_prefix(&request.prefix)?;
+ if request.expected.is_empty() || request.expected.len() > MAX_RECURSIVE_ENTRIES {
+ return Err("CONSUL_DELETE_PREVIEW_REQUIRED: A complete delete preview is required".to_string());
+ }
+ let preview = consul_delete_prefix_preview_core(state, connection_id, &request.prefix).await?;
+ if !preview.can_execute {
+ return Err(if preview.filtered_by_acls == Some(true) {
+ "CONSUL_DELETE_ACL_FILTERED: Prefix deletion is blocked because ACL policies hide keys".to_string()
+ } else if preview.locked > 0 {
+ format!("CONSUL_DELETE_LOCKED: Prefix contains {} Session-locked keys", preview.locked)
+ } else {
+ "CONSUL_DELETE_PREVIEW_INVALID: Prefix cannot be deleted from the current preview".to_string()
+ });
+ }
+ ensure_same_preview(&request.expected, &preview.candidates)?;
+
+ let client = client_for_state(state, connection_id).await?;
+ let mut candidates = preview.candidates;
+ candidates.sort_by(|left, right| left.key.cmp(&right.key));
+ let atomic = candidates.len() <= MAX_TXN_OPERATIONS;
+ let mut items = Vec::with_capacity(candidates.len());
+ for (batch_index, chunk) in candidates.chunks(MAX_TXN_OPERATIONS).enumerate() {
+ let operations = chunk
+ .iter()
+ .map(|candidate| delete_cas_operation(candidate.key.clone(), candidate.modify_index.clone()))
+ .collect();
+ match client.txn(ConsulTxnRequest { operations }).await {
+ Ok(result) if result.committed => {
+ items.extend(chunk.iter().enumerate().map(|(op_index, candidate)| ConsulDeleteResultItem {
+ key: candidate.key.clone(),
+ outcome: ConsulDeleteOutcome::Succeeded,
+ message: None,
+ batch: Some(batch_index),
+ op_index: Some(op_index),
+ }))
+ }
+ Ok(result) => {
+ for (op_index, candidate) in chunk.iter().enumerate() {
+ let error = result.errors.iter().find(|error| error.op_index == op_index);
+ items.push(ConsulDeleteResultItem {
+ key: candidate.key.clone(),
+ outcome: if error.is_some() {
+ ConsulDeleteOutcome::Conflicted
+ } else {
+ ConsulDeleteOutcome::Failed
+ },
+ message: Some(
+ error
+ .map(|error| error.message.clone())
+ .unwrap_or_else(|| "Transaction batch was aborted".to_string()),
+ ),
+ batch: Some(batch_index),
+ op_index: Some(op_index),
+ });
+ }
+ }
+ Err(error) => items.extend(chunk.iter().enumerate().map(|(op_index, candidate)| ConsulDeleteResultItem {
+ key: candidate.key.clone(),
+ outcome: ConsulDeleteOutcome::Failed,
+ message: Some(error.clone()),
+ batch: Some(batch_index),
+ op_index: Some(op_index),
+ })),
+ }
+ }
+ let succeeded = items.iter().filter(|item| item.outcome == ConsulDeleteOutcome::Succeeded).count();
+ let conflicted = items.iter().filter(|item| item.outcome == ConsulDeleteOutcome::Conflicted).count();
+ let failed = items.iter().filter(|item| item.outcome == ConsulDeleteOutcome::Failed).count();
+ Ok(ConsulDeletePrefixReport { items, succeeded, conflicted, failed, atomic })
+}
+
+fn ensure_same_preview(expected: &[ConsulDeleteCandidate], current: &[ConsulDeleteCandidate]) -> Result<(), String> {
+ let expected =
+ expected.iter().map(|candidate| (&candidate.key, candidate.modify_index.as_str())).collect::<BTreeMap<_, _>>();
+ let current =
+ current.iter().map(|candidate| (&candidate.key, candidate.modify_index.as_str())).collect::<BTreeMap<_, _>>();
+ if expected != current {
+ return Err(
+ "CONSUL_DELETE_PREVIEW_STALE: Prefix contents changed after preview; refresh before deleting".to_string()
+ );
+ }
+ Ok(())
+}
+
+fn validate_prefix(prefix: &str) -> Result<(), String> {
+ if prefix.trim().is_empty() {
+ return Err("CONSUL_DELETE_PREFIX_REQUIRED: Deleting the entire Consul KV root is not allowed".to_string());
+ }
+ Ok(())
+}
diff --git a/crates/dbx-core/src/consul/capabilities.rs b/crates/dbx-core/src/consul/capabilities.rs
new file mode 100644
index 0000000000..b7ee594c4c
--- /dev/null
+++ b/crates/dbx-core/src/consul/capabilities.rs
@@ -0,0 +1,247 @@
+use reqwest::{Method, StatusCode};
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ConsulClient};
+use super::response::decode_json_response;
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum ConsulCapabilityStatus {
+ Supported,
+ Unsupported,
+ Disabled,
+ Forbidden,
+ #[default]
+ Unknown,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulCapabilities {
+ pub version: Option<String>,
+ pub datacenter: Option<String>,
+ pub node_name: Option<String>,
+ pub server: Option<bool>,
+ pub edition: Option<String>,
+ pub agent: ConsulCapabilityStatus,
+ pub catalog: ConsulCapabilityStatus,
+ pub health: ConsulCapabilityStatus,
+ pub sessions: ConsulCapabilityStatus,
+ pub acl: ConsulCapabilityStatus,
+ pub auth_methods: ConsulCapabilityStatus,
+ pub binding_rules: ConsulCapabilityStatus,
+ pub templated_policies: ConsulCapabilityStatus,
+ pub namespaces: ConsulCapabilityStatus,
+ pub partitions: ConsulCapabilityStatus,
+ pub config_entries: ConsulCapabilityStatus,
+ pub intentions: ConsulCapabilityStatus,
+ pub peering: ConsulCapabilityStatus,
+ pub exported_services: ConsulCapabilityStatus,
+ pub prepared_queries: ConsulCapabilityStatus,
+ pub events: ConsulCapabilityStatus,
+ pub coordinates: ConsulCapabilityStatus,
+ pub operator_autopilot: ConsulCapabilityStatus,
+ pub operator_raft: ConsulCapabilityStatus,
+ pub operator_keyring: ConsulCapabilityStatus,
+ pub operator_usage: ConsulCapabilityStatus,
+ pub operator_license: ConsulCapabilityStatus,
+ pub audit: ConsulCapabilityStatus,
+}
+
+#[derive(Debug, Deserialize)]
+struct AgentSelfResponse {
+ #[serde(rename = "Config")]
+ config: AgentSelfConfig,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct AgentSelfConfig {
+ version: Option<String>,
+ datacenter: Option<String>,
+ node_name: Option<String>,
+ server: Option<bool>,
+}
+
+pub async fn consul_capabilities_core(state: &AppState, connection_id: &str) -> Result<ConsulCapabilities, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let (
+ mut capabilities,
+ acl,
+ auth_methods,
+ binding_rules,
+ templated_policies,
+ namespaces,
+ partitions,
+ config_entries,
+ intentions,
+ peering,
+ exported_services,
+ catalog,
+ health,
+ sessions,
+ prepared_queries,
+ events,
+ coordinates,
+ operator_autopilot,
+ operator_raft,
+ operator_keyring,
+ operator_usage,
+ operator_license,
+ audit,
+ ) = tokio::join!(
+ probe_agent(&client),
+ probe_acl_endpoint(&client),
+ probe_endpoint(&client, "/v1/acl/auth-methods"),
+ probe_endpoint(&client, "/v1/acl/binding-rules"),
+ probe_endpoint(&client, "/v1/acl/templated-policies"),
+ probe_endpoint(&client, "/v1/namespaces"),
+ probe_endpoint(&client, "/v1/partitions"),
+ probe_endpoint(&client, "/v1/config/service-defaults"),
+ probe_endpoint(&client, "/v1/connect/intentions"),
+ probe_endpoint(&client, "/v1/peerings"),
+ probe_endpoint(&client, "/v1/exported-services"),
+ probe_endpoint(&client, "/v1/catalog/datacenters"),
+ probe_endpoint(&client, "/v1/health/state/any"),
+ probe_endpoint(&client, "/v1/session/list"),
+ probe_endpoint(&client, "/v1/query"),
+ probe_endpoint(&client, "/v1/event/list"),
+ probe_endpoint(&client, "/v1/coordinate/nodes"),
+ probe_endpoint(&client, "/v1/operator/autopilot/configuration"),
+ probe_endpoint(&client, "/v1/operator/raft/configuration"),
+ probe_endpoint(&client, "/v1/operator/keyring"),
+ probe_endpoint(&client, "/v1/operator/usage"),
+ probe_endpoint(&client, "/v1/operator/license"),
+ probe_audit_endpoint(&client),
+ );
+ capabilities.acl = acl;
+ capabilities.auth_methods = auth_methods;
+ capabilities.binding_rules = binding_rules;
+ capabilities.templated_policies = templated_policies;
+ capabilities.namespaces = namespaces;
+ capabilities.partitions = partitions;
+ capabilities.config_entries = config_entries;
+ capabilities.intentions = intentions;
+ capabilities.peering = peering;
+ capabilities.exported_services = exported_services;
+ capabilities.catalog = catalog;
+ capabilities.health = health;
+ capabilities.sessions = sessions;
+ capabilities.prepared_queries = prepared_queries;
+ capabilities.events = events;
+ capabilities.coordinates = coordinates;
+ capabilities.operator_autopilot = operator_autopilot;
+ capabilities.operator_raft = operator_raft;
+ capabilities.operator_keyring = operator_keyring;
+ capabilities.operator_usage = operator_usage;
+ capabilities.operator_license = operator_license;
+ capabilities.audit = audit;
+ capabilities.edition = infer_edition(capabilities.namespaces, capabilities.partitions);
+ Ok(capabilities)
+}
+
+async fn probe_agent(client: &ConsulClient) -> ConsulCapabilities {
+ let Ok(url) = client.api_url("/v1/agent/self") else {
+ return ConsulCapabilities::default();
+ };
+ let Ok(response) = client.send(Method::GET, url, None).await else {
+ return ConsulCapabilities::default();
+ };
+ let status = capability_status(response.status());
+ if status != ConsulCapabilityStatus::Supported {
+ return ConsulCapabilities { agent: status, ..ConsulCapabilities::default() };
+ }
+ let Ok(response) = decode_json_response::<AgentSelfResponse>(response, "probe Consul agent").await else {
+ return ConsulCapabilities::default();
+ };
+ ConsulCapabilities {
+ version: response.config.version,
+ datacenter: response.config.datacenter,
+ node_name: response.config.node_name,
+ server: response.config.server,
+ agent: ConsulCapabilityStatus::Supported,
+ ..ConsulCapabilities::default()
+ }
+}
+
+async fn probe_endpoint(client: &ConsulClient, path: &str) -> ConsulCapabilityStatus {
+ let Ok(mut url) = client.api_url(path) else {
+ return ConsulCapabilityStatus::Unknown;
+ };
+ client.append_scope(&mut url, true);
+ match client.send(Method::GET, url, None).await {
+ Ok(response) => capability_status(response.status()),
+ Err(_) => ConsulCapabilityStatus::Unknown,
+ }
+}
+
+async fn probe_acl_endpoint(client: &ConsulClient) -> ConsulCapabilityStatus {
+ let Ok(mut url) = client.api_url("/v1/acl/token/self") else {
+ return ConsulCapabilityStatus::Unknown;
+ };
+ client.append_scope(&mut url, true);
+ match client.send(Method::GET, url, None).await {
+ Ok(response) if response.status() == StatusCode::UNAUTHORIZED => {
+ let body = response.text().await.unwrap_or_default();
+ if is_acl_support_disabled(&body) {
+ ConsulCapabilityStatus::Disabled
+ } else {
+ ConsulCapabilityStatus::Forbidden
+ }
+ }
+ Ok(response) => capability_status(response.status()),
+ Err(_) => ConsulCapabilityStatus::Unknown,
+ }
+}
+
+async fn probe_audit_endpoint(client: &ConsulClient) -> ConsulCapabilityStatus {
+ let Ok(mut url) = client.api_url("/v1/operator/audit-hash") else {
+ return ConsulCapabilityStatus::Unknown;
+ };
+ client.append_scope(&mut url, true);
+ match client.send(Method::POST, url, Some(br#"{"Input":"dbx-capability-probe"}"#.to_vec())).await {
+ Ok(response) => capability_status(response.status()),
+ Err(_) => ConsulCapabilityStatus::Unknown,
+ }
+}
+
+fn capability_status(status: StatusCode) -> ConsulCapabilityStatus {
+ match status {
+ status if status.is_success() => ConsulCapabilityStatus::Supported,
+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => ConsulCapabilityStatus::Forbidden,
+ StatusCode::NOT_FOUND => ConsulCapabilityStatus::Unsupported,
+ _ => ConsulCapabilityStatus::Unknown,
+ }
+}
+
+fn is_acl_support_disabled(body: &str) -> bool {
+ body.trim().eq_ignore_ascii_case("ACL support disabled")
+}
+
+fn infer_edition(namespaces: ConsulCapabilityStatus, partitions: ConsulCapabilityStatus) -> Option<String> {
+ if matches!(namespaces, ConsulCapabilityStatus::Supported)
+ || matches!(partitions, ConsulCapabilityStatus::Supported)
+ {
+ Some("enterprise".to_string())
+ } else if matches!(namespaces, ConsulCapabilityStatus::Unsupported)
+ && matches!(partitions, ConsulCapabilityStatus::Unsupported)
+ {
+ Some("community".to_string())
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn recognizes_an_explicitly_disabled_acl_subsystem() {
+ assert!(is_acl_support_disabled("ACL support disabled\n"));
+ assert!(!is_acl_support_disabled("Permission denied"));
+ assert_eq!(capability_status(StatusCode::UNAUTHORIZED), ConsulCapabilityStatus::Forbidden);
+ }
+}
diff --git a/crates/dbx-core/src/consul/catalog.rs b/crates/dbx-core/src/consul/catalog.rs
new file mode 100644
index 0000000000..6af8657907
--- /dev/null
+++ b/crates/dbx-core/src/consul/catalog.rs
@@ -0,0 +1,294 @@
+use std::collections::BTreeMap;
+
+use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ConsulClient};
+use super::response::{decode_json_response, ensure_success, ConsulResponseMetadata};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulReadOptions {
+ pub filter: Option<String>,
+ pub near: Option<String>,
+ pub index: Option<String>,
+ pub wait: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulListResponse<T> {
+ pub items: T,
+ pub metadata: ConsulResponseMetadata,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulCatalogNode {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub node: String,
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub datacenter: String,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, String>,
+ #[serde(default)]
+ pub node_meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulCatalogServiceNode {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub node: String,
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub datacenter: String,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, String>,
+ #[serde(default)]
+ pub node_meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub service_kind: String,
+ #[serde(default, rename = "ServiceID", alias = "ServiceId")]
+ pub service_id: String,
+ #[serde(default)]
+ pub service_name: String,
+ #[serde(default)]
+ pub service_tags: Vec<String>,
+ #[serde(default)]
+ pub service_address: String,
+ #[serde(default)]
+ pub service_port: u16,
+ #[serde(default)]
+ pub service_meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub service_tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
+ #[serde(default)]
+ pub service_weights: ConsulServiceWeights,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulServiceAddress {
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub port: u16,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulServiceWeights {
+ #[serde(default = "default_weight")]
+ pub passing: u32,
+ #[serde(default = "default_weight")]
+ pub warning: u32,
+}
+
+impl Default for ConsulServiceWeights {
+ fn default() -> Self {
+ Self { passing: 1, warning: 1 }
+ }
+}
+
+fn default_weight() -> u32 {
+ 1
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulCatalogService {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub service: String,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
+ #[serde(default)]
+ pub meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub port: u16,
+ #[serde(default)]
+ pub weights: ConsulServiceWeights,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulNodeServices {
+ pub node: ConsulCatalogNode,
+ #[serde(default)]
+ pub services: BTreeMap<String, ConsulCatalogService>,
+}
+
+impl ConsulClient {
+ pub async fn catalog_datacenters(&self) -> Result<Vec<String>, String> {
+ let url = self.api_url("/v1/catalog/datacenters")?;
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "list Consul datacenters", self.token()).await?;
+ decode_json_response(response, "list Consul datacenters").await
+ }
+
+ pub async fn catalog_nodes(
+ &self,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulCatalogNode>>, String> {
+ self.read_list("/v1/catalog/nodes", options, "list Consul catalog nodes").await
+ }
+
+ pub async fn catalog_services(
+ &self,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<BTreeMap<String, Vec<String>>>, String> {
+ self.read_list("/v1/catalog/services", options, "list Consul catalog services").await
+ }
+
+ pub async fn catalog_service_nodes(
+ &self,
+ service: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulCatalogServiceNode>>, String> {
+ let service = required_segment(service, "service")?;
+ self.read_list(
+ &format!("/v1/catalog/service/{}", encode_segment(service)),
+ options,
+ "list Consul service nodes",
+ )
+ .await
+ }
+
+ pub async fn catalog_node_services(
+ &self,
+ node: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<ConsulNodeServices>, String> {
+ let node = required_segment(node, "node")?;
+ self.read_list(&format!("/v1/catalog/node/{}", encode_segment(node)), options, "read Consul node services")
+ .await
+ }
+
+ pub(super) async fn read_list<T: serde::de::DeserializeOwned>(
+ &self,
+ path: &str,
+ options: &ConsulReadOptions,
+ action: &str,
+ ) -> Result<ConsulListResponse<T>, String> {
+ let mut url = self.api_url(path)?;
+ self.append_scope(&mut url, true);
+ append_read_options(&mut url, options);
+ let response = ensure_success(self.send(Method::GET, url, None).await?, action, self.token()).await?;
+ let metadata = ConsulResponseMetadata::from_response(&response);
+ let items = decode_json_response(response, action).await?;
+ Ok(ConsulListResponse { items, metadata })
+ }
+}
+
+pub(super) fn append_read_options(url: &mut reqwest::Url, options: &ConsulReadOptions) {
+ let mut query = url.query_pairs_mut();
+ for (name, value) in [
+ ("filter", options.filter.as_deref()),
+ ("near", options.near.as_deref()),
+ ("index", options.index.as_deref()),
+ ("wait", options.wait.as_deref()),
+ ] {
+ if let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) {
+ query.append_pair(name, value);
+ }
+ }
+}
+
+pub(super) fn encode_segment(value: &str) -> String {
+ utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
+}
+
+fn required_segment<'a>(value: &'a str, name: &str) -> Result<&'a str, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ return Err(format!("CONSUL_INVALID_REQUEST: {name} is required"));
+ }
+ Ok(value)
+}
+
+pub async fn consul_catalog_datacenters_core(state: &AppState, connection_id: &str) -> Result<Vec<String>, String> {
+ client_for_state(state, connection_id).await?.catalog_datacenters().await
+}
+
+pub async fn consul_catalog_nodes_core(
+ state: &AppState,
+ connection_id: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulCatalogNode>>, String> {
+ client_for_state(state, connection_id).await?.catalog_nodes(&options).await
+}
+
+pub async fn consul_catalog_services_core(
+ state: &AppState,
+ connection_id: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<BTreeMap<String, Vec<String>>>, String> {
+ client_for_state(state, connection_id).await?.catalog_services(&options).await
+}
+
+pub async fn consul_catalog_service_nodes_core(
+ state: &AppState,
+ connection_id: &str,
+ service: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulCatalogServiceNode>>, String> {
+ client_for_state(state, connection_id).await?.catalog_service_nodes(service, &options).await
+}
+
+pub async fn consul_catalog_node_services_core(
+ state: &AppState,
+ connection_id: &str,
+ node: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<ConsulNodeServices>, String> {
+ client_for_state(state, connection_id).await?.catalog_node_services(node, &options).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn consul_acronym_ids_deserialize_without_becoming_empty() {
+ let instance: ConsulCatalogServiceNode = serde_json::from_value(serde_json::json!({
+ "ID": "node-id",
+ "Node": "node-1",
+ "ServiceID": "api-1",
+ "ServiceName": "api"
+ }))
+ .unwrap();
+ assert_eq!(instance.id, "node-id");
+ assert_eq!(instance.service_id, "api-1");
+
+ let service: ConsulCatalogService = serde_json::from_value(serde_json::json!({
+ "ID": "api-1",
+ "Service": "api"
+ }))
+ .unwrap();
+ assert_eq!(service.id, "api-1");
+ }
+}
diff --git a/crates/dbx-core/src/consul/client.rs b/crates/dbx-core/src/consul/client.rs
new file mode 100644
index 0000000000..012360d05c
--- /dev/null
+++ b/crates/dbx-core/src/consul/client.rs
@@ -0,0 +1,314 @@
+use std::net::{IpAddr, SocketAddr};
+use std::time::Duration;
+
+use reqwest::{Method, Url};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+
+use crate::connection::{AppState, PoolKind};
+use crate::path_utils::expand_tilde;
+
+use super::config::ConsulScope;
+use super::config::{ConsulConfig, ConsulConsistency};
+
+#[derive(Debug, Clone)]
+pub struct ConsulClient {
+ config: ConsulConfig,
+ http: reqwest::Client,
+}
+
+impl ConsulClient {
+ pub async fn new(config: ConsulConfig) -> Result<Self, String> {
+ let mut builder = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(config.connect_timeout_secs.max(1)))
+ .redirect(reqwest::redirect::Policy::none());
+ if config.request_timeout_secs > 0 {
+ builder = builder.timeout(Duration::from_secs(config.request_timeout_secs));
+ }
+ if config.tls_skip_verify {
+ builder = builder.danger_accept_invalid_certs(true);
+ }
+ if !config.ca_cert_path.is_empty() {
+ let path = expand_tilde(&config.ca_cert_path);
+ let bytes = tokio::fs::read(&path)
+ .await
+ .map_err(|error| format!("Failed to read Consul CA certificate at {path}: {error}"))?;
+ let certificates = reqwest::Certificate::from_pem_bundle(&bytes)
+ .or_else(|_| reqwest::Certificate::from_der(&bytes).map(|certificate| vec![certificate]))
+ .map_err(|error| format!("Failed to parse Consul CA certificate at {path}: {error}"))?;
+ for certificate in certificates {
+ builder = builder.add_root_certificate(certificate);
+ }
+ }
+ if !config.client_cert_path.is_empty() {
+ let cert_path = expand_tilde(&config.client_cert_path);
+ let key_path = expand_tilde(&config.client_key_path);
+ let mut pem = tokio::fs::read(&cert_path)
+ .await
+ .map_err(|error| format!("Failed to read Consul client certificate at {cert_path}: {error}"))?;
+ if !pem.ends_with(b"\n") {
+ pem.push(b'\n');
+ }
+ pem.extend(
+ tokio::fs::read(&key_path)
+ .await
+ .map_err(|error| format!("Failed to read Consul client key at {key_path}: {error}"))?,
+ );
+ let identity = reqwest::Identity::from_pem(&pem)
+ .map_err(|error| format!("Failed to parse Consul client identity: {error}"))?;
+ builder = builder.identity(identity);
+ }
+ if let Some((override_host, override_port)) = &config.connect_override {
+ let original_host = config.base_url.host_str().ok_or("Consul server address has no host")?;
+ let ip = override_host
+ .parse::<IpAddr>()
+ .map_err(|_| format!("Consul transport target must resolve to an IP address: {override_host}"))?;
+ builder = builder.resolve(original_host, SocketAddr::new(ip, *override_port));
+ }
+ let http = builder.build().map_err(|error| format!("Failed to initialize Consul HTTP client: {error}"))?;
+ Ok(Self { config, http })
+ }
+
+ pub async fn probe(&self) -> Result<(), String> {
+ self.list_prefix("", 1, None).await.map(|_| ())
+ }
+
+ pub(super) fn api_url(&self, path: &str) -> Result<Url, String> {
+ let base = self.config.base_url.as_str().trim_end_matches('/');
+ Url::parse(&format!("{base}/{}", path.trim_start_matches('/')))
+ .map_err(|error| format!("Failed to build Consul API URL: {error}"))
+ }
+
+ pub(super) fn append_scope(&self, url: &mut Url, read: bool) {
+ let mut query = url.query_pairs_mut();
+ if !self.config.datacenter.is_empty() {
+ query.append_pair("dc", &self.config.datacenter);
+ }
+ if !self.config.namespace.is_empty() {
+ query.append_pair("ns", &self.config.namespace);
+ }
+ if !self.config.partition.is_empty() {
+ query.append_pair("partition", &self.config.partition);
+ }
+ if read {
+ match self.config.consistency {
+ ConsulConsistency::Default => {}
+ ConsulConsistency::Stale => {
+ query.append_pair("stale", "");
+ }
+ ConsulConsistency::Consistent => {
+ query.append_pair("consistent", "");
+ }
+ }
+ }
+ }
+
+ pub(super) async fn send(
+ &self,
+ method: Method,
+ url: Url,
+ body: Option<Vec<u8>>,
+ ) -> Result<reqwest::Response, String> {
+ let mut request = self.request(method, url);
+ if let Some(body) = body {
+ request = request.body(body);
+ }
+ request.send().await.map_err(|error| format!("Consul request failed: {}", error.without_url()))
+ }
+
+ fn request(&self, method: Method, url: Url) -> reqwest::RequestBuilder {
+ let mut request = self.http.request(method, url);
+ if !self.config.token.is_empty() {
+ request = request.header("X-Consul-Token", &self.config.token);
+ }
+ request
+ }
+
+ pub(super) async fn send_json<T: Serialize + ?Sized>(
+ &self,
+ method: Method,
+ mut url: Url,
+ body: Option<&T>,
+ read: bool,
+ action: &str,
+ ) -> Result<reqwest::Response, String> {
+ self.append_scope(&mut url, read);
+ let body = body
+ .map(serde_json::to_vec)
+ .transpose()
+ .map_err(|error| format!("Failed to serialize Consul request: {error}"))?;
+ let mut request = self.http.request(method, url);
+ if !self.config.token.is_empty() {
+ request = request.header("X-Consul-Token", &self.config.token);
+ }
+ if let Some(body) = body {
+ request = request.header(reqwest::header::CONTENT_TYPE, "application/json").body(body);
+ }
+ let response =
+ request.send().await.map_err(|error| format!("Consul request failed: {}", error.without_url()))?;
+ super::response::ensure_success(response, action, self.token()).await
+ }
+
+ pub(super) async fn request_json<R: DeserializeOwned, T: Serialize + ?Sized>(
+ &self,
+ method: Method,
+ url: Url,
+ body: Option<&T>,
+ read: bool,
+ action: &str,
+ ) -> Result<R, String> {
+ let response = self.send_json(method, url, body, read, action).await?;
+ super::response::decode_json_response(response, action).await
+ }
+
+ pub(super) async fn request_json_unscoped<R: DeserializeOwned, T: Serialize + ?Sized>(
+ &self,
+ method: Method,
+ url: Url,
+ body: Option<&T>,
+ action: &str,
+ ) -> Result<R, String> {
+ let body = body
+ .map(serde_json::to_vec)
+ .transpose()
+ .map_err(|error| format!("Failed to serialize Consul request: {error}"))?;
+ let mut request = self.request(method, url);
+ if let Some(body) = body {
+ request = request.header(reqwest::header::CONTENT_TYPE, "application/json").body(body);
+ }
+ let response =
+ request.send().await.map_err(|error| format!("Consul request failed: {}", error.without_url()))?;
+ let response = super::response::ensure_success(response, action, self.token()).await?;
+ super::response::decode_json_response(response, action).await
+ }
+
+ pub(super) fn token(&self) -> &str {
+ &self.config.token
+ }
+
+ pub(super) fn datacenter(&self) -> &str {
+ &self.config.datacenter
+ }
+
+ pub(super) fn namespace(&self) -> &str {
+ &self.config.namespace
+ }
+
+ pub(super) fn partition(&self) -> &str {
+ &self.config.partition
+ }
+
+ pub fn scope(&self) -> ConsulScope {
+ self.config.scope()
+ }
+
+ pub(super) fn config(&self) -> &ConsulConfig {
+ &self.config
+ }
+
+ pub(super) fn operator_feature_enabled(&self, feature: &str) -> bool {
+ match feature {
+ "snapshot_restore" => self.config.operator_snapshot_restore_enabled,
+ "autopilot" => self.config.operator_autopilot_write_enabled,
+ "raft" => self.config.operator_raft_write_enabled,
+ "keyring" => self.config.operator_keyring_write_enabled,
+ "license" => self.config.operator_license_write_enabled,
+ _ => false,
+ }
+ }
+}
+
+pub(super) async fn client_for_state(state: &AppState, connection_id: &str) -> Result<ConsulClient, String> {
+ state.get_or_create_pool(connection_id, None).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id) {
+ Some(PoolKind::Consul(client)) => Ok(client.clone()),
+ Some(_) => Err("Connection is not a Consul connection".to_string()),
+ None => Err("Connection not found".to_string()),
+ }
+}
+
+pub(crate) async fn ensure_writable_core(state: &AppState, connection_id: &str, action: &str) -> Result<(), String> {
+ if let Some(name) = crate::query::connection_readonly_name(state, connection_id).await {
+ return Err(format!(
+ "CONSUL_READ_ONLY: connection '{name}' has read-only protection enabled; {action} blocked"
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn preserves_proxy_path_scope_and_token_header() {
+ let client = test_client("fixture-secret");
+ let mut url = client.api_url("/v1/catalog/nodes").unwrap();
+ client.append_scope(&mut url, true);
+ let request = client.request(Method::GET, url).build().unwrap();
+ assert_eq!(request.method(), Method::GET);
+ assert_eq!(request.url().path(), "/proxy/v1/catalog/nodes");
+ assert_eq!(request.url().query(), Some("dc=dc1&ns=ns1&partition=part1"));
+ assert_eq!(request.headers().get("X-Consul-Token").unwrap(), "fixture-secret");
+ }
+
+ #[test]
+ fn redacts_sensitive_error_fields() {
+ let body = format!("SecretID=fixture-secret {}", "x".repeat(8_000));
+ let redacted = super::super::response::redact_sensitive(&body[..4096], "fixture-secret");
+ assert!(!redacted.contains("fixture-secret"));
+ assert!(redacted.contains("[REDACTED]"));
+ assert!(redacted.len() < 4_100);
+ }
+
+ #[test]
+ fn operator_write_flags_are_independent_and_unknown_features_stay_disabled() {
+ let mut client = test_client("");
+ for feature in ["snapshot_restore", "autopilot", "raft", "keyring", "license", "unknown"] {
+ assert!(!client.operator_feature_enabled(feature));
+ }
+
+ let cases = [("snapshot_restore", 0usize), ("autopilot", 1), ("raft", 2), ("keyring", 3), ("license", 4)];
+ for (enabled_feature, enabled_index) in cases {
+ client.config.operator_snapshot_restore_enabled = enabled_index == 0;
+ client.config.operator_autopilot_write_enabled = enabled_index == 1;
+ client.config.operator_raft_write_enabled = enabled_index == 2;
+ client.config.operator_keyring_write_enabled = enabled_index == 3;
+ client.config.operator_license_write_enabled = enabled_index == 4;
+ for (feature, index) in
+ ["snapshot_restore", "autopilot", "raft", "keyring", "license"].into_iter().zip(0usize..)
+ {
+ assert_eq!(client.operator_feature_enabled(feature), index == enabled_index, "{enabled_feature}");
+ }
+ }
+ }
+
+ fn test_client(token: &str) -> ConsulClient {
+ ConsulClient { config: test_config(token), http: reqwest::Client::new() }
+ }
+
+ fn test_config(token: &str) -> ConsulConfig {
+ ConsulConfig {
+ base_url: Url::parse("http://127.0.0.1:8500/proxy").unwrap(),
+ token: token.to_string(),
+ datacenter: "dc1".to_string(),
+ namespace: "ns1".to_string(),
+ partition: "part1".to_string(),
+ consistency: ConsulConsistency::Default,
+ tls_skip_verify: false,
+ ca_cert_path: String::new(),
+ client_cert_path: String::new(),
+ client_key_path: String::new(),
+ connect_timeout_secs: 2,
+ request_timeout_secs: 2,
+ connect_override: None,
+ agent_target: None,
+ operator_snapshot_restore_enabled: false,
+ operator_autopilot_write_enabled: false,
+ operator_raft_write_enabled: false,
+ operator_keyring_write_enabled: false,
+ operator_license_write_enabled: false,
+ }
+ }
+}
diff --git a/crates/dbx-core/src/consul/config.rs b/crates/dbx-core/src/consul/config.rs
new file mode 100644
index 0000000000..0828c36a40
--- /dev/null
+++ b/crates/dbx-core/src/consul/config.rs
@@ -0,0 +1,204 @@
+use std::fmt;
+
+use reqwest::Url;
+use serde::{Deserialize, Serialize};
+
+use crate::models::connection::ConnectionConfig;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulScope {
+ pub datacenter: String,
+ pub namespace: String,
+ pub partition: String,
+}
+
+impl ConsulScope {
+ pub fn contains_wildcard(&self) -> bool {
+ self.datacenter == "*" || self.namespace == "*" || self.partition == "*"
+ }
+}
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum ConsulConsistency {
+ #[default]
+ Default,
+ Stale,
+ Consistent,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentTarget {
+ pub node: String,
+ pub address: String,
+}
+
+#[derive(Clone, PartialEq, Eq)]
+pub struct ConsulConfig {
+ pub base_url: Url,
+ pub token: String,
+ pub datacenter: String,
+ pub namespace: String,
+ pub partition: String,
+ pub consistency: ConsulConsistency,
+ pub tls_skip_verify: bool,
+ pub ca_cert_path: String,
+ pub client_cert_path: String,
+ pub client_key_path: String,
+ pub connect_timeout_secs: u64,
+ pub request_timeout_secs: u64,
+ pub connect_override: Option<(String, u16)>,
+ pub operator_snapshot_restore_enabled: bool,
+ pub operator_autopilot_write_enabled: bool,
+ pub operator_raft_write_enabled: bool,
+ pub operator_keyring_write_enabled: bool,
+ pub operator_license_write_enabled: bool,
+ pub agent_target: Option<ConsulAgentTarget>,
+}
+
+impl fmt::Debug for ConsulConfig {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let token = if self.token.is_empty() { "none" } else { "redacted" };
+ formatter
+ .debug_struct("ConsulConfig")
+ .field("base_url", &self.base_url)
+ .field("token", &token)
+ .field("datacenter", &self.datacenter)
+ .field("namespace", &self.namespace)
+ .field("partition", &self.partition)
+ .field("consistency", &self.consistency)
+ .field("tls_skip_verify", &self.tls_skip_verify)
+ .field("ca_cert_path", &self.ca_cert_path)
+ .field("client_cert_path", &self.client_cert_path)
+ .field("client_key_path", &self.client_key_path)
+ .field("connect_timeout_secs", &self.connect_timeout_secs)
+ .field("request_timeout_secs", &self.request_timeout_secs)
+ .field("connect_override", &self.connect_override)
+ .field("operator_snapshot_restore_enabled", &self.operator_snapshot_restore_enabled)
+ .field("operator_autopilot_write_enabled", &self.operator_autopilot_write_enabled)
+ .field("operator_raft_write_enabled", &self.operator_raft_write_enabled)
+ .field("operator_keyring_write_enabled", &self.operator_keyring_write_enabled)
+ .field("operator_license_write_enabled", &self.operator_license_write_enabled)
+ .field("agent_target", &self.agent_target)
+ .finish()
+ }
+}
+
+impl ConsulConfig {
+ pub fn scope(&self) -> ConsulScope {
+ ConsulScope {
+ datacenter: self.datacenter.clone(),
+ namespace: self.namespace.clone(),
+ partition: self.partition.clone(),
+ }
+ }
+
+ pub fn from_connection(connection: &ConnectionConfig) -> Result<Self, String> {
+ let external = connection.external_config.as_ref();
+ let server_addr =
+ external_string(external, &["serverAddr", "server_addr"]).unwrap_or_else(|| connection.connection_url());
+ let mut base_url =
+ Url::parse(server_addr.trim()).map_err(|error| format!("Consul server address is invalid: {error}"))?;
+ if !matches!(base_url.scheme(), "http" | "https") {
+ return Err("Consul server address must use http or https".to_string());
+ }
+ if base_url.host_str().is_none() {
+ return Err("Consul server address must include a host".to_string());
+ }
+ if !base_url.username().is_empty() || base_url.password().is_some() {
+ return Err("Consul server address must not contain embedded credentials".to_string());
+ }
+ if base_url.query().is_some() || base_url.fragment().is_some() {
+ return Err("Consul server address must not contain a query or fragment".to_string());
+ }
+ let normalized_path = base_url.path().trim_end_matches('/').to_string();
+ base_url.set_path(&normalized_path);
+
+ let consistency = match external_string(external, &["consistency", "consulConsistency", "consul_consistency"])
+ .unwrap_or_else(|| "default".to_string())
+ .to_ascii_lowercase()
+ .as_str()
+ {
+ "default" | "" => ConsulConsistency::Default,
+ "stale" => ConsulConsistency::Stale,
+ "consistent" => ConsulConsistency::Consistent,
+ value => return Err(format!("Unsupported Consul consistency mode: {value}")),
+ };
+
+ let client_cert_path = connection.client_cert_path.trim().to_string();
+ let client_key_path = connection.client_key_path.trim().to_string();
+ if client_cert_path.is_empty() != client_key_path.is_empty() {
+ return Err("Consul client certificate and key must be configured together".to_string());
+ }
+
+ Ok(Self {
+ base_url,
+ token: connection.password.clone(),
+ datacenter: external_string(external, &["datacenter", "consulDatacenter", "consul_datacenter"])
+ .unwrap_or_default(),
+ namespace: external_string(external, &["namespace", "consulNamespace", "consul_namespace"])
+ .unwrap_or_default(),
+ partition: external_string(external, &["partition", "consulPartition", "consul_partition"])
+ .unwrap_or_default(),
+ consistency,
+ tls_skip_verify: external_bool(
+ external,
+ &["tlsSkipVerify", "tls_skip_verify", "consulTlsSkipVerify", "consul_tls_skip_verify"],
+ )
+ .unwrap_or(false),
+ ca_cert_path: connection.ca_cert_path.trim().to_string(),
+ client_cert_path,
+ client_key_path,
+ connect_timeout_secs: connection.effective_connect_timeout_secs(),
+ request_timeout_secs: connection.effective_query_timeout_secs(),
+ connect_override: None,
+ operator_snapshot_restore_enabled: external_bool(external, &["consulOperatorSnapshotRestoreEnabled"])
+ .unwrap_or(false),
+ operator_autopilot_write_enabled: external_bool(external, &["consulOperatorAutopilotWriteEnabled"])
+ .unwrap_or(false),
+ operator_raft_write_enabled: external_bool(external, &["consulOperatorRaftWriteEnabled"]).unwrap_or(false),
+ operator_keyring_write_enabled: external_bool(external, &["consulOperatorKeyringWriteEnabled"])
+ .unwrap_or(false),
+ operator_license_write_enabled: external_bool(external, &["consulOperatorLicenseWriteEnabled"])
+ .unwrap_or(false),
+ agent_target: parse_agent_target(external)?,
+ })
+ }
+
+ pub fn with_connect_override(mut self, host: impl Into<String>, port: u16) -> Self {
+ self.connect_override = Some((host.into(), port));
+ self
+ }
+}
+
+fn parse_agent_target(value: Option<&serde_json::Value>) -> Result<Option<ConsulAgentTarget>, String> {
+ let Some(raw) = value
+ .and_then(serde_json::Value::as_object)
+ .and_then(|object| object.get("agentTarget").or_else(|| object.get("agent_target")))
+ else {
+ return Ok(None);
+ };
+ let object = raw.as_object().ok_or("Consul agent_target must contain an explicit node and address")?;
+ let node = object.get("node").and_then(serde_json::Value::as_str).unwrap_or_default().trim();
+ let address = object.get("address").and_then(serde_json::Value::as_str).unwrap_or_default().trim();
+ if node.is_empty() || address.is_empty() {
+ return Err("Consul agent_target requires both node and address".to_string());
+ }
+ Ok(Some(ConsulAgentTarget { node: node.to_string(), address: address.to_string() }))
+}
+
+fn external_string(value: Option<&serde_json::Value>, keys: &[&str]) -> Option<String> {
+ let object = value?.as_object()?;
+ keys.iter()
+ .find_map(|key| object.get(*key).and_then(serde_json::Value::as_str))
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+}
+
+fn external_bool(value: Option<&serde_json::Value>, keys: &[&str]) -> Option<bool> {
+ let object = value?.as_object()?;
+ keys.iter().find_map(|key| object.get(*key).and_then(serde_json::Value::as_bool))
+}
diff --git a/crates/dbx-core/src/consul/enterprise.rs b/crates/dbx-core/src/consul/enterprise.rs
new file mode 100644
index 0000000000..c5bb1d80fd
--- /dev/null
+++ b/crates/dbx-core/src/consul/enterprise.rs
@@ -0,0 +1,796 @@
+use std::collections::{BTreeMap, BTreeSet};
+
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ConsulClient};
+use super::config::ConsulConsistency;
+use super::response::{decode_json_response, ensure_success, ConsulResponseMetadata, MAX_COLLECTION_ITEMS};
+
+// Consul lists config entries by kind and does not expose a single inventory endpoint.
+const NAMESPACE_CONFIG_ENTRY_KINDS: &[&str] = &[
+ "api-gateway",
+ "bound-api-gateway",
+ "file-system-certificate",
+ "http-route",
+ "ingress-gateway",
+ "inline-certificate",
+ "jwt-provider",
+ "service-defaults",
+ "service-intentions",
+ "service-resolver",
+ "service-router",
+ "service-splitter",
+ "tcp-route",
+ "terminating-gateway",
+];
+
+const PARTITION_CONFIG_ENTRY_KINDS: &[&str] = &[
+ "control-plane-request-limit",
+ "exported-services",
+ "mesh",
+ "product-usage",
+ "proxy-defaults",
+ "rate-limit",
+ "sameness-group",
+];
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum ConsulEnterpriseKind {
+ Namespace,
+ Partition,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulNamespace {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub meta: BTreeMap<String, String>,
+ #[serde(rename = "ACLs", default)]
+ pub acls: ConsulNamespaceAcls,
+ #[serde(default)]
+ pub deleted_at: Option<String>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulNamespaceAcls {
+ #[serde(default)]
+ pub policy_defaults: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub role_defaults: Vec<serde_json::Value>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPartition {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub deleted_at: Option<String>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "items", rename_all = "camelCase")]
+pub enum ConsulEnterpriseList {
+ Namespace(Vec<ConsulNamespace>),
+ Partition(Vec<ConsulPartition>),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "item", rename_all = "camelCase")]
+pub enum ConsulEnterpriseItem {
+ Namespace(ConsulNamespace),
+ Partition(ConsulPartition),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", content = "item", rename_all = "camelCase")]
+pub enum ConsulEnterpriseWrite {
+ Namespace(ConsulNamespace),
+ Partition(ConsulPartition),
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulScopeImpact {
+ pub services: usize,
+ pub nodes: usize,
+ pub kv_keys: usize,
+ pub health_checks: usize,
+ pub sessions: usize,
+ pub config_entries: usize,
+ pub intentions: usize,
+ pub peerings: usize,
+ pub namespaces: usize,
+ pub acl_tokens: usize,
+ pub acl_policies: usize,
+ pub acl_roles: usize,
+ pub acl_auth_methods: usize,
+ pub acl_binding_rules: usize,
+ pub complete: bool,
+ pub filtered_by_acls: bool,
+ pub unavailable_resources: Vec<String>,
+}
+
+#[derive(Debug, Clone, Copy)]
+enum ImpactResource {
+ Services,
+ Nodes,
+ KvKeys,
+ HealthChecks,
+ Sessions,
+ ConfigEntries,
+ Intentions,
+ Peerings,
+ Namespaces,
+ AclTokens,
+ AclPolicies,
+ AclRoles,
+ AclAuthMethods,
+ AclBindingRules,
+}
+
+#[derive(Debug)]
+struct ImpactInspection {
+ count: usize,
+ filtered_by_acls: bool,
+}
+
+impl ConsulScopeImpact {
+ fn record(&mut self, resource: ImpactResource, label: String, result: Result<ImpactInspection, String>) {
+ match result {
+ Ok(inspection) => {
+ let target = match resource {
+ ImpactResource::Services => &mut self.services,
+ ImpactResource::Nodes => &mut self.nodes,
+ ImpactResource::KvKeys => &mut self.kv_keys,
+ ImpactResource::HealthChecks => &mut self.health_checks,
+ ImpactResource::Sessions => &mut self.sessions,
+ ImpactResource::ConfigEntries => &mut self.config_entries,
+ ImpactResource::Intentions => &mut self.intentions,
+ ImpactResource::Peerings => &mut self.peerings,
+ ImpactResource::Namespaces => &mut self.namespaces,
+ ImpactResource::AclTokens => &mut self.acl_tokens,
+ ImpactResource::AclPolicies => &mut self.acl_policies,
+ ImpactResource::AclRoles => &mut self.acl_roles,
+ ImpactResource::AclAuthMethods => &mut self.acl_auth_methods,
+ ImpactResource::AclBindingRules => &mut self.acl_binding_rules,
+ };
+ if let Some(total) = target.checked_add(inspection.count) {
+ *target = total;
+ } else {
+ self.unavailable_resources.push(label);
+ }
+ self.filtered_by_acls |= inspection.filtered_by_acls;
+ }
+ Err(_) => self.unavailable_resources.push(label),
+ }
+ }
+
+ fn finish(mut self) -> Self {
+ self.unavailable_resources.sort();
+ self.unavailable_resources.dedup();
+ self.complete = self.unavailable_resources.is_empty() && !self.filtered_by_acls;
+ self
+ }
+}
+
+pub async fn consul_enterprise_list_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulEnterpriseKind,
+) -> Result<ConsulEnterpriseList, String> {
+ let client = client_for_state(state, connection_id).await?;
+ match kind {
+ ConsulEnterpriseKind::Namespace => {
+ Ok(ConsulEnterpriseList::Namespace(get_json(&client, "/v1/namespaces", "list namespaces").await?))
+ }
+ ConsulEnterpriseKind::Partition => {
+ Ok(ConsulEnterpriseList::Partition(get_json(&client, "/v1/partitions", "list partitions").await?))
+ }
+ }
+}
+
+pub async fn consul_enterprise_get_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulEnterpriseKind,
+ name: &str,
+) -> Result<ConsulEnterpriseItem, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&enterprise_path(kind, name))?;
+ match kind {
+ ConsulEnterpriseKind::Namespace => Ok(ConsulEnterpriseItem::Namespace(
+ client.request_json(Method::GET, url, None::<&()>, true, "read namespace").await?,
+ )),
+ ConsulEnterpriseKind::Partition => Ok(ConsulEnterpriseItem::Partition(
+ client.request_json(Method::GET, url, None::<&()>, true, "read partition").await?,
+ )),
+ }
+}
+
+pub async fn consul_enterprise_apply_core(
+ state: &AppState,
+ connection_id: &str,
+ existing_name: Option<&str>,
+ item: ConsulEnterpriseWrite,
+) -> Result<ConsulEnterpriseItem, String> {
+ super::ensure_writable(state, connection_id, "Enterprise scope write").await?;
+ let client = client_for_state(state, connection_id).await?;
+ match item {
+ ConsulEnterpriseWrite::Namespace(value) => {
+ Ok(ConsulEnterpriseItem::Namespace(write_namespace(&client, existing_name, value).await?))
+ }
+ ConsulEnterpriseWrite::Partition(value) => {
+ Ok(ConsulEnterpriseItem::Partition(write_partition(&client, existing_name, value).await?))
+ }
+ }
+}
+
+async fn write_namespace(
+ client: &ConsulClient,
+ existing_name: Option<&str>,
+ mut value: ConsulNamespace,
+) -> Result<ConsulNamespace, String> {
+ value.partition = target_partition(client.partition()).to_string();
+ let (method, path) = write_path(ConsulEnterpriseKind::Namespace, existing_name);
+ let mut url = client.api_url(&path)?;
+ append_enterprise_target(client, &mut url, ConsulEnterpriseKind::Namespace, false);
+ client.request_json_unscoped(method, url, Some(&value), "write namespace").await
+}
+
+async fn write_partition(
+ client: &ConsulClient,
+ existing_name: Option<&str>,
+ value: ConsulPartition,
+) -> Result<ConsulPartition, String> {
+ let (method, path) = write_path(ConsulEnterpriseKind::Partition, existing_name);
+ let mut url = client.api_url(&path)?;
+ append_enterprise_target(client, &mut url, ConsulEnterpriseKind::Partition, false);
+ client.request_json_unscoped(method, url, Some(&value), "write partition").await
+}
+
+fn target_partition(partition: &str) -> &str {
+ if partition.trim().is_empty() {
+ "default"
+ } else {
+ partition
+ }
+}
+
+pub async fn consul_enterprise_impact_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulEnterpriseKind,
+ name: &str,
+) -> Result<ConsulScopeImpact, String> {
+ let client = client_for_state(state, connection_id).await?;
+ inspect_scope_impact(&client, kind, name).await
+}
+
+pub async fn consul_enterprise_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulEnterpriseKind,
+ name: &str,
+) -> Result<ConsulScopeImpact, String> {
+ super::ensure_writable(state, connection_id, "Enterprise scope delete").await?;
+ let impact = consul_enterprise_impact_core(state, connection_id, kind, name).await?;
+ if !impact.complete {
+ return Err(
+ "CONSUL_IMPACT_INCOMPLETE: scoped resources could not be enumerated completely; delete blocked".to_string()
+ );
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url(&enterprise_path(kind, name))?;
+ append_enterprise_target(&client, &mut url, kind, false);
+ ensure_success(client.send(Method::DELETE, url, None).await?, "delete Enterprise scope", client.token()).await?;
+ Ok(impact)
+}
+
+async fn get_json<T: serde::de::DeserializeOwned>(
+ client: &ConsulClient,
+ path: &str,
+ action: &str,
+) -> Result<T, String> {
+ let url = client.api_url(path)?;
+ client.request_json(Method::GET, url, None::<&()>, true, action).await
+}
+
+async fn inspect_scope_impact(
+ client: &ConsulClient,
+ kind: ConsulEnterpriseKind,
+ name: &str,
+) -> Result<ConsulScopeImpact, String> {
+ if name.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: Enterprise scope name is required".to_string());
+ }
+
+ let mut impact = ConsulScopeImpact::default();
+ match kind {
+ ConsulEnterpriseKind::Namespace => {
+ inspect_namespace_resources(client, name, client.partition(), &mut impact).await;
+ }
+ ConsulEnterpriseKind::Partition => {
+ match inspect_partition_namespaces(client, name).await {
+ Ok((namespaces, filtered)) => {
+ impact.record(
+ ImpactResource::Namespaces,
+ "namespaces".to_string(),
+ Ok(ImpactInspection { count: namespaces.len(), filtered_by_acls: filtered }),
+ );
+ // Every partition owns a default namespace. Its absence means the list cannot prove completeness,
+ // even if an older Consul version omitted the ACL-filtered response header.
+ if !namespaces.contains("default") {
+ impact.unavailable_resources.push("namespaces:default".to_string());
+ }
+ for namespace in namespaces {
+ inspect_namespace_resources(client, &namespace, name, &mut impact).await;
+ }
+ }
+ Err(_) => impact.unavailable_resources.push("namespaces".to_string()),
+ }
+
+ record_inspection(
+ client,
+ &mut impact,
+ ImpactResource::Nodes,
+ "nodes",
+ "/v1/catalog/nodes",
+ name,
+ None,
+ &[],
+ false,
+ )
+ .await;
+ record_inspection(
+ client,
+ &mut impact,
+ ImpactResource::Peerings,
+ "peerings",
+ "/v1/peerings",
+ name,
+ None,
+ &[],
+ false,
+ )
+ .await;
+ for config_kind in PARTITION_CONFIG_ENTRY_KINDS {
+ record_inspection(
+ client,
+ &mut impact,
+ ImpactResource::ConfigEntries,
+ &format!("configEntries:{config_kind}"),
+ &format!("/v1/config/{config_kind}"),
+ name,
+ Some("default"),
+ &[],
+ false,
+ )
+ .await;
+ }
+ }
+ }
+ Ok(impact.finish())
+}
+
+async fn inspect_namespace_resources(
+ client: &ConsulClient,
+ namespace: &str,
+ partition: &str,
+ impact: &mut ConsulScopeImpact,
+) {
+ let resources = [
+ (ImpactResource::Services, "services", "/v1/catalog/services", false),
+ (ImpactResource::KvKeys, "kvKeys", "/v1/kv/", true),
+ (ImpactResource::HealthChecks, "healthChecks", "/v1/health/state/any", false),
+ (ImpactResource::Sessions, "sessions", "/v1/session/list", false),
+ (ImpactResource::Intentions, "intentions", "/v1/connect/intentions", false),
+ (ImpactResource::AclTokens, "aclTokens", "/v1/acl/tokens", false),
+ (ImpactResource::AclPolicies, "aclPolicies", "/v1/acl/policies", false),
+ (ImpactResource::AclRoles, "aclRoles", "/v1/acl/roles", false),
+ (ImpactResource::AclAuthMethods, "aclAuthMethods", "/v1/acl/auth-methods", false),
+ (ImpactResource::AclBindingRules, "aclBindingRules", "/v1/acl/binding-rules", false),
+ ];
+ for (resource, label, path, empty_on_not_found) in resources {
+ let query = if matches!(resource, ImpactResource::KvKeys) { &[("keys", "")][..] } else { &[][..] };
+ record_inspection(
+ client,
+ impact,
+ resource,
+ &scoped_label(label, namespace),
+ path,
+ partition,
+ Some(namespace),
+ query,
+ empty_on_not_found,
+ )
+ .await;
+ }
+ for config_kind in NAMESPACE_CONFIG_ENTRY_KINDS {
+ record_inspection(
+ client,
+ impact,
+ ImpactResource::ConfigEntries,
+ &scoped_label(&format!("configEntries:{config_kind}"), namespace),
+ &format!("/v1/config/{config_kind}"),
+ partition,
+ Some(namespace),
+ &[],
+ false,
+ )
+ .await;
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn record_inspection(
+ client: &ConsulClient,
+ impact: &mut ConsulScopeImpact,
+ resource: ImpactResource,
+ label: &str,
+ path: &str,
+ partition: &str,
+ namespace: Option<&str>,
+ query: &[(&str, &str)],
+ empty_on_not_found: bool,
+) {
+ let result = impact_get(client, path, partition, namespace, query, empty_on_not_found).await;
+ impact.record(resource, label.to_string(), result);
+}
+
+async fn impact_get(
+ client: &ConsulClient,
+ path: &str,
+ partition: &str,
+ namespace: Option<&str>,
+ extra_query: &[(&str, &str)],
+ empty_on_not_found: bool,
+) -> Result<ImpactInspection, String> {
+ let mut url = client.api_url(path)?;
+ append_explicit_scope(client, &mut url, partition, namespace, true);
+ for (key, value) in extra_query {
+ url.query_pairs_mut().append_pair(key, value);
+ }
+ let response = client.send(Method::GET, url, None).await?;
+ let filtered = ConsulResponseMetadata::from_response(&response).filtered_by_acls.unwrap_or(false);
+ if is_empty_not_found(response.status(), empty_on_not_found) {
+ return Ok(ImpactInspection { count: 0, filtered_by_acls: filtered });
+ }
+ let response = ensure_success(response, "inspect scoped resources", client.token()).await?;
+ let value = decode_json_response::<serde_json::Value>(response, "inspect scoped resources").await?;
+ let count = count_collection(&value)?;
+ Ok(ImpactInspection { count, filtered_by_acls: filtered })
+}
+
+async fn inspect_partition_namespaces(
+ client: &ConsulClient,
+ partition: &str,
+) -> Result<(BTreeSet<String>, bool), String> {
+ let mut url = client.api_url("/v1/namespaces")?;
+ append_explicit_scope(client, &mut url, partition, None, true);
+ let response = ensure_success(
+ client.send(Method::GET, url, None).await?,
+ "list namespaces for partition impact",
+ client.token(),
+ )
+ .await?;
+ let filtered = ConsulResponseMetadata::from_response(&response).filtered_by_acls.unwrap_or(false);
+ let value = decode_json_response::<serde_json::Value>(response, "list namespaces for partition impact").await?;
+ let items = value
+ .as_array()
+ .ok_or_else(|| "CONSUL_INVALID_RESPONSE: namespace impact response must be an array".to_string())?;
+ if items.len() > MAX_COLLECTION_ITEMS {
+ return Err(format!("CONSUL_RESPONSE_TOO_LARGE: impact response exceeds {MAX_COLLECTION_ITEMS} items"));
+ }
+ let mut namespaces = BTreeSet::new();
+ for item in items {
+ let name = item
+ .get("Name")
+ .and_then(serde_json::Value::as_str)
+ .filter(|name| !name.is_empty())
+ .ok_or_else(|| "CONSUL_INVALID_RESPONSE: namespace impact item is missing Name".to_string())?;
+ if !namespaces.insert(name.to_string()) {
+ return Err(format!("CONSUL_INVALID_RESPONSE: duplicate namespace {name:?} in impact response"));
+ }
+ }
+ Ok((namespaces, filtered))
+}
+
+fn count_collection(value: &serde_json::Value) -> Result<usize, String> {
+ let count = match value {
+ serde_json::Value::Array(items) => items.len(),
+ serde_json::Value::Object(items) => items.len(),
+ _ => return Err("CONSUL_INVALID_RESPONSE: impact response must be an array or object".to_string()),
+ };
+ if count > MAX_COLLECTION_ITEMS {
+ return Err(format!("CONSUL_RESPONSE_TOO_LARGE: impact response exceeds {MAX_COLLECTION_ITEMS} items"));
+ }
+ Ok(count)
+}
+
+fn is_empty_not_found(status: reqwest::StatusCode, empty_on_not_found: bool) -> bool {
+ empty_on_not_found && status == reqwest::StatusCode::NOT_FOUND
+}
+
+fn append_explicit_scope(
+ client: &ConsulClient,
+ url: &mut reqwest::Url,
+ partition: &str,
+ namespace: Option<&str>,
+ read: bool,
+) {
+ let mut query = url.query_pairs_mut();
+ if !client.datacenter().is_empty() {
+ query.append_pair("dc", client.datacenter());
+ }
+ if !partition.is_empty() {
+ query.append_pair("partition", partition);
+ }
+ if let Some(namespace) = namespace.filter(|namespace| !namespace.is_empty()) {
+ query.append_pair("ns", namespace);
+ }
+ if read {
+ match client.config().consistency {
+ ConsulConsistency::Default => {}
+ ConsulConsistency::Stale => {
+ query.append_pair("stale", "");
+ }
+ ConsulConsistency::Consistent => {
+ query.append_pair("consistent", "");
+ }
+ }
+ }
+}
+
+fn append_enterprise_target(client: &ConsulClient, url: &mut reqwest::Url, kind: ConsulEnterpriseKind, read: bool) {
+ let partition = match kind {
+ ConsulEnterpriseKind::Namespace => client.partition(),
+ ConsulEnterpriseKind::Partition => "",
+ };
+ append_explicit_scope(client, url, partition, None, read);
+}
+
+fn scoped_label(label: &str, namespace: &str) -> String {
+ format!("{label}@namespace:{namespace}")
+}
+
+fn enterprise_path(kind: ConsulEnterpriseKind, name: &str) -> String {
+ let name = percent_encoding::utf8_percent_encode(name, percent_encoding::NON_ALPHANUMERIC);
+ match kind {
+ ConsulEnterpriseKind::Namespace => format!("/v1/namespace/{name}"),
+ ConsulEnterpriseKind::Partition => format!("/v1/partition/{name}"),
+ }
+}
+
+fn write_path(kind: ConsulEnterpriseKind, existing_name: Option<&str>) -> (Method, String) {
+ match existing_name {
+ Some(name) => (Method::PUT, enterprise_path(kind, name)),
+ None => (
+ Method::PUT,
+ match kind {
+ ConsulEnterpriseKind::Namespace => "/v1/namespace",
+ ConsulEnterpriseKind::Partition => "/v1/partition",
+ }
+ .to_string(),
+ ),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::test_support::{serve_once, test_client as fixture_client};
+ use super::*;
+ use reqwest::Url;
+
+ #[test]
+ fn enterprise_paths_encode_names() {
+ assert_eq!(enterprise_path(ConsulEnterpriseKind::Namespace, "team/a"), "/v1/namespace/team%2Fa");
+ }
+
+ #[test]
+ fn namespace_acl_defaults_round_trip_with_the_official_nested_shape() {
+ let value = serde_json::json!({
+ "Name": "team-a",
+ "Partition": "payments",
+ "ACLs": {
+ "PolicyDefaults": [{ "Name": "node-read" }],
+ "RoleDefaults": [{ "ID": "role-1" }]
+ }
+ });
+ let namespace: ConsulNamespace = serde_json::from_value(value.clone()).unwrap();
+ assert_eq!(namespace.acls.policy_defaults.len(), 1);
+ assert_eq!(namespace.acls.role_defaults.len(), 1);
+ assert_eq!(namespace.partition, "payments");
+ let serialized = serde_json::to_value(namespace).unwrap();
+ assert_eq!(serialized["ACLs"], value["ACLs"]);
+ }
+
+ #[test]
+ fn namespace_write_partition_is_explicit_and_defaults_safely() {
+ assert_eq!(target_partition("partition-a"), "partition-a");
+ assert_eq!(target_partition(""), "default");
+ assert_eq!(target_partition(" "), "default");
+ assert_eq!(
+ write_path(ConsulEnterpriseKind::Namespace, Some("team/a")),
+ (Method::PUT, "/v1/namespace/team%2Fa".to_string())
+ );
+ }
+
+ #[tokio::test]
+ async fn namespace_create_uses_partition_body_and_excludes_current_namespace() {
+ let response_body = r#"{"Name":"team-b","Partition":"partition-a","Description":"","Meta":{},"ACLs":{}}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response_body}",
+ response_body.len()
+ );
+ let (url, request_rx) = serve_once(response).await;
+ let client = fixture_client(url).await;
+ let written =
+ write_namespace(&client, None, ConsulNamespace { name: "team-b".to_string(), ..Default::default() })
+ .await
+ .unwrap();
+ assert_eq!(written.partition, "partition-a");
+
+ let request = request_rx.await.unwrap();
+ let (headers, body) = request.split_once("\r\n\r\n").unwrap();
+ assert!(headers.starts_with("PUT /proxy/v1/namespace?dc=dc1&partition=partition-a HTTP/1.1"));
+ assert!(!headers.contains("ns="));
+ assert!(headers.to_ascii_lowercase().contains("content-type: application/json"));
+ assert!(headers.to_ascii_lowercase().contains("x-consul-token: fixture-token"));
+ let body: serde_json::Value = serde_json::from_str(body).unwrap();
+ assert_eq!(body["Name"], "team-b");
+ assert_eq!(body["Partition"], "partition-a");
+ }
+
+ #[tokio::test]
+ async fn explicit_impact_scope_uses_the_target_without_wildcards() {
+ let client = test_client().await;
+ let mut url = client.api_url("/v1/catalog/services").unwrap();
+ append_explicit_scope(&client, &mut url, "target-partition", Some("target-namespace"), true);
+ let pairs: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
+ assert_eq!(pairs.get("dc").map(String::as_str), Some("dc1"));
+ assert_eq!(pairs.get("partition").map(String::as_str), Some("target-partition"));
+ assert_eq!(pairs.get("ns").map(String::as_str), Some("target-namespace"));
+ assert!(pairs.contains_key("consistent"));
+ assert!(!url.as_str().contains('*'));
+ assert!(!url.as_str().contains("configured-namespace"));
+ assert!(!url.as_str().contains("configured-partition"));
+ }
+
+ #[tokio::test]
+ async fn enterprise_delete_target_does_not_append_the_connection_namespace() {
+ let client = test_client().await;
+ let mut namespace_url = client.api_url("/v1/namespace/team-a").unwrap();
+ append_enterprise_target(&client, &mut namespace_url, ConsulEnterpriseKind::Namespace, false);
+ assert_eq!(namespace_url.query(), Some("dc=dc1&partition=configured-partition"));
+
+ let mut partition_url = client.api_url("/v1/partition/team-a").unwrap();
+ append_enterprise_target(&client, &mut partition_url, ConsulEnterpriseKind::Partition, false);
+ assert_eq!(partition_url.query(), Some("dc=dc1"));
+ }
+
+ #[test]
+ fn impact_is_incomplete_when_any_result_is_filtered_or_unavailable() {
+ let mut impact = ConsulScopeImpact::default();
+ impact.record(
+ ImpactResource::Services,
+ "services".to_string(),
+ Ok(ImpactInspection { count: 2, filtered_by_acls: true }),
+ );
+ impact.record(ImpactResource::Sessions, "sessions".to_string(), Err("forbidden".to_string()));
+ let impact = impact.finish();
+ assert_eq!(impact.services, 2);
+ assert!(impact.filtered_by_acls);
+ assert_eq!(impact.unavailable_resources, vec!["sessions"]);
+ assert!(!impact.complete);
+ }
+
+ #[test]
+ fn impact_is_complete_only_after_all_recorded_results_are_unfiltered() {
+ let mut impact = ConsulScopeImpact::default();
+ impact.record(
+ ImpactResource::KvKeys,
+ "kvKeys".to_string(),
+ Ok(ImpactInspection { count: 3, filtered_by_acls: false }),
+ );
+ impact.record(
+ ImpactResource::ConfigEntries,
+ "configEntries".to_string(),
+ Ok(ImpactInspection { count: 4, filtered_by_acls: false }),
+ );
+ let impact = impact.finish();
+ assert_eq!(impact.kv_keys, 3);
+ assert_eq!(impact.config_entries, 4);
+ assert!(impact.complete);
+ }
+
+ #[test]
+ fn impact_collection_count_rejects_non_collections_and_excess_items() {
+ assert!(count_collection(&serde_json::json!(false)).is_err());
+ let oversized = serde_json::Value::Array(vec![serde_json::Value::Null; MAX_COLLECTION_ITEMS + 1]);
+ assert!(count_collection(&oversized).is_err());
+ }
+
+ #[test]
+ fn config_entry_inventory_covers_namespace_and_partition_scopes_without_duplicates() {
+ let all = NAMESPACE_CONFIG_ENTRY_KINDS
+ .iter()
+ .chain(PARTITION_CONFIG_ENTRY_KINDS.iter())
+ .copied()
+ .collect::<BTreeSet<_>>();
+ assert_eq!(all.len(), NAMESPACE_CONFIG_ENTRY_KINDS.len() + PARTITION_CONFIG_ENTRY_KINDS.len());
+ for required in [
+ "service-defaults",
+ "service-intentions",
+ "api-gateway",
+ "bound-api-gateway",
+ "jwt-provider",
+ "proxy-defaults",
+ "mesh",
+ "exported-services",
+ "sameness-group",
+ ] {
+ assert!(all.contains(required), "missing config entry kind {required}");
+ }
+ }
+
+ #[test]
+ fn only_explicitly_empty_collections_treat_not_found_as_zero() {
+ assert!(is_empty_not_found(reqwest::StatusCode::NOT_FOUND, true));
+ assert!(!is_empty_not_found(reqwest::StatusCode::NOT_FOUND, false));
+ assert!(!is_empty_not_found(reqwest::StatusCode::FORBIDDEN, true));
+ }
+
+ async fn test_client() -> ConsulClient {
+ test_client_at(Url::parse("https://consul.example/proxy").unwrap()).await
+ }
+
+ async fn test_client_at(base_url: Url) -> ConsulClient {
+ ConsulClient::new(super::super::config::ConsulConfig {
+ base_url,
+ token: String::new(),
+ datacenter: "dc1".to_string(),
+ namespace: "configured-namespace".to_string(),
+ partition: "configured-partition".to_string(),
+ consistency: ConsulConsistency::Consistent,
+ tls_skip_verify: false,
+ ca_cert_path: String::new(),
+ client_cert_path: String::new(),
+ client_key_path: String::new(),
+ connect_timeout_secs: 5,
+ request_timeout_secs: 30,
+ connect_override: None,
+ operator_snapshot_restore_enabled: false,
+ operator_autopilot_write_enabled: false,
+ operator_raft_write_enabled: false,
+ operator_keyring_write_enabled: false,
+ operator_license_write_enabled: false,
+ agent_target: None,
+ })
+ .await
+ .unwrap()
+ }
+}
diff --git a/crates/dbx-core/src/consul/health.rs b/crates/dbx-core/src/consul/health.rs
new file mode 100644
index 0000000000..33ace473b7
--- /dev/null
+++ b/crates/dbx-core/src/consul/health.rs
@@ -0,0 +1,216 @@
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::catalog::{
+ encode_segment, ConsulCatalogNode, ConsulListResponse, ConsulReadOptions, ConsulServiceAddress,
+ ConsulServiceWeights,
+};
+use super::client::{client_for_state, ConsulClient};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulHealthCheck {
+ #[serde(default)]
+ pub node: String,
+ #[serde(default, rename = "CheckID", alias = "CheckId")]
+ pub check_id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub status: String,
+ #[serde(default)]
+ pub notes: String,
+ #[serde(default)]
+ pub output: String,
+ #[serde(default, rename = "ServiceID", alias = "ServiceId")]
+ pub service_id: String,
+ #[serde(default)]
+ pub service_name: String,
+ #[serde(default)]
+ pub service_tags: Vec<String>,
+ #[serde(default)]
+ #[serde(rename = "Type")]
+ pub type_: String,
+ #[serde(default)]
+ pub exposed_port: u16,
+ #[serde(default)]
+ pub definition: ConsulHealthCheckDefinition,
+ #[serde(default, rename = "CreateIndex")]
+ pub create_index: u64,
+ #[serde(default, rename = "ModifyIndex")]
+ pub modify_index: u64,
+ #[serde(default, skip_deserializing)]
+ pub maintenance: bool,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulHealthCheckDefinition {
+ #[serde(default)]
+ pub http: String,
+ #[serde(default)]
+ pub tcp: String,
+ #[serde(default)]
+ pub grpc: String,
+ #[serde(default)]
+ pub interval: String,
+ #[serde(default)]
+ pub timeout: String,
+ #[serde(default)]
+ pub ttl: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulHealthService {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub service: String,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub tagged_addresses: BTreeMap<String, ConsulServiceAddress>,
+ #[serde(default)]
+ pub meta: BTreeMap<String, String>,
+ #[serde(default)]
+ pub port: u16,
+ #[serde(default)]
+ pub weights: ConsulServiceWeights,
+ #[serde(default)]
+ pub kind: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulServiceInstance {
+ pub node: ConsulCatalogNode,
+ pub service: ConsulHealthService,
+ #[serde(default)]
+ pub checks: Vec<ConsulHealthCheck>,
+}
+
+impl ConsulClient {
+ pub async fn health_node_checks(
+ &self,
+ node: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ let mut response: ConsulListResponse<Vec<ConsulHealthCheck>> = self
+ .read_list(
+ &format!("/v1/health/node/{}", encode_segment(required(node, "node")?)),
+ options,
+ "read Consul node health",
+ )
+ .await?;
+ mark_maintenance(&mut response.items);
+ Ok(response)
+ }
+
+ pub async fn health_service_checks(
+ &self,
+ service: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ let mut response: ConsulListResponse<Vec<ConsulHealthCheck>> = self
+ .read_list(
+ &format!("/v1/health/checks/{}", encode_segment(required(service, "service")?)),
+ options,
+ "read Consul service checks",
+ )
+ .await?;
+ mark_maintenance(&mut response.items);
+ Ok(response)
+ }
+
+ pub async fn health_service_instances(
+ &self,
+ service: &str,
+ passing: Option<bool>,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulServiceInstance>>, String> {
+ let mut path = format!("/v1/health/service/{}", encode_segment(required(service, "service")?));
+ if let Some(passing) = passing {
+ path.push_str(if passing { "?passing=true" } else { "?passing=false" });
+ }
+ let mut response: ConsulListResponse<Vec<ConsulServiceInstance>> =
+ self.read_list(&path, options, "read Consul service instances").await?;
+ for instance in &mut response.items {
+ mark_maintenance(&mut instance.checks);
+ }
+ Ok(response)
+ }
+
+ pub async fn health_state_checks(
+ &self,
+ state: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ let state = state.trim().to_ascii_lowercase();
+ if !matches!(state.as_str(), "any" | "passing" | "warning" | "critical") {
+ return Err("CONSUL_INVALID_REQUEST: health state must be any, passing, warning, or critical".to_string());
+ }
+ let mut response: ConsulListResponse<Vec<ConsulHealthCheck>> =
+ self.read_list(&format!("/v1/health/state/{state}"), options, "read Consul health state").await?;
+ mark_maintenance(&mut response.items);
+ Ok(response)
+ }
+}
+
+fn required<'a>(value: &'a str, field: &str) -> Result<&'a str, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ Err(format!("CONSUL_INVALID_REQUEST: {field} is required"))
+ } else {
+ Ok(value)
+ }
+}
+
+pub(super) fn mark_maintenance(checks: &mut [ConsulHealthCheck]) {
+ for check in checks {
+ check.maintenance =
+ check.check_id == "_node_maintenance" || check.check_id.starts_with("_service_maintenance:");
+ }
+}
+
+pub async fn consul_health_node_core(
+ state: &AppState,
+ connection_id: &str,
+ node: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ client_for_state(state, connection_id).await?.health_node_checks(node, &options).await
+}
+
+pub async fn consul_health_checks_core(
+ state: &AppState,
+ connection_id: &str,
+ service: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ client_for_state(state, connection_id).await?.health_service_checks(service, &options).await
+}
+
+pub async fn consul_health_service_core(
+ state: &AppState,
+ connection_id: &str,
+ service: &str,
+ passing: Option<bool>,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulServiceInstance>>, String> {
+ client_for_state(state, connection_id).await?.health_service_instances(service, passing, &options).await
+}
+
+pub async fn consul_health_state_core(
+ state: &AppState,
+ connection_id: &str,
+ health_state: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulHealthCheck>>, String> {
+ client_for_state(state, connection_id).await?.health_state_checks(health_state, &options).await
+}
diff --git a/crates/dbx-core/src/consul/kv.rs b/crates/dbx-core/src/consul/kv.rs
new file mode 100644
index 0000000000..7c1f2c0c35
--- /dev/null
+++ b/crates/dbx-core/src/consul/kv.rs
@@ -0,0 +1,573 @@
+use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
+use base64::Engine;
+use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
+use reqwest::{Method, Url};
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::{
+ KvDeleteOptions, KvDeleteResponse, KvGetResponse, KvInt64, KvKeyMetadata, KvKeySummary, KvListPrefixResponse,
+ KvPutOptions, KvPutResponse, KvValue, KvValueEncoding, KvWriteMode,
+};
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::response::{
+ decode_json_body, decode_json_response, decode_text_response, ensure_success, is_consul_kv_not_found,
+ ConsulResponseMetadata, MAX_RESPONSE_BYTES,
+};
+use super::types::ConsulKvEntry;
+
+const MAX_VALUE_BYTES: usize = 512 * 1024;
+pub const MAX_RECURSIVE_ENTRIES: usize = 10_000;
+pub const MAX_RECURSIVE_VALUE_BYTES: usize = 32 * 1024 * 1024;
+const MAX_RECURSIVE_RESPONSE_BYTES: usize = MAX_RESPONSE_BYTES;
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulKvRecord {
+ pub key: String,
+ pub value: KvValue,
+ pub flags: KvInt64,
+ pub create_index: KvInt64,
+ pub modify_index: KvInt64,
+ pub lock_index: KvInt64,
+ pub session: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulRecursiveListResponse {
+ pub entries: Vec<ConsulKvRecord>,
+ pub index: Option<KvInt64>,
+ pub filtered_by_acls: Option<bool>,
+ pub total_value_bytes: u64,
+ pub complete: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulLockRequest {
+ pub key: String,
+ pub session: String,
+ pub value: KvValue,
+ pub flags: Option<KvInt64>,
+ pub expected_modify_index: Option<KvInt64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulLockResponse {
+ pub acquired: bool,
+ pub key: String,
+ pub session: String,
+}
+
+impl ConsulClient {
+ pub(super) async fn acquire_lock(&self, request: ConsulLockRequest) -> Result<ConsulLockResponse, String> {
+ let session = required_lock_field(&request.session, "session")?;
+ let bytes = value_bytes(&request.value)?;
+ if bytes.len() > MAX_VALUE_BYTES {
+ return Err(format!("CONSUL_VALUE_TOO_LARGE: Consul KV values cannot exceed {MAX_VALUE_BYTES} bytes"));
+ }
+ let current = match self.get_required_entry(&request.key).await {
+ Ok(current) => Some(current),
+ Err(error) if error.starts_with("CONSUL_KEY_NOT_FOUND:") => None,
+ Err(error) => return Err(error),
+ };
+ if let Some(current) = &current {
+ if let Some(owner) = current.session.as_deref().filter(|owner| !owner.is_empty()) {
+ if owner != session {
+ return Err("CONSUL_LOCK_CONFLICT: The key is held by a different Consul Session".to_string());
+ }
+ }
+ let expected = request
+ .expected_modify_index
+ .as_ref()
+ .ok_or("CONSUL_CAS_REQUIRED: Acquiring an existing Consul lock requires its ModifyIndex")?;
+ if parse_u64(expected)? != current.modify_index {
+ return Err("CONSUL_CAS_CONFLICT: The Consul KV key changed before lock acquisition".to_string());
+ }
+ } else if request.expected_modify_index.as_ref().is_some_and(|value| value.as_str() != "0") {
+ return Err("CONSUL_CAS_CONFLICT: The Consul KV key no longer exists".to_string());
+ }
+
+ let cas = current.as_ref().map(|entry| entry.modify_index).unwrap_or(0);
+ let flags = request
+ .flags
+ .as_ref()
+ .map(parse_u64)
+ .transpose()?
+ .unwrap_or_else(|| current.as_ref().map(|entry| entry.flags).unwrap_or(0));
+ let mut url = self.kv_url(&request.key)?;
+ self.append_scope(&mut url, false);
+ url.query_pairs_mut()
+ .append_pair("acquire", session)
+ .append_pair("cas", &cas.to_string())
+ .append_pair("flags", &flags.to_string());
+ let response =
+ ensure_success(self.send(Method::PUT, url, Some(bytes)).await?, "acquire Consul KV lock", self.token())
+ .await?;
+ let acquired = decode_text_response(response, "acquire Consul KV lock").await?;
+ if acquired.trim() != "true" {
+ return Err("CONSUL_LOCK_CONFLICT: Consul refused lock acquisition".to_string());
+ }
+ Ok(ConsulLockResponse { acquired: true, key: request.key, session: session.to_string() })
+ }
+
+ pub(super) async fn release_lock(&self, key: &str, session: &str) -> Result<ConsulLockResponse, String> {
+ let session = required_lock_field(session, "session")?;
+ let current = self.get_required_entry(key).await?;
+ if current.session.as_deref() != Some(session) {
+ return Err("CONSUL_LOCK_SESSION_MISMATCH: Only the Session holding this key can release it".to_string());
+ }
+ let bytes = decode_consul_value(current.value.as_deref())?;
+ let mut url = self.kv_url(key)?;
+ self.append_scope(&mut url, false);
+ url.query_pairs_mut()
+ .append_pair("release", session)
+ .append_pair("cas", &current.modify_index.to_string())
+ .append_pair("flags", &current.flags.to_string());
+ let response =
+ ensure_success(self.send(Method::PUT, url, Some(bytes)).await?, "release Consul KV lock", self.token())
+ .await?;
+ let released = decode_text_response(response, "release Consul KV lock").await?;
+ if released.trim() != "true" {
+ return Err("CONSUL_LOCK_CONFLICT: Consul refused lock release".to_string());
+ }
+ Ok(ConsulLockResponse { acquired: false, key: key.to_string(), session: session.to_string() })
+ }
+
+ pub async fn list_recursive(
+ &self,
+ prefix: &str,
+ max_entries: usize,
+ max_value_bytes: usize,
+ ) -> Result<ConsulRecursiveListResponse, String> {
+ self.list_recursive_with_control(prefix, max_entries, max_value_bytes, None).await
+ }
+
+ pub(super) async fn list_recursive_with_control(
+ &self,
+ prefix: &str,
+ max_entries: usize,
+ max_value_bytes: usize,
+ control: Option<&(dyn Fn(usize) -> Result<(), String> + Send + Sync)>,
+ ) -> Result<ConsulRecursiveListResponse, String> {
+ let max_entries = max_entries.clamp(1, MAX_RECURSIVE_ENTRIES);
+ let max_value_bytes = max_value_bytes.clamp(MAX_VALUE_BYTES, MAX_RECURSIVE_VALUE_BYTES);
+ let mut url = self.kv_url(prefix)?;
+ self.append_scope(&mut url, true);
+ url.query_pairs_mut().append_pair("recurse", "");
+ let mut response = self.send(Method::GET, url, None).await?;
+ let metadata = ConsulResponseMetadata::from_response(&response);
+ if is_consul_kv_not_found(&response) {
+ return Ok(ConsulRecursiveListResponse {
+ entries: Vec::new(),
+ index: metadata.index,
+ filtered_by_acls: metadata.filtered_by_acls,
+ total_value_bytes: 0,
+ complete: true,
+ });
+ }
+ if !response.status().is_success() {
+ return ensure_success(response, "list Consul KV prefix recursively", self.token())
+ .await
+ .map(|_| unreachable!());
+ }
+
+ let mut body = Vec::new();
+ while let Some(chunk) = response
+ .chunk()
+ .await
+ .map_err(|error| format!("Failed to read Consul recursive KV response: {}", error.without_url()))?
+ {
+ control.map(|check| check(0)).transpose()?;
+ if body.len().saturating_add(chunk.len()) > MAX_RECURSIVE_RESPONSE_BYTES {
+ return Err(format!(
+ "CONSUL_SCAN_LIMIT_EXCEEDED: Consul recursive KV response exceeds {} MiB",
+ MAX_RECURSIVE_RESPONSE_BYTES / 1024 / 1024
+ ));
+ }
+ body.extend_from_slice(&chunk);
+ }
+ let raw_entries = decode_json_body::<Vec<ConsulKvEntry>>(&body, "list Consul KV prefix recursively")?;
+ if raw_entries.len() > max_entries {
+ return Err(format!("CONSUL_SCAN_LIMIT_EXCEEDED: Consul prefix contains more than {max_entries} keys"));
+ }
+
+ let mut entries = Vec::with_capacity(raw_entries.len());
+ let mut total_value_bytes = 0usize;
+ for (index, entry) in raw_entries.into_iter().enumerate() {
+ control.map(|check| check(index + 1)).transpose()?;
+ let bytes = decode_consul_value(entry.value.as_deref())?;
+ total_value_bytes = total_value_bytes.saturating_add(bytes.len());
+ if total_value_bytes > max_value_bytes {
+ return Err(format!(
+ "CONSUL_SCAN_LIMIT_EXCEEDED: Consul prefix values exceed {} MiB",
+ max_value_bytes / 1024 / 1024
+ ));
+ }
+ entries.push(ConsulKvRecord {
+ key: entry.key,
+ value: value_from_bytes(&bytes),
+ flags: KvInt64(entry.flags.to_string()),
+ create_index: KvInt64(entry.create_index.to_string()),
+ modify_index: KvInt64(entry.modify_index.to_string()),
+ lock_index: KvInt64(entry.lock_index.to_string()),
+ session: entry.session.filter(|session| !session.is_empty()),
+ });
+ }
+ Ok(ConsulRecursiveListResponse {
+ entries,
+ index: metadata.index,
+ filtered_by_acls: metadata.filtered_by_acls,
+ total_value_bytes: total_value_bytes as u64,
+ complete: true,
+ })
+ }
+
+ pub async fn list_prefix(
+ &self,
+ prefix: &str,
+ limit: usize,
+ continuation: Option<&str>,
+ ) -> Result<KvListPrefixResponse, String> {
+ let mut url = self.kv_url(prefix)?;
+ self.append_scope(&mut url, true);
+ url.query_pairs_mut().append_pair("keys", "").append_pair("separator", "/");
+ let response = self.send(Method::GET, url, None).await?;
+ let metadata = ConsulResponseMetadata::from_response(&response);
+ if is_consul_kv_not_found(&response) {
+ return Ok(KvListPrefixResponse {
+ keys: Vec::new(),
+ continuation: None,
+ revision: metadata.index,
+ filtered_by_acls: metadata.filtered_by_acls,
+ });
+ }
+ let response = ensure_success(response, "list KV keys", self.token()).await?;
+ let mut keys = decode_json_response::<Vec<String>>(response, "list KV keys").await?;
+ keys.sort();
+ keys.dedup();
+ if !prefix.is_empty() {
+ keys.retain(|key| key != prefix);
+ }
+ let after = continuation.map(decode_continuation).transpose()?;
+ if let Some(after) = after.as_deref() {
+ keys.retain(|key| key.as_str() > after);
+ }
+ let limit = limit.clamp(1, 500);
+ let has_more = keys.len() > limit;
+ keys.truncate(limit);
+ let next = has_more.then(|| keys.last().map(|key| encode_continuation(key))).flatten();
+ Ok(KvListPrefixResponse {
+ keys: keys.into_iter().map(summary_for_key).collect(),
+ continuation: next,
+ revision: metadata.index,
+ filtered_by_acls: metadata.filtered_by_acls,
+ })
+ }
+
+ pub async fn get_key(&self, key: &str) -> Result<KvGetResponse, String> {
+ let mut url = self.kv_url(key)?;
+ self.append_scope(&mut url, true);
+ let response = self.send(Method::GET, url, None).await?;
+ if is_consul_kv_not_found(&response) {
+ return Ok(KvGetResponse { found: false, key: None, key_bytes: None, value: None, metadata: None });
+ }
+ let response = ensure_success(response, "read KV key", self.token()).await?;
+ let mut entries = decode_json_response::<Vec<ConsulKvEntry>>(response, "read KV key").await?;
+ let entry = entries.pop().ok_or("CONSUL_KEY_NOT_FOUND: Consul returned an empty KV response")?;
+ let bytes = decode_consul_value(entry.value.as_deref())?;
+ let value = value_from_bytes(&bytes);
+ Ok(KvGetResponse {
+ found: true,
+ key: Some(entry.key.clone()),
+ key_bytes: None,
+ value: Some(value),
+ metadata: Some(metadata_for_entry(&entry, bytes.len() as u64)),
+ })
+ }
+
+ pub(super) async fn put_key(
+ &self,
+ key: &str,
+ value: KvValue,
+ options: KvPutOptions,
+ ) -> Result<KvPutResponse, String> {
+ let bytes = value_bytes(&value)?;
+ if bytes.len() > MAX_VALUE_BYTES {
+ return Err(format!(
+ "CONSUL_VALUE_TOO_LARGE: Consul KV values cannot exceed {MAX_VALUE_BYTES} bytes (received {})",
+ bytes.len()
+ ));
+ }
+
+ let creating = matches!(options.write_mode, Some(KvWriteMode::Create))
+ || options.expected_create_revision.as_ref().is_some_and(|value| value.as_str() == "0");
+ let (cas, flags) = if creating {
+ (0, options.flags.as_ref().map(parse_u64).transpose()?.unwrap_or(0))
+ } else {
+ let expected = parse_u64(options.expected_mod_revision.as_ref().ok_or_else(|| {
+ "CONSUL_CAS_REQUIRED: Updating a Consul KV key requires its ModifyIndex".to_string()
+ })?)?;
+ let current = self.get_required_entry(key).await?;
+ ensure_unlocked(&current)?;
+ if current.modify_index != expected {
+ return Err("CONSUL_CAS_CONFLICT: The Consul KV key changed before it could be saved".to_string());
+ }
+ (expected, options.flags.as_ref().map(parse_u64).transpose()?.unwrap_or(current.flags))
+ };
+
+ let mut url = self.kv_url(key)?;
+ self.append_scope(&mut url, false);
+ url.query_pairs_mut().append_pair("cas", &cas.to_string()).append_pair("flags", &flags.to_string());
+ let response =
+ ensure_success(self.send(Method::PUT, url, Some(bytes)).await?, "write KV key", self.token()).await?;
+ let written = decode_text_response(response, "write KV key").await?;
+ if written.trim() != "true" {
+ return Err(if creating {
+ "CONSUL_KEY_ALREADY_EXISTS: The Consul KV key already exists".to_string()
+ } else {
+ "CONSUL_CAS_CONFLICT: The Consul KV key changed before it could be saved".to_string()
+ });
+ }
+ Ok(KvPutResponse { revision: None, key: Some(key.to_string()), created_key: creating.then(|| key.to_string()) })
+ }
+
+ pub(super) async fn delete_key(&self, key: &str, options: KvDeleteOptions) -> Result<KvDeleteResponse, String> {
+ let expected =
+ parse_u64(options.expected_mod_revision.as_ref().ok_or_else(|| {
+ "CONSUL_CAS_REQUIRED: Deleting a Consul KV key requires its ModifyIndex".to_string()
+ })?)?;
+ let current = self.get_required_entry(key).await?;
+ ensure_unlocked(&current)?;
+ if current.modify_index != expected {
+ return Err("CONSUL_CAS_CONFLICT: The Consul KV key changed before it could be deleted".to_string());
+ }
+ let mut url = self.kv_url(key)?;
+ self.append_scope(&mut url, false);
+ url.query_pairs_mut().append_pair("cas", &expected.to_string());
+ let response =
+ ensure_success(self.send(Method::DELETE, url, None).await?, "delete KV key", self.token()).await?;
+ let deleted = decode_text_response(response, "delete KV key").await?;
+ if deleted.trim() != "true" {
+ return Err("CONSUL_CAS_CONFLICT: The Consul KV key changed before it could be deleted".to_string());
+ }
+ Ok(KvDeleteResponse { deleted: 1, revision: None })
+ }
+
+ async fn get_required_entry(&self, key: &str) -> Result<ConsulKvEntry, String> {
+ let mut url = self.kv_url(key)?;
+ self.append_scope(&mut url, true);
+ let response = self.send(Method::GET, url, None).await?;
+ if is_consul_kv_not_found(&response) {
+ return Err("CONSUL_KEY_NOT_FOUND: The Consul KV key no longer exists".to_string());
+ }
+ let response = ensure_success(response, "read KV metadata", self.token()).await?;
+ decode_json_response::<Vec<ConsulKvEntry>>(response, "read KV metadata")
+ .await?
+ .pop()
+ .ok_or_else(|| "CONSUL_KEY_NOT_FOUND: Consul returned an empty KV response".to_string())
+ }
+
+ fn kv_url(&self, key: &str) -> Result<Url, String> {
+ let encoded = key
+ .split('/')
+ .map(|segment| utf8_percent_encode(segment, NON_ALPHANUMERIC).to_string())
+ .collect::<Vec<_>>()
+ .join("/");
+ self.api_url(&format!("/v1/kv/{encoded}"))
+ }
+}
+
+pub async fn consul_list_prefix_core(
+ state: &AppState,
+ connection_id: &str,
+ prefix: &str,
+ limit: usize,
+ continuation: Option<&str>,
+) -> Result<KvListPrefixResponse, String> {
+ client_for_state(state, connection_id).await?.list_prefix(prefix, limit, continuation).await
+}
+
+pub async fn consul_list_recursive_core(
+ state: &AppState,
+ connection_id: &str,
+ prefix: &str,
+ max_entries: usize,
+ max_value_bytes: usize,
+) -> Result<ConsulRecursiveListResponse, String> {
+ client_for_state(state, connection_id).await?.list_recursive(prefix, max_entries, max_value_bytes).await
+}
+
+pub async fn consul_get_core(state: &AppState, connection_id: &str, key: &str) -> Result<KvGetResponse, String> {
+ client_for_state(state, connection_id).await?.get_key(key).await
+}
+
+pub async fn consul_put_core(
+ state: &AppState,
+ connection_id: &str,
+ key: &str,
+ value: KvValue,
+ options: KvPutOptions,
+) -> Result<KvPutResponse, String> {
+ ensure_writable_core(state, connection_id, "write Consul KV key").await?;
+ client_for_state(state, connection_id).await?.put_key(key, value, options).await
+}
+
+pub async fn consul_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ key: &str,
+ options: KvDeleteOptions,
+) -> Result<KvDeleteResponse, String> {
+ ensure_writable_core(state, connection_id, "delete Consul KV key").await?;
+ client_for_state(state, connection_id).await?.delete_key(key, options).await
+}
+
+pub async fn consul_acquire_lock_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulLockRequest,
+) -> Result<ConsulLockResponse, String> {
+ ensure_writable_core(state, connection_id, "acquire Consul KV lock").await?;
+ client_for_state(state, connection_id).await?.acquire_lock(request).await
+}
+
+pub async fn consul_release_lock_core(
+ state: &AppState,
+ connection_id: &str,
+ key: &str,
+ session: &str,
+) -> Result<ConsulLockResponse, String> {
+ ensure_writable_core(state, connection_id, "release Consul KV lock").await?;
+ client_for_state(state, connection_id).await?.release_lock(key, session).await
+}
+
+fn required_lock_field<'a>(value: &'a str, field: &str) -> Result<&'a str, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ Err(format!("CONSUL_INVALID_REQUEST: {field} is required"))
+ } else {
+ Ok(value)
+ }
+}
+
+fn summary_for_key(key: String) -> KvKeySummary {
+ KvKeySummary { key, key_bytes: None, value: None, metadata: empty_metadata() }
+}
+
+fn metadata_for_entry(entry: &ConsulKvEntry, value_size: u64) -> KvKeyMetadata {
+ KvKeyMetadata {
+ create_revision: Some(KvInt64(entry.create_index.to_string())),
+ mod_revision: Some(KvInt64(entry.modify_index.to_string())),
+ version: None,
+ lease: None,
+ ttl: None,
+ value_size: Some(value_size),
+ czxid: None,
+ mzxid: None,
+ pzxid: None,
+ ctime: None,
+ mtime: None,
+ cversion: None,
+ aversion: None,
+ ephemeral_owner: None,
+ data_length: None,
+ num_children: None,
+ flags: Some(KvInt64(entry.flags.to_string())),
+ lock_index: Some(KvInt64(entry.lock_index.to_string())),
+ session: entry.session.clone().filter(|session| !session.is_empty()),
+ }
+}
+
+fn empty_metadata() -> KvKeyMetadata {
+ KvKeyMetadata {
+ create_revision: None,
+ mod_revision: None,
+ version: None,
+ lease: None,
+ ttl: None,
+ value_size: None,
+ czxid: None,
+ mzxid: None,
+ pzxid: None,
+ ctime: None,
+ mtime: None,
+ cversion: None,
+ aversion: None,
+ ephemeral_owner: None,
+ data_length: None,
+ num_children: None,
+ flags: None,
+ lock_index: None,
+ session: None,
+ }
+}
+
+fn decode_consul_value(value: Option<&str>) -> Result<Vec<u8>, String> {
+ match value {
+ Some(value) => {
+ STANDARD.decode(value).map_err(|error| format!("Failed to decode Consul KV Base64 value: {error}"))
+ }
+ None => Ok(Vec::new()),
+ }
+}
+
+fn value_from_bytes(bytes: &[u8]) -> KvValue {
+ match std::str::from_utf8(bytes) {
+ Ok(value) => KvValue { encoding: KvValueEncoding::Utf8, data: value.to_string() },
+ Err(_) => KvValue { encoding: KvValueEncoding::Base64, data: STANDARD.encode(bytes) },
+ }
+}
+
+fn value_bytes(value: &KvValue) -> Result<Vec<u8>, String> {
+ match value.encoding {
+ KvValueEncoding::Utf8 => Ok(value.data.as_bytes().to_vec()),
+ KvValueEncoding::Base64 => STANDARD
+ .decode(value.data.chars().filter(|char| !char.is_whitespace()).collect::<String>())
+ .map_err(|error| format!("Invalid Base64 KV value: {error}")),
+ }
+}
+
+fn parse_u64(value: &KvInt64) -> Result<u64, String> {
+ value.as_str().parse::<u64>().map_err(|_| format!("Invalid Consul index: {}", value.as_str()))
+}
+
+fn ensure_unlocked(entry: &ConsulKvEntry) -> Result<(), String> {
+ if let Some(session) = entry.session.as_deref().filter(|session| !session.is_empty()) {
+ return Err(format!("CONSUL_KEY_LOCKED: The Consul KV key is held by session {session}"));
+ }
+ Ok(())
+}
+
+fn encode_continuation(key: &str) -> String {
+ URL_SAFE_NO_PAD.encode(key.as_bytes())
+}
+
+fn decode_continuation(value: &str) -> Result<String, String> {
+ let bytes = URL_SAFE_NO_PAD.decode(value).map_err(|_| "Invalid Consul continuation token".to_string())?;
+ String::from_utf8(bytes).map_err(|_| "Invalid Consul continuation token".to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn u64_fields_accept_the_full_unsigned_range_only() {
+ assert_eq!(parse_u64(&KvInt64("0".into())).unwrap(), 0);
+ assert_eq!(parse_u64(&KvInt64(u64::MAX.to_string())).unwrap(), u64::MAX);
+ assert!(parse_u64(&KvInt64("-1".into())).is_err());
+ assert!(parse_u64(&KvInt64("18446744073709551616".into())).is_err());
+ }
+
+ #[test]
+ fn binary_values_round_trip_without_utf8_coercion() {
+ let bytes = [0, 0xff, 0x80, b'a'];
+ let value = value_from_bytes(&bytes);
+ assert_eq!(value.encoding, KvValueEncoding::Base64);
+ assert_eq!(value_bytes(&value).unwrap(), bytes);
+ }
+}
diff --git a/crates/dbx-core/src/consul/mesh/config_entries.rs b/crates/dbx-core/src/consul/mesh/config_entries.rs
new file mode 100644
index 0000000000..34933810b5
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/config_entries.rs
@@ -0,0 +1,143 @@
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::super::client::client_for_state;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulConfigEntry {
+ pub kind: String,
+ pub name: String,
+ pub modify_index: u64,
+ pub raw: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulConfigEntryApply {
+ pub kind: String,
+ pub name: String,
+ pub expected_modify_index: u64,
+ pub raw: serde_json::Value,
+}
+
+pub async fn consul_mesh_config_list_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: &str,
+) -> Result<Vec<ConsulConfigEntry>, String> {
+ validate_identifier(kind, "kind")?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/config/{}", segment(kind)))?;
+ let values: Vec<serde_json::Value> =
+ client.request_json(Method::GET, url, None::<&()>, true, "list Service Mesh config entries").await?;
+ values.into_iter().map(config_entry_from_raw).collect()
+}
+
+pub async fn consul_mesh_config_get_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: &str,
+ name: &str,
+) -> Result<ConsulConfigEntry, String> {
+ validate_identifier(kind, "kind")?;
+ validate_identifier(name, "name")?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&config_path(kind, name))?;
+ let value = client.request_json(Method::GET, url, None::<&()>, true, "read Service Mesh config entry").await?;
+ config_entry_from_raw(value)
+}
+
+pub async fn consul_mesh_config_apply_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulConfigEntryApply,
+) -> Result<ConsulConfigEntry, String> {
+ super::super::ensure_writable(state, connection_id, "Service Mesh config entry write").await?;
+ validate_raw_identity(&request)?;
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/config")?;
+ url.query_pairs_mut().append_pair("cas", &request.expected_modify_index.to_string());
+ let applied: bool = client
+ .request_json(Method::PUT, url, Some(&request.raw), false, "apply Service Mesh config entry with CAS")
+ .await?;
+ if !applied {
+ return Err("CONSUL_CAS_CONFLICT: Service Mesh config entry changed after it was loaded".to_string());
+ }
+ consul_mesh_config_get_core(state, connection_id, &request.kind, &request.name).await
+}
+
+pub async fn consul_mesh_config_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: &str,
+ name: &str,
+ expected_modify_index: u64,
+) -> Result<bool, String> {
+ super::super::ensure_writable(state, connection_id, "Service Mesh config entry delete").await?;
+ validate_identifier(kind, "kind")?;
+ validate_identifier(name, "name")?;
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url(&config_path(kind, name))?;
+ url.query_pairs_mut().append_pair("cas", &expected_modify_index.to_string());
+ let deleted: bool = client
+ .request_json(Method::DELETE, url, None::<&()>, false, "delete Service Mesh config entry with CAS")
+ .await?;
+ if !deleted {
+ return Err("CONSUL_CAS_CONFLICT: Service Mesh config entry changed after it was loaded".to_string());
+ }
+ Ok(true)
+}
+
+fn config_entry_from_raw(raw: serde_json::Value) -> Result<ConsulConfigEntry, String> {
+ let kind = raw.get("Kind").and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
+ let name = raw.get("Name").and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
+ let modify_index = raw.get("ModifyIndex").and_then(serde_json::Value::as_u64).unwrap_or(0);
+ if kind.is_empty() || name.is_empty() {
+ return Err("CONSUL_INVALID_RESPONSE: config entry is missing Kind or Name".to_string());
+ }
+ Ok(ConsulConfigEntry { kind, name, modify_index, raw })
+}
+
+fn validate_raw_identity(request: &ConsulConfigEntryApply) -> Result<(), String> {
+ validate_identifier(&request.kind, "kind")?;
+ validate_identifier(&request.name, "name")?;
+ let object = request.raw.as_object().ok_or("CONSUL_INVALID_REQUEST: config entry raw JSON must be an object")?;
+ if object.get("Kind").and_then(serde_json::Value::as_str) != Some(request.kind.as_str())
+ || object.get("Name").and_then(serde_json::Value::as_str) != Some(request.name.as_str())
+ {
+ return Err("CONSUL_INVALID_REQUEST: raw JSON Kind and Name must match the selected resource".to_string());
+ }
+ Ok(())
+}
+
+fn validate_identifier(value: &str, label: &str) -> Result<(), String> {
+ if value.trim().is_empty() || value.len() > 256 {
+ Err(format!("CONSUL_INVALID_REQUEST: config entry {label} is invalid"))
+ } else {
+ Ok(())
+ }
+}
+fn segment(value: &str) -> String {
+ percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
+}
+fn config_path(kind: &str, name: &str) -> String {
+ format!("/v1/config/{}/{}", segment(kind), segment(name))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn raw_identity_must_match() {
+ let request = ConsulConfigEntryApply {
+ kind: "service-defaults".into(),
+ name: "api".into(),
+ expected_modify_index: 4,
+ raw: serde_json::json!({"Kind":"service-defaults","Name":"other"}),
+ };
+ assert!(validate_raw_identity(&request).is_err());
+ }
+}
diff --git a/crates/dbx-core/src/consul/mesh/discovery.rs b/crates/dbx-core/src/consul/mesh/discovery.rs
new file mode 100644
index 0000000000..328387c667
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/discovery.rs
@@ -0,0 +1,40 @@
+use super::super::client::client_for_state;
+use crate::connection::AppState;
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulDiscoveryChain {
+ #[serde(default)]
+ pub service_name: String,
+ #[serde(default)]
+ pub namespace: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub datacenter: String,
+ #[serde(default)]
+ pub protocol: String,
+ #[serde(default)]
+ pub start_node: String,
+ #[serde(default)]
+ pub nodes: BTreeMap<String, serde_json::Value>,
+ #[serde(default)]
+ pub targets: BTreeMap<String, serde_json::Value>,
+}
+
+pub async fn consul_mesh_discovery_chain_core(
+ state: &AppState,
+ connection_id: &str,
+ service: &str,
+) -> Result<ConsulDiscoveryChain, String> {
+ if service.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: discovery service is required".into());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let service = percent_encoding::utf8_percent_encode(service, percent_encoding::NON_ALPHANUMERIC);
+ let url = client.api_url(&format!("/v1/discovery-chain/{service}"))?;
+ client.request_json(Method::GET, url, None::<&()>, true, "compile discovery chain").await
+}
diff --git a/crates/dbx-core/src/consul/mesh/exported_services.rs b/crates/dbx-core/src/consul/mesh/exported_services.rs
new file mode 100644
index 0000000000..123afce8b5
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/exported_services.rs
@@ -0,0 +1,42 @@
+use super::super::client::client_for_state;
+use super::config_entries::{consul_mesh_config_apply_core, ConsulConfigEntry, ConsulConfigEntryApply};
+use crate::connection::AppState;
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulExportedService {
+ #[serde(default)]
+ pub service: String,
+ #[serde(default)]
+ pub namespace: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub consumers: Vec<serde_json::Value>,
+}
+
+pub async fn consul_mesh_exported_services_list_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<Vec<ConsulExportedService>, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/exported-services")?;
+ client.request_json(Method::GET, url, None::<&()>, true, "list exported services").await
+}
+
+pub async fn consul_mesh_exported_services_apply_core(
+ state: &AppState,
+ connection_id: &str,
+ name: &str,
+ expected_modify_index: u64,
+ raw: serde_json::Value,
+) -> Result<ConsulConfigEntry, String> {
+ consul_mesh_config_apply_core(
+ state,
+ connection_id,
+ ConsulConfigEntryApply { kind: "exported-services".into(), name: name.into(), expected_modify_index, raw },
+ )
+ .await
+}
diff --git a/crates/dbx-core/src/consul/mesh/intentions.rs b/crates/dbx-core/src/consul/mesh/intentions.rs
new file mode 100644
index 0000000000..ed13799002
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/intentions.rs
@@ -0,0 +1,219 @@
+use reqwest::{Method, Url};
+use serde::{Deserialize, Serialize};
+
+use super::super::client::client_for_state;
+use crate::connection::AppState;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulIntention {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub source_name: String,
+ #[serde(default)]
+ pub destination_name: String,
+ #[serde(default)]
+ pub source_namespace: String,
+ #[serde(default)]
+ pub destination_namespace: String,
+ #[serde(default)]
+ pub source_partition: String,
+ #[serde(default)]
+ pub destination_partition: String,
+ #[serde(default)]
+ pub action: String,
+ #[serde(default)]
+ pub permissions: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub precedence: u64,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulIntentionMatchRequest {
+ pub by: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulIntentionCheckRequest {
+ pub source: String,
+ pub destination: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulIntentionExactRequest {
+ pub source: String,
+ pub destination: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulIntentionCheckResponse {
+ pub allowed: bool,
+}
+
+pub async fn consul_mesh_intentions_list_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<Vec<ConsulIntention>, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/connect/intentions")?;
+ client.request_json(Method::GET, url, None::<&()>, true, "list intentions").await
+}
+
+pub async fn consul_mesh_intention_get_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulIntention, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/connect/intentions/{}", segment(id)))?;
+ client.request_json(Method::GET, url, None::<&()>, true, "read intention").await
+}
+
+pub async fn consul_mesh_intention_get_exact_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulIntentionExactRequest,
+) -> Result<ConsulIntention, String> {
+ validate_exact_request(&request)?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/connect/intentions/exact")?;
+ let url = exact_intention_url(url, &request.source, &request.destination);
+ client.request_json(Method::GET, url, None::<&()>, true, "read exact intention").await
+}
+
+pub async fn consul_mesh_intention_upsert_core(
+ state: &AppState,
+ connection_id: &str,
+ item: ConsulIntention,
+) -> Result<ConsulIntention, String> {
+ super::super::ensure_writable(state, connection_id, "intention write").await?;
+ if item.source_name.trim().is_empty() || item.destination_name.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: intention SourceName and DestinationName are required".into());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/connect/intentions/exact")?;
+ let url = exact_intention_url(url, &item.source_name, &item.destination_name);
+ let written: bool = client.request_json(Method::PUT, url, Some(&item), false, "upsert intention").await?;
+ if !written {
+ return Err("CONSUL_WRITE_REJECTED: Consul rejected the intention upsert".to_string());
+ }
+ let mut url = client.api_url("/v1/connect/intentions/exact")?;
+ url.query_pairs_mut().append_pair("source", &item.source_name).append_pair("destination", &item.destination_name);
+ client.request_json(Method::GET, url, None::<&()>, true, "read upserted intention").await
+}
+
+pub async fn consul_mesh_intention_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<bool, String> {
+ super::super::ensure_writable(state, connection_id, "intention delete").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/connect/intentions/{}", segment(id)))?;
+ client.send_json(Method::DELETE, url, None::<&()>, false, "delete intention").await?;
+ Ok(true)
+}
+
+pub async fn consul_mesh_intention_delete_exact_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulIntentionExactRequest,
+) -> Result<bool, String> {
+ super::super::ensure_writable(state, connection_id, "exact intention delete").await?;
+ validate_exact_request(&request)?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/connect/intentions/exact")?;
+ let url = exact_intention_url(url, &request.source, &request.destination);
+ client.send_json(Method::DELETE, url, None::<&()>, false, "delete exact intention").await?;
+ Ok(true)
+}
+
+pub async fn consul_mesh_intention_match_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulIntentionMatchRequest,
+) -> Result<Vec<ConsulIntention>, String> {
+ if !matches!(request.by.as_str(), "source" | "destination") {
+ return Err("CONSUL_INVALID_REQUEST: intention match 'by' must be source or destination".into());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/connect/intentions/match")?;
+ url.query_pairs_mut().append_pair("by", &request.by).append_pair("name", &request.name);
+ client.request_json(Method::GET, url, None::<&()>, true, "match intentions").await
+}
+
+pub async fn consul_mesh_intention_check_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulIntentionCheckRequest,
+) -> Result<ConsulIntentionCheckResponse, String> {
+ if request.source.trim().is_empty() || request.destination.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: intention check source and destination are required".into());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/connect/intentions/check")?;
+ url.query_pairs_mut().append_pair("source", &request.source).append_pair("destination", &request.destination);
+ client.request_json(Method::GET, url, None::<&()>, true, "check intention authorization").await
+}
+
+fn segment(value: &str) -> String {
+ percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
+}
+
+fn exact_intention_url(mut url: Url, source: &str, destination: &str) -> Url {
+ url.query_pairs_mut().append_pair("source", source).append_pair("destination", destination);
+ url
+}
+
+fn validate_exact_request(request: &ConsulIntentionExactRequest) -> Result<(), String> {
+ if request.source.trim().is_empty() || request.destination.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: exact intention source and destination are required".to_string());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn exact_upsert_uses_official_method_path_and_query() {
+ let base = Url::parse("https://consul.example/proxy/v1/connect/intentions/exact").unwrap();
+ let url = exact_intention_url(base, "api/web", "payments v2");
+
+ assert_eq!(url.path(), "/proxy/v1/connect/intentions/exact");
+ assert_eq!(url.query(), Some("source=api%2Fweb&destination=payments+v2"));
+ }
+
+ #[test]
+ fn exact_read_and_delete_share_the_official_path_and_validate_names() {
+ let base = Url::parse("https://consul.example/proxy/v1/connect/intentions/exact").unwrap();
+ let request = ConsulIntentionExactRequest { source: "api".into(), destination: "db".into() };
+ assert!(validate_exact_request(&request).is_ok());
+ let url = exact_intention_url(base, &request.source, &request.destination);
+ assert_eq!(url.query(), Some("source=api&destination=db"));
+ assert!(validate_exact_request(&ConsulIntentionExactRequest { source: "".into(), destination: "db".into() })
+ .is_err());
+ }
+
+ #[test]
+ fn check_endpoint_uses_official_path() {
+ let mut url = Url::parse("https://consul.example/proxy/v1/connect/intentions/check").unwrap();
+ url.query_pairs_mut().append_pair("source", "api").append_pair("destination", "db");
+
+ assert_eq!(url.path(), "/proxy/v1/connect/intentions/check");
+ assert_eq!(url.query(), Some("source=api&destination=db"));
+ }
+}
diff --git a/crates/dbx-core/src/consul/mesh/mod.rs b/crates/dbx-core/src/consul/mesh/mod.rs
new file mode 100644
index 0000000000..2d1cdb5c6e
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/mod.rs
@@ -0,0 +1,11 @@
+mod config_entries;
+mod discovery;
+mod exported_services;
+mod intentions;
+mod peering;
+
+pub use config_entries::*;
+pub use discovery::*;
+pub use exported_services::*;
+pub use intentions::*;
+pub use peering::*;
diff --git a/crates/dbx-core/src/consul/mesh/peering.rs b/crates/dbx-core/src/consul/mesh/peering.rs
new file mode 100644
index 0000000000..3cb8bee910
--- /dev/null
+++ b/crates/dbx-core/src/consul/mesh/peering.rs
@@ -0,0 +1,111 @@
+use super::super::client::client_for_state;
+use super::super::ConsulSecret;
+use crate::connection::AppState;
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPeering {
+ #[serde(rename = "ID", default)]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub state: String,
+ #[serde(rename = "PeerID", default)]
+ pub peer_id: String,
+ #[serde(default)]
+ pub peer_server_name: String,
+ #[serde(rename = "PeerCAPems", default)]
+ pub peer_ca_pems: Vec<String>,
+ #[serde(default)]
+ pub peer_server_addresses: Vec<String>,
+ #[serde(default)]
+ pub imported_services: Vec<String>,
+ #[serde(default)]
+ pub exported_services: Vec<String>,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPeeringGenerateRequest {
+ pub peer_name: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub meta: serde_json::Value,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPeeringToken {
+ pub peering_token: ConsulSecret,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPeeringEstablishRequest {
+ pub peer_name: String,
+ pub peering_token: ConsulSecret,
+ #[serde(default)]
+ pub partition: String,
+}
+
+pub async fn consul_mesh_peering_list_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<Vec<ConsulPeering>, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/peerings")?;
+ client.request_json(Method::GET, url, None::<&()>, true, "list peerings").await
+}
+pub async fn consul_mesh_peering_get_core(
+ state: &AppState,
+ connection_id: &str,
+ name: &str,
+) -> Result<ConsulPeering, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/peering/{}", segment(name)))?;
+ client.request_json(Method::GET, url, None::<&()>, true, "read peering").await
+}
+pub async fn consul_mesh_peering_generate_token_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulPeeringGenerateRequest,
+) -> Result<ConsulPeeringToken, String> {
+ super::super::ensure_writable(state, connection_id, "peering token generation").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/peering/token")?;
+ client.request_json(Method::POST, url, Some(&request), false, "generate peering token").await
+}
+pub async fn consul_mesh_peering_establish_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulPeeringEstablishRequest,
+) -> Result<ConsulPeering, String> {
+ super::super::ensure_writable(state, connection_id, "peering establish").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/peering/establish")?;
+ client.request_json(Method::POST, url, Some(&request), false, "establish peering").await
+}
+pub async fn consul_mesh_peering_delete_core(
+ state: &AppState,
+ connection_id: &str,
+ name: &str,
+) -> Result<bool, String> {
+ super::super::ensure_writable(state, connection_id, "peering delete").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/peering/{}", segment(name)))?;
+ client.send_json(Method::DELETE, url, None::<&()>, false, "delete peering").await?;
+ Ok(true)
+}
+fn segment(value: &str) -> String {
+ percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
+}
diff --git a/crates/dbx-core/src/consul/mod.rs b/crates/dbx-core/src/consul/mod.rs
new file mode 100644
index 0000000000..e2b050bbc9
--- /dev/null
+++ b/crates/dbx-core/src/consul/mod.rs
@@ -0,0 +1,107 @@
+mod acl;
+mod agent;
+mod archive;
+mod blocking;
+mod bulk;
+mod capabilities;
+mod catalog;
+mod client;
+mod config;
+mod enterprise;
+mod health;
+mod kv;
+pub mod mesh;
+mod operator;
+mod response;
+mod search;
+mod session;
+mod status;
+#[cfg(test)]
+mod test_support;
+mod tools;
+mod txn;
+mod types;
+
+pub use acl::*;
+pub use agent::*;
+pub use archive::{
+ consul_export_bundle_core, consul_import_execute_core, consul_import_preview_core, ConsulBundleEntry,
+ ConsulBundleScope, ConsulExportRequest, ConsulExportScopeKind, ConsulImportConflictPolicy, ConsulImportOperation,
+ ConsulImportOutcome, ConsulImportPreview, ConsulImportPreviewRow, ConsulImportReport, ConsulImportRequest,
+ ConsulImportResultItem, ConsulKvBundle,
+};
+pub use blocking::{
+ consul_blocking_query_core, consul_cancel_blocking_core, consul_domain_watch_core, ConsulBlockingRequest,
+ ConsulBlockingResponse, ConsulDomainWatchItems, ConsulDomainWatchRequest, ConsulDomainWatchResponse,
+ ConsulDomainWatchTarget,
+};
+pub use bulk::{
+ consul_delete_prefix_execute_core, consul_delete_prefix_preview_core, ConsulDeleteCandidate, ConsulDeleteOutcome,
+ ConsulDeletePrefixPreview, ConsulDeletePrefixReport, ConsulDeletePrefixRequest, ConsulDeleteResultItem,
+};
+pub use capabilities::{consul_capabilities_core, ConsulCapabilities, ConsulCapabilityStatus};
+pub use catalog::*;
+pub use client::ConsulClient;
+pub use config::{ConsulAgentTarget, ConsulConfig, ConsulConsistency, ConsulScope};
+pub use enterprise::*;
+pub use health::*;
+pub use kv::{
+ consul_acquire_lock_core, consul_delete_core, consul_get_core, consul_list_prefix_core, consul_list_recursive_core,
+ consul_put_core, consul_release_lock_core, ConsulKvRecord, ConsulLockRequest, ConsulLockResponse,
+ ConsulRecursiveListResponse, MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES,
+};
+pub use operator::*;
+pub use response::ConsulResponseMetadata;
+pub use search::{
+ consul_cancel_search_core, consul_search_core, consul_search_progress_core, ConsulSearchMatch,
+ ConsulSearchProgress, ConsulSearchRequest, ConsulSearchResponse,
+};
+pub use session::*;
+pub use status::*;
+pub use tools::*;
+pub use txn::{
+ consul_rename_key_core, consul_txn_core, ConsulTxnError, ConsulTxnKvOperation, ConsulTxnKvResult, ConsulTxnRequest,
+ ConsulTxnResult, ConsulTxnVerb, MAX_TXN_OPERATIONS,
+};
+
+async fn ensure_writable(state: &crate::connection::AppState, connection_id: &str, action: &str) -> Result<(), String> {
+ if let Some(name) = crate::query::connection_readonly_name(state, connection_id).await {
+ return Err(format!(
+ "CONSUL_READ_ONLY: connection '{name}' has read-only protection enabled. {action} blocked."
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod contract_tests {
+ #[test]
+ fn low_level_mutations_are_not_public_outside_the_consul_module() {
+ let modules = [
+ (include_str!("kv.rs"), &["acquire_lock", "release_lock", "put_key", "delete_key"] as &[&str]),
+ (include_str!("txn.rs"), &["txn"] as &[&str]),
+ (
+ include_str!("agent.rs"),
+ &[
+ "register_agent_service",
+ "deregister_agent_service",
+ "set_agent_service_maintenance",
+ "register_agent_check",
+ "deregister_agent_check",
+ "update_ttl_check",
+ ] as &[&str],
+ ),
+ (include_str!("session.rs"), &["create_session", "renew_session", "destroy_session"] as &[&str]),
+ ];
+
+ for (source, methods) in modules {
+ for method in methods {
+ assert!(
+ source.contains(&format!("pub(super) async fn {method}")),
+ "{method} must remain module-private so callers cannot bypass Core read-only checks"
+ );
+ assert!(!source.contains(&format!("pub async fn {method}")), "{method} must not be publicly callable");
+ }
+ }
+ }
+}
diff --git a/crates/dbx-core/src/consul/operator.rs b/crates/dbx-core/src/consul/operator.rs
new file mode 100644
index 0000000000..b7fa64e4e9
--- /dev/null
+++ b/crates/dbx-core/src/consul/operator.rs
@@ -0,0 +1,557 @@
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use flate2::read::GzDecoder;
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use std::io::Read;
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::response::ensure_success;
+
+const MAX_SNAPSHOT_BYTES: usize = 128 * 1024 * 1024;
+const MAX_SNAPSHOT_EXPANDED_BYTES: u64 = 512 * 1024 * 1024;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulOperatorField {
+ pub name: String,
+ pub value: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulOperatorDocument {
+ pub kind: String,
+ pub fields: Vec<ConsulOperatorField>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulOperatorReadKind {
+ AutopilotConfiguration,
+ AutopilotHealth,
+ AutopilotState,
+ RaftConfiguration,
+ Usage,
+ License,
+ Audit,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulAutopilotUpdate {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cleanup_dead_servers: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_contact_threshold: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_trailing_logs: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub min_quorum: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub server_stabilization_time: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub redundancy_zone_tag: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub disable_upgrade_migration: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub upgrade_version_tag: Option<String>,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSnapshotRestoreRequest {
+ pub snapshot_base64: String,
+ pub target_datacenter: String,
+ pub confirmation: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSnapshot {
+ pub data_base64: String,
+ pub size_bytes: usize,
+ pub datacenter: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulRaftWriteRequest {
+ pub server_id: Option<String>,
+ pub address: Option<String>,
+ pub confirmation: String,
+}
+
+#[derive(Clone, Copy, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ConsulKeyringOperation {
+ Install,
+ Use,
+ Remove,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulKeyringWriteRequest {
+ pub operation: ConsulKeyringOperation,
+ pub key: String,
+ pub confirmation: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "PascalCase")]
+struct ConsulKeyringWriteBody<'a> {
+ key: &'a str,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulLicenseWriteRequest {
+ pub license: String,
+ pub confirmation: String,
+}
+
+pub async fn consul_operator_read_core(
+ state: &AppState,
+ connection_id: &str,
+ kind: ConsulOperatorReadKind,
+) -> Result<ConsulOperatorDocument, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let path = match kind {
+ ConsulOperatorReadKind::AutopilotConfiguration => "/v1/operator/autopilot/configuration",
+ ConsulOperatorReadKind::AutopilotHealth => "/v1/operator/autopilot/health",
+ ConsulOperatorReadKind::AutopilotState => "/v1/operator/autopilot/state",
+ ConsulOperatorReadKind::RaftConfiguration => "/v1/operator/raft/configuration",
+ ConsulOperatorReadKind::Usage => "/v1/operator/usage",
+ ConsulOperatorReadKind::License => "/v1/operator/license",
+ ConsulOperatorReadKind::Audit => "/v1/operator/audit-hash",
+ };
+ let url = client.api_url(path)?;
+ let value: serde_json::Value = if matches!(kind, ConsulOperatorReadKind::Audit) {
+ client
+ .request_json(
+ Method::POST,
+ url,
+ Some(&serde_json::json!({ "Input": "dbx-operator-audit" })),
+ true,
+ "read Consul audit hash",
+ )
+ .await?
+ } else {
+ client.request_json(Method::GET, url, None::<&()>, true, "read Consul operator state").await?
+ };
+ Ok(document(format!("{kind:?}"), value))
+}
+
+pub async fn consul_snapshot_generate_core(state: &AppState, connection_id: &str) -> Result<ConsulSnapshot, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/snapshot")?;
+ client.append_scope(&mut url, true);
+ let mut response =
+ ensure_success(client.send(Method::GET, url, None).await?, "generate Consul snapshot", client.token()).await?;
+ let mut bytes = Vec::new();
+ while let Some(chunk) =
+ response.chunk().await.map_err(|error| format!("Failed to read snapshot: {}", error.without_url()))?
+ {
+ if bytes.len().saturating_add(chunk.len()) > MAX_SNAPSHOT_BYTES {
+ return Err("CONSUL_SNAPSHOT_TOO_LARGE: Snapshot exceeds 128 MiB".to_string());
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ Ok(ConsulSnapshot {
+ data_base64: STANDARD.encode(&bytes),
+ size_bytes: bytes.len(),
+ datacenter: client.datacenter().to_string(),
+ })
+}
+
+pub async fn consul_snapshot_restore_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulSnapshotRestoreRequest,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "snapshot_restore", "restore Consul snapshot").await?;
+ let client = client_for_state(state, connection_id).await?;
+ validate_datacenter_and_confirmation(
+ &client,
+ &request.target_datacenter,
+ &request.confirmation,
+ &format!("RESTORE SNAPSHOT {}", request.target_datacenter),
+ )?;
+ let snapshot =
+ STANDARD.decode(request.snapshot_base64.trim()).map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: {error}"))?;
+ if snapshot.is_empty() || snapshot.len() > MAX_SNAPSHOT_BYTES {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot is empty or exceeds 128 MiB".to_string());
+ }
+ let snapshot = tokio::task::spawn_blocking(move || {
+ validate_snapshot_archive(&snapshot)?;
+ Ok::<_, String>(snapshot)
+ })
+ .await
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Snapshot validation task failed: {error}"))??;
+ let mut url = client.api_url("/v1/snapshot")?;
+ client.append_scope(&mut url, false);
+ ensure_success(client.send(Method::PUT, url, Some(snapshot)).await?, "restore Consul snapshot", client.token())
+ .await
+ .map(|_| ())
+}
+
+fn validate_snapshot_archive(snapshot: &[u8]) -> Result<(), String> {
+ if snapshot.len() < 10 || !snapshot.starts_with(&[0x1f, 0x8b, 0x08]) {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot must be a gzip archive generated by Consul".to_string());
+ }
+
+ let decoder = GzDecoder::new(snapshot);
+ let mut archive = tar::Archive::new(decoder);
+ let mut digests = HashMap::new();
+ let mut checksum_manifest = None;
+ let mut expanded_bytes = 0_u64;
+ let mut entry_count = 0_u8;
+ let entries =
+ archive.entries().map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Invalid snapshot archive: {error}"))?;
+
+ for entry in entries {
+ entry_count = entry_count
+ .checked_add(1)
+ .ok_or_else(|| "CONSUL_SNAPSHOT_INVALID: Snapshot contains too many entries".to_string())?;
+ if entry_count > 64 {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot contains too many entries".to_string());
+ }
+ let mut entry = entry.map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Invalid snapshot entry: {error}"))?;
+ let size = entry.size();
+ expanded_bytes = expanded_bytes
+ .checked_add(size)
+ .ok_or_else(|| "CONSUL_SNAPSHOT_INVALID: Snapshot expanded size overflow".to_string())?;
+ if expanded_bytes > MAX_SNAPSHOT_EXPANDED_BYTES {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot expands beyond 512 MiB".to_string());
+ }
+
+ let path = entry
+ .path()
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Invalid snapshot path: {error}"))?
+ .to_string_lossy()
+ .trim_start_matches("./")
+ .to_string();
+ match path.as_str() {
+ "meta.json" | "state.bin" => {
+ let mut hasher = Sha256::new();
+ let mut buffer = [0_u8; 64 * 1024];
+ let mut bytes_read = 0_u64;
+ loop {
+ let count = entry
+ .read(&mut buffer)
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Failed to read {path}: {error}"))?;
+ if count == 0 {
+ break;
+ }
+ bytes_read += count as u64;
+ hasher.update(&buffer[..count]);
+ }
+ if bytes_read == 0 {
+ return Err(format!("CONSUL_SNAPSHOT_INVALID: Snapshot entry {path} is empty"));
+ }
+ if digests.insert(path.clone(), hex_digest(hasher.finalize().as_slice())).is_some() {
+ return Err(format!("CONSUL_SNAPSHOT_INVALID: Snapshot contains duplicate {path}"));
+ }
+ }
+ "SHA256SUMS" => {
+ if size > 64 * 1024 {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot checksum manifest is too large".to_string());
+ }
+ let mut manifest = Vec::with_capacity(size as usize);
+ entry
+ .read_to_end(&mut manifest)
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Failed to read checksum manifest: {error}"))?;
+ if checksum_manifest.replace(manifest).is_some() {
+ return Err("CONSUL_SNAPSHOT_INVALID: Snapshot contains duplicate SHA256SUMS".to_string());
+ }
+ }
+ _ => {
+ std::io::copy(&mut entry, &mut std::io::sink())
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Failed to read snapshot entry: {error}"))?;
+ }
+ }
+ }
+
+ let mut decoder = archive.into_inner();
+ std::io::copy(&mut decoder, &mut std::io::sink())
+ .map_err(|error| format!("CONSUL_SNAPSHOT_INVALID: Corrupt gzip stream: {error}"))?;
+
+ let manifest =
+ checksum_manifest.ok_or_else(|| "CONSUL_SNAPSHOT_INVALID: Snapshot is missing SHA256SUMS".to_string())?;
+ let manifest = std::str::from_utf8(&manifest)
+ .map_err(|_| "CONSUL_SNAPSHOT_INVALID: Snapshot checksum manifest is not UTF-8".to_string())?;
+ let expected = parse_checksum_manifest(manifest)?;
+ for required in ["meta.json", "state.bin"] {
+ let actual =
+ digests.get(required).ok_or_else(|| format!("CONSUL_SNAPSHOT_INVALID: Snapshot is missing {required}"))?;
+ let expected = expected
+ .get(required)
+ .ok_or_else(|| format!("CONSUL_SNAPSHOT_INVALID: Checksum manifest is missing {required}"))?;
+ if !actual.eq_ignore_ascii_case(expected) {
+ return Err(format!("CONSUL_SNAPSHOT_INVALID: Checksum mismatch for {required}"));
+ }
+ }
+ Ok(())
+}
+
+fn parse_checksum_manifest(manifest: &str) -> Result<HashMap<String, String>, String> {
+ let mut checksums = HashMap::new();
+ for line in manifest.lines().filter(|line| !line.trim().is_empty()) {
+ let mut fields = line.split_whitespace();
+ let checksum = fields.next().unwrap_or_default();
+ let path = fields.next().unwrap_or_default().trim_start_matches('*').trim_start_matches("./");
+ if checksum.len() != 64 || !checksum.bytes().all(|byte| byte.is_ascii_hexdigit()) || path.is_empty() {
+ return Err("CONSUL_SNAPSHOT_INVALID: Malformed SHA256SUMS entry".to_string());
+ }
+ if checksums.insert(path.to_string(), checksum.to_string()).is_some() {
+ return Err(format!("CONSUL_SNAPSHOT_INVALID: Duplicate SHA256SUMS entry for {path}"));
+ }
+ }
+ Ok(checksums)
+}
+
+fn hex_digest(digest: &[u8]) -> String {
+ digest.iter().map(|byte| format!("{byte:02x}")).collect()
+}
+
+pub async fn consul_autopilot_update_core(
+ state: &AppState,
+ connection_id: &str,
+ update: ConsulAutopilotUpdate,
+ confirmation: &str,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "autopilot", "update Consul Autopilot").await?;
+ if confirmation != "UPDATE AUTOPILOT" {
+ return Err("CONSUL_CONFIRMATION_REQUIRED: Enter UPDATE AUTOPILOT".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/operator/autopilot/configuration")?;
+ client.send_json(Method::PUT, url, Some(&update), false, "update Consul Autopilot").await.map(|_| ())
+}
+
+pub async fn consul_raft_transfer_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulRaftWriteRequest,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "raft", "transfer Consul Raft leadership").await?;
+ let id =
+ request.server_id.filter(|id| !id.is_empty()).ok_or("CONSUL_RAFT_TARGET_REQUIRED: Server ID is required")?;
+ if request.confirmation != id {
+ return Err("CONSUL_CONFIRMATION_REQUIRED: Re-enter the target server ID".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/operator/raft/transfer-leader")?;
+ url.query_pairs_mut().append_pair("id", &id);
+ client.send_json(Method::POST, url, None::<&()>, false, "transfer Raft leadership").await.map(|_| ())
+}
+
+pub async fn consul_raft_remove_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulRaftWriteRequest,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "raft", "remove Consul Raft peer").await?;
+ let (key, target) = match (
+ request.server_id.filter(|value| !value.is_empty()),
+ request.address.filter(|value| !value.is_empty()),
+ ) {
+ (Some(id), None) => ("id", id),
+ (None, Some(address)) => ("address", address),
+ _ => return Err("CONSUL_RAFT_TARGET_INVALID: Specify exactly one server ID or address".to_string()),
+ };
+ if request.confirmation != target {
+ return Err("CONSUL_CONFIRMATION_REQUIRED: Re-enter the peer identifier".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/operator/raft/peer")?;
+ url.query_pairs_mut().append_pair(key, &target);
+ client.send_json(Method::DELETE, url, None::<&()>, false, "remove Raft peer").await.map(|_| ())
+}
+
+pub async fn consul_keyring_write_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulKeyringWriteRequest,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "keyring", "modify Consul gossip keyring").await?;
+ if request.confirmation != "CHANGE KEYRING" {
+ return Err("CONSUL_CONFIRMATION_REQUIRED: Enter CHANGE KEYRING".to_string());
+ }
+ if request.key.trim().is_empty() {
+ return Err("CONSUL_KEYRING_KEY_REQUIRED: Gossip key is required".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let method = match request.operation {
+ ConsulKeyringOperation::Install => Method::POST,
+ ConsulKeyringOperation::Use => Method::PUT,
+ ConsulKeyringOperation::Remove => Method::DELETE,
+ };
+ let url = client.api_url("/v1/operator/keyring")?;
+ let body = ConsulKeyringWriteBody { key: request.key.trim() };
+ client.send_json(method, url, Some(&body), false, "modify Consul gossip keyring").await.map(|_| ())
+}
+
+pub async fn consul_license_write_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulLicenseWriteRequest,
+) -> Result<(), String> {
+ ensure_operator_write(state, connection_id, "license", "update Consul license").await?;
+ if request.confirmation != "UPDATE LICENSE" {
+ return Err("CONSUL_CONFIRMATION_REQUIRED: Enter UPDATE LICENSE".to_string());
+ }
+ if request.license.trim().is_empty() {
+ return Err("CONSUL_LICENSE_REQUIRED: License is required".to_string());
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/operator/license")?;
+ client.append_scope(&mut url, false);
+ ensure_success(
+ client.send(Method::PUT, url, Some(request.license.into_bytes())).await?,
+ "update Consul license",
+ client.token(),
+ )
+ .await
+ .map(|_| ())
+}
+
+async fn ensure_operator_write(
+ state: &AppState,
+ connection_id: &str,
+ feature: &str,
+ action: &str,
+) -> Result<(), String> {
+ ensure_writable_core(state, connection_id, action).await?;
+ let client = client_for_state(state, connection_id).await?;
+ if !client.operator_feature_enabled(feature) {
+ return Err(format!("CONSUL_OPERATOR_FEATURE_DISABLED: {feature} is disabled by default"));
+ }
+ Ok(())
+}
+
+fn validate_datacenter_and_confirmation(
+ client: &ConsulClient,
+ target: &str,
+ confirmation: &str,
+ expected: &str,
+) -> Result<(), String> {
+ if client.datacenter().is_empty() || target != client.datacenter() {
+ return Err("CONSUL_DATACENTER_MISMATCH: Snapshot target must match the configured Datacenter".to_string());
+ }
+ if confirmation != expected {
+ return Err(format!("CONSUL_CONFIRMATION_REQUIRED: Enter {expected}"));
+ }
+ Ok(())
+}
+
+fn document(kind: String, value: serde_json::Value) -> ConsulOperatorDocument {
+ let mut fields = Vec::new();
+ if let Some(object) = value.as_object() {
+ for (name, value) in object {
+ let lower = name.to_ascii_lowercase();
+ if lower.contains("secret") || lower.contains("token") || lower == "license" {
+ continue;
+ }
+ let mut value = value.clone();
+ redact_nested_sensitive_fields(&mut value);
+ let mut rendered = match &value {
+ serde_json::Value::String(value) => value.clone(),
+ _ => value.to_string(),
+ };
+ rendered.truncate(4096);
+ fields.push(ConsulOperatorField { name: name.clone(), value: rendered });
+ }
+ }
+ ConsulOperatorDocument { kind, fields }
+}
+
+fn redact_nested_sensitive_fields(value: &mut serde_json::Value) {
+ match value {
+ serde_json::Value::Object(object) => {
+ object.retain(|name, _| {
+ let lower = name.to_ascii_lowercase();
+ !lower.contains("secret") && !lower.contains("token") && lower != "license"
+ });
+ for value in object.values_mut() {
+ redact_nested_sensitive_fields(value);
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for value in values {
+ redact_nested_sensitive_fields(value);
+ }
+ }
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn operator_document_drops_sensitive_fields() {
+ let result = document(
+ "license".to_string(),
+ serde_json::json!({
+ "SecretID":"top-secret",
+ "Healthy":true,
+ "Config": { "PeeringToken": "nested-secret", "Mode": "safe" }
+ }),
+ );
+ assert_eq!(result.fields.len(), 2);
+ assert!(result.fields.iter().any(|field| field.name == "Healthy"));
+ let serialized = serde_json::to_string(&result).unwrap();
+ assert!(!serialized.contains("top-secret"));
+ assert!(!serialized.contains("nested-secret"));
+ assert!(serialized.contains("safe"));
+ }
+
+ #[test]
+ fn keyring_body_uses_the_official_pascal_case_field() {
+ let body = ConsulKeyringWriteBody { key: "sensitive-gossip-key" };
+ assert_eq!(serde_json::to_value(body).unwrap(), serde_json::json!({ "Key": "sensitive-gossip-key" }));
+ }
+
+ #[test]
+ fn snapshot_preflight_requires_a_gzip_archive() {
+ assert!(validate_snapshot_archive(b"not-a-snapshot").is_err());
+ let valid = snapshot_fixture(b"raft-state");
+ assert!(validate_snapshot_archive(&valid).is_ok());
+
+ let mut truncated = valid.clone();
+ truncated.truncate(truncated.len() - 4);
+ assert!(validate_snapshot_archive(&truncated).is_err());
+
+ let invalid_checksum = snapshot_fixture_with_checksum(b"raft-state", "0".repeat(64));
+ assert!(validate_snapshot_archive(&invalid_checksum).is_err());
+ }
+
+ fn snapshot_fixture(state: &[u8]) -> Vec<u8> {
+ snapshot_fixture_with_checksum(state, hex_digest(Sha256::digest(state).as_slice()))
+ }
+
+ fn snapshot_fixture_with_checksum(state: &[u8], state_checksum: String) -> Vec<u8> {
+ let metadata = br#"{"ID":"fixture"}"#;
+ let manifest =
+ format!("{} meta.json\n{} state.bin\n", hex_digest(Sha256::digest(metadata).as_slice()), state_checksum);
+ let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ let mut archive = tar::Builder::new(encoder);
+ for (path, contents) in
+ [("meta.json", metadata.as_slice()), ("state.bin", state), ("SHA256SUMS", manifest.as_bytes())]
+ {
+ let mut header = tar::Header::new_gnu();
+ header.set_mode(0o600);
+ header.set_size(contents.len() as u64);
+ header.set_cksum();
+ archive.append_data(&mut header, path, contents).unwrap();
+ }
+ archive.into_inner().unwrap().finish().unwrap()
+ }
+}
diff --git a/crates/dbx-core/src/consul/response.rs b/crates/dbx-core/src/consul/response.rs
new file mode 100644
index 0000000000..ce26d70ea9
--- /dev/null
+++ b/crates/dbx-core/src/consul/response.rs
@@ -0,0 +1,275 @@
+use reqwest::StatusCode;
+
+use serde::de::DeserializeOwned;
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::KvInt64;
+
+const MAX_ERROR_BYTES: usize = 4096;
+pub(super) const MAX_RESPONSE_BYTES: usize = 48 * 1024 * 1024;
+pub(super) const MAX_COLLECTION_ITEMS: usize = 10_000;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulResponseMetadata {
+ pub index: Option<KvInt64>,
+ pub filtered_by_acls: Option<bool>,
+ pub known_leader: Option<bool>,
+ pub last_contact: Option<KvInt64>,
+ pub query_backend: Option<String>,
+}
+
+impl ConsulResponseMetadata {
+ pub fn from_response(response: &reqwest::Response) -> Self {
+ Self {
+ index: response
+ .headers()
+ .get("X-Consul-Index")
+ .and_then(|value| value.to_str().ok())
+ .map(|value| KvInt64(value.to_string())),
+ filtered_by_acls: response
+ .headers()
+ .get("X-Consul-Results-Filtered-By-ACLs")
+ .and_then(|value| value.to_str().ok())
+ .map(|value| value.eq_ignore_ascii_case("true")),
+ known_leader: header(response, "X-Consul-KnownLeader").map(|value| value.eq_ignore_ascii_case("true")),
+ last_contact: header(response, "X-Consul-LastContact").map(KvInt64),
+ query_backend: header(response, "X-Consul-Query-Backend"),
+ }
+ }
+}
+
+fn header(response: &reqwest::Response, name: &str) -> Option<String> {
+ response.headers().get(name).and_then(|value| value.to_str().ok()).map(str::to_string)
+}
+
+pub(super) async fn ensure_success(
+ response: reqwest::Response,
+ action: &str,
+ token: &str,
+) -> Result<reqwest::Response, String> {
+ if response.status().is_success() {
+ return Ok(response);
+ }
+ let status = response.status();
+ let code = match status {
+ StatusCode::UNAUTHORIZED => "CONSUL_AUTH_REQUIRED",
+ StatusCode::FORBIDDEN => "CONSUL_PERMISSION_DENIED",
+ StatusCode::NOT_FOUND if is_consul_kv_not_found(&response) => "CONSUL_KEY_NOT_FOUND",
+ StatusCode::NOT_FOUND => "CONSUL_REQUEST_FAILED",
+ StatusCode::TOO_MANY_REQUESTS => "CONSUL_RATE_LIMITED",
+ _ if status.is_server_error() => "CONSUL_SERVER_ERROR",
+ _ => "CONSUL_REQUEST_FAILED",
+ };
+ let detail = limited_response_text(response).await;
+ let detail = redact_sensitive(&detail, token);
+ Err(format!("{code}: Failed to {action} ({status}): {}", detail.trim()))
+}
+
+pub(super) async fn decode_json_response<T: DeserializeOwned>(
+ response: reqwest::Response,
+ action: &str,
+) -> Result<T, String> {
+ let body = read_bounded_response(response, action).await?;
+ decode_json_body(&body, action)
+}
+
+pub(super) async fn decode_text_response(response: reqwest::Response, action: &str) -> Result<String, String> {
+ let body = read_bounded_response(response, action).await?;
+ String::from_utf8(body)
+ .map_err(|error| format!("CONSUL_INVALID_RESPONSE: Failed to decode {action} response as UTF-8: {error}"))
+}
+
+pub(super) async fn read_bounded_response(mut response: reqwest::Response, action: &str) -> Result<Vec<u8>, String> {
+ if response.content_length().is_some_and(|length| length > MAX_RESPONSE_BYTES as u64) {
+ return Err(response_size_error(action));
+ }
+ let capacity = response.content_length().unwrap_or(0).min(MAX_RESPONSE_BYTES as u64) as usize;
+ let mut body = Vec::with_capacity(capacity);
+ while let Some(chunk) = response.chunk().await.map_err(|error| {
+ format!("CONSUL_RESPONSE_READ_FAILED: Failed to read {action} response: {}", error.without_url())
+ })? {
+ append_bounded_chunk(&mut body, &chunk, MAX_RESPONSE_BYTES).map_err(|_| response_size_error(action))?;
+ }
+ Ok(body)
+}
+
+pub(super) fn decode_json_body<T: DeserializeOwned>(body: &[u8], action: &str) -> Result<T, String> {
+ let value = serde_json::from_slice::<serde_json::Value>(body)
+ .map_err(|error| format!("CONSUL_INVALID_RESPONSE: Failed to decode {action} response: {error}"))?;
+ validate_collection_limits(&value, action, "$")?;
+ serde_json::from_value(value)
+ .map_err(|error| format!("CONSUL_INVALID_RESPONSE: Failed to decode {action} response: {error}"))
+}
+
+fn response_size_error(action: &str) -> String {
+ format!(
+ "CONSUL_RESPONSE_TOO_LARGE: {action} response body exceeds the {} MiB limit",
+ MAX_RESPONSE_BYTES / 1024 / 1024
+ )
+}
+
+fn append_bounded_chunk(body: &mut Vec<u8>, chunk: &[u8], limit: usize) -> Result<(), ()> {
+ if body.len().saturating_add(chunk.len()) > limit {
+ return Err(());
+ }
+ body.extend_from_slice(chunk);
+ Ok(())
+}
+
+fn validate_collection_limits(value: &serde_json::Value, action: &str, path: &str) -> Result<(), String> {
+ match value {
+ serde_json::Value::Array(items) => {
+ ensure_collection_limit(items.len(), action, path)?;
+ for (index, item) in items.iter().enumerate() {
+ validate_collection_limits(item, action, &format!("{path}[{index}]"))?;
+ }
+ }
+ serde_json::Value::Object(items) => {
+ ensure_collection_limit(items.len(), action, path)?;
+ for (key, item) in items {
+ validate_collection_limits(item, action, &format!("{path}.{}", json_path_key(key)))?;
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+fn ensure_collection_limit(length: usize, action: &str, path: &str) -> Result<(), String> {
+ if length > MAX_COLLECTION_ITEMS {
+ return Err(format!(
+ "CONSUL_RESPONSE_ITEM_LIMIT_EXCEEDED: {action} response collection at {path} contains {length} items; maximum is {MAX_COLLECTION_ITEMS}"
+ ));
+ }
+ Ok(())
+}
+
+fn json_path_key(key: &str) -> String {
+ if key.chars().all(|character| character.is_ascii_alphanumeric() || character == '_') {
+ key.to_string()
+ } else {
+ format!("[{key:?}]")
+ }
+}
+
+pub(crate) fn redact_sensitive(detail: &str, token: &str) -> String {
+ let mut redacted = if token.is_empty() { detail.to_string() } else { detail.replace(token, "[REDACTED]") };
+ for marker in [
+ "SecretID",
+ "Secret_ID",
+ "Secret-ID",
+ "Secret",
+ "JWT",
+ "BootstrapToken",
+ "Bootstrap_Token",
+ "Bootstrap-Token",
+ "PeeringToken",
+ "Peering_Token",
+ "Peering-Token",
+ "X-Consul-Token",
+ "X_Consul_Token",
+ ] {
+ redacted = redact_jsonish_field(&redacted, marker);
+ }
+ redacted
+}
+
+fn redact_jsonish_field(value: &str, marker: &str) -> String {
+ let mut output = String::with_capacity(value.len());
+ let mut rest = value;
+ let marker = marker.to_ascii_lowercase();
+ while let Some(index) = rest.to_ascii_lowercase().find(&marker) {
+ let (before, after_marker) = rest.split_at(index + marker.len());
+ output.push_str(before);
+ let Some(separator) = after_marker.find([':', '=']) else {
+ rest = after_marker;
+ continue;
+ };
+ output.push_str(&after_marker[..=separator]);
+ let after_separator = &after_marker[separator + 1..];
+ let leading = after_separator.len() - after_separator.trim_start().len();
+ output.push_str(&after_separator[..leading]);
+ output.push_str("[REDACTED]");
+ let value_start = &after_separator[leading..];
+ let end = value_start.find([',', '}', '\n', '\r', '&']).unwrap_or(value_start.len());
+ rest = &value_start[end..];
+ }
+ output.push_str(rest);
+ output
+}
+
+pub(super) fn is_consul_kv_not_found(response: &reqwest::Response) -> bool {
+ response.status() == StatusCode::NOT_FOUND && ConsulResponseMetadata::from_response(response).index.is_some()
+}
+
+async fn limited_response_text(mut response: reqwest::Response) -> String {
+ let mut body = Vec::with_capacity(MAX_ERROR_BYTES);
+ while body.len() < MAX_ERROR_BYTES {
+ let Ok(Some(chunk)) = response.chunk().await else {
+ break;
+ };
+ if append_limited_error_chunk(&mut body, &chunk) {
+ break;
+ }
+ }
+ String::from_utf8_lossy(&body).into_owned()
+}
+
+fn append_limited_error_chunk(body: &mut Vec<u8>, chunk: &[u8]) -> bool {
+ let remaining = MAX_ERROR_BYTES.saturating_sub(body.len());
+ body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
+ chunk.len() >= remaining
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn redacts_acl_and_peering_secrets() {
+ let detail = r#"{"SecretID":"acl-secret","peering_token":"peer-secret","bootstrap-token":"bootstrap-secret","nested":{"oidcClientSecret":"oidc-secret"},"message":"bad"}"#;
+ let redacted = redact_sensitive(detail, "connection-token");
+ assert!(!redacted.contains("acl-secret"));
+ assert!(!redacted.contains("peer-secret"));
+ assert!(!redacted.contains("bootstrap-secret"));
+ assert!(!redacted.contains("oidc-secret"));
+ assert!(redacted.contains("[REDACTED]"));
+ }
+
+ #[test]
+ fn limits_error_body_to_four_kibibytes_across_chunks() {
+ let mut body = Vec::new();
+ assert!(!append_limited_error_chunk(&mut body, &[b'a'; 3_000]));
+ assert!(append_limited_error_chunk(&mut body, &[b'b'; 3_000]));
+ assert_eq!(body.len(), MAX_ERROR_BYTES);
+ assert_eq!(&body[..3_000], &[b'a'; 3_000]);
+ assert!(body[3_000..].iter().all(|byte| *byte == b'b'));
+ }
+
+ #[test]
+ fn bounded_chunk_accepts_exact_limit_and_rejects_next_byte() {
+ let mut body = Vec::new();
+ assert_eq!(append_bounded_chunk(&mut body, b"1234", 4), Ok(()));
+ assert_eq!(body, b"1234");
+ assert_eq!(append_bounded_chunk(&mut body, b"5", 4), Err(()));
+ assert_eq!(body, b"1234");
+ }
+
+ #[test]
+ fn json_collection_limit_accepts_boundary() {
+ let body = serde_json::to_vec(&vec![0_u8; MAX_COLLECTION_ITEMS]).unwrap();
+ let decoded = decode_json_body::<Vec<u8>>(&body, "test list").unwrap();
+ assert_eq!(decoded.len(), MAX_COLLECTION_ITEMS);
+ }
+
+ #[test]
+ fn json_collection_limit_reports_path_and_count() {
+ let value = serde_json::json!({ "items": vec![0_u8; MAX_COLLECTION_ITEMS + 1] });
+ let body = serde_json::to_vec(&value).unwrap();
+ let error = decode_json_body::<serde_json::Value>(&body, "test list").unwrap_err();
+ assert!(error.starts_with("CONSUL_RESPONSE_ITEM_LIMIT_EXCEEDED:"));
+ assert!(error.contains("$.items"));
+ assert!(error.contains("10001 items"));
+ }
+}
diff --git a/crates/dbx-core/src/consul/search.rs b/crates/dbx-core/src/consul/search.rs
new file mode 100644
index 0000000000..db20eb11ce
--- /dev/null
+++ b/crates/dbx-core/src/consul/search.rs
@@ -0,0 +1,201 @@
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::KvValueEncoding;
+use crate::connection::AppState;
+
+use super::client::client_for_state;
+use super::kv::{ConsulKvRecord, MAX_RECURSIVE_ENTRIES, MAX_RECURSIVE_VALUE_BYTES};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchRequest {
+ pub request_id: String,
+ pub prefix: String,
+ pub query: String,
+ pub search_keys: bool,
+ pub search_values: bool,
+ pub case_sensitive: bool,
+ pub limit: usize,
+ pub max_scan: usize,
+ #[serde(default)]
+ pub generation: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchMatch {
+ #[serde(flatten)]
+ pub record: ConsulKvRecord,
+ pub matches_key: bool,
+ pub matches_value: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchResponse {
+ pub matches: Vec<ConsulSearchMatch>,
+ pub scanned: usize,
+ pub matched: usize,
+ pub limited: bool,
+ pub filtered_by_acls: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchProgress {
+ pub running: bool,
+ pub scanned: usize,
+ pub cancelled: bool,
+}
+
+#[derive(Default)]
+struct SearchControl {
+ cancelled: AtomicBool,
+ scanned: AtomicUsize,
+}
+
+static SEARCHES: OnceLock<Mutex<HashMap<String, Arc<SearchControl>>>> = OnceLock::new();
+
+struct SearchRegistration {
+ key: String,
+}
+
+impl Drop for SearchRegistration {
+ fn drop(&mut self) {
+ if let Ok(mut searches) = searches().lock() {
+ searches.remove(&self.key);
+ }
+ }
+}
+
+pub async fn consul_search_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulSearchRequest,
+) -> Result<ConsulSearchResponse, String> {
+ let query = request.query.trim();
+ if query.is_empty() {
+ return Err("CONSUL_SEARCH_QUERY_REQUIRED: Search query cannot be empty".to_string());
+ }
+ if !request.search_keys && !request.search_values {
+ return Err("CONSUL_SEARCH_SCOPE_REQUIRED: Enable Key or Value search".to_string());
+ }
+ let request_id = request.request_id.trim();
+ if request_id.is_empty() || request_id.len() > 128 {
+ return Err("CONSUL_SEARCH_REQUEST_INVALID: Search request ID is invalid".to_string());
+ }
+
+ let client = client_for_state(state, connection_id).await?;
+ let scope = client.scope();
+ let key = search_key(connection_id, &scope, request.generation, request_id);
+ let control = Arc::new(SearchControl::default());
+ {
+ let mut registry = searches().lock().map_err(|_| "Consul search registry is unavailable".to_string())?;
+ if registry.contains_key(&key) {
+ return Err(
+ "CONSUL_OPERATION_ALREADY_RUNNING: A search with this request ID is already running".to_string()
+ );
+ }
+ registry.insert(key.clone(), Arc::clone(&control));
+ }
+ let _registration = SearchRegistration { key };
+
+ let max_scan = request.max_scan.clamp(1, MAX_RECURSIVE_ENTRIES);
+ let check = |scanned: usize| {
+ control.scanned.store(scanned, Ordering::Relaxed);
+ if control.cancelled.load(Ordering::Relaxed) {
+ Err("CONSUL_SEARCH_CANCELLED: Consul KV search was cancelled".to_string())
+ } else {
+ Ok(())
+ }
+ };
+ let recursive =
+ client.list_recursive_with_control(&request.prefix, max_scan, MAX_RECURSIVE_VALUE_BYTES, Some(&check)).await?;
+
+ let normalized_query = normalize(query, request.case_sensitive);
+ let limit = request.limit.clamp(1, 1000);
+ let mut matched = 0usize;
+ let mut matches = Vec::new();
+ for (index, record) in recursive.entries.into_iter().enumerate() {
+ check(index + 1)?;
+ let matches_key =
+ request.search_keys && normalize(&record.key, request.case_sensitive).contains(&normalized_query);
+ let matches_value = request.search_values
+ && matches!(record.value.encoding, KvValueEncoding::Utf8)
+ && normalize(&record.value.data, request.case_sensitive).contains(&normalized_query);
+ if matches_key || matches_value {
+ matched += 1;
+ if matches.len() < limit {
+ matches.push(ConsulSearchMatch { record, matches_key, matches_value });
+ }
+ }
+ }
+ Ok(ConsulSearchResponse {
+ matches,
+ scanned: control.scanned.load(Ordering::Relaxed),
+ matched,
+ limited: matched > limit,
+ filtered_by_acls: recursive.filtered_by_acls,
+ })
+}
+
+pub fn consul_search_progress_core(
+ connection_id: &str,
+ scope: &super::ConsulScope,
+ generation: u64,
+ request_id: &str,
+) -> ConsulSearchProgress {
+ let control = searches()
+ .lock()
+ .ok()
+ .and_then(|searches| searches.get(&search_key(connection_id, scope, generation, request_id)).cloned());
+ match control {
+ Some(control) => ConsulSearchProgress {
+ running: true,
+ scanned: control.scanned.load(Ordering::Relaxed),
+ cancelled: control.cancelled.load(Ordering::Relaxed),
+ },
+ None => ConsulSearchProgress { running: false, scanned: 0, cancelled: false },
+ }
+}
+
+pub fn consul_cancel_search_core(
+ connection_id: &str,
+ scope: &super::ConsulScope,
+ generation: u64,
+ request_id: &str,
+) -> bool {
+ let control = searches()
+ .lock()
+ .ok()
+ .and_then(|searches| searches.get(&search_key(connection_id, scope, generation, request_id)).cloned());
+ if let Some(control) = control {
+ control.cancelled.store(true, Ordering::Relaxed);
+ true
+ } else {
+ false
+ }
+}
+
+fn searches() -> &'static Mutex<HashMap<String, Arc<SearchControl>>> {
+ SEARCHES.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn search_key(connection_id: &str, scope: &super::ConsulScope, generation: u64, request_id: &str) -> String {
+ format!(
+ "{connection_id}\0{}\0{}\0{}\0{generation}\0{request_id}",
+ scope.datacenter, scope.partition, scope.namespace
+ )
+}
+
+fn normalize(value: &str, case_sensitive: bool) -> String {
+ if case_sensitive {
+ value.to_string()
+ } else {
+ value.to_lowercase()
+ }
+}
diff --git a/crates/dbx-core/src/consul/session.rs b/crates/dbx-core/src/consul/session.rs
new file mode 100644
index 0000000000..e03f1ac7bd
--- /dev/null
+++ b/crates/dbx-core/src/consul/session.rs
@@ -0,0 +1,479 @@
+use reqwest::Method;
+use serde::{Deserialize, Deserializer, Serialize};
+
+use crate::connection::AppState;
+
+use super::catalog::{encode_segment, ConsulListResponse, ConsulReadOptions};
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::kv::ConsulKvRecord;
+use super::response::{decode_json_response, decode_text_response, ensure_success};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulSession {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub node: String,
+ #[serde(default)]
+ pub lock_delay: u64,
+ #[serde(default)]
+ pub behavior: String,
+ #[serde(default, rename = "TTL", alias = "Ttl")]
+ pub ttl: String,
+ #[serde(default, rename = "NodeChecks", alias = "Checks", deserialize_with = "deserialize_null_default")]
+ pub node_checks: Vec<String>,
+ #[serde(default, deserialize_with = "deserialize_null_default")]
+ pub service_checks: Vec<ConsulSessionServiceCheck>,
+ #[serde(default)]
+ pub namespace: String,
+ #[serde(default)]
+ pub partition: String,
+ #[serde(default)]
+ pub create_index: u64,
+ #[serde(default)]
+ pub modify_index: u64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulSessionServiceCheck {
+ #[serde(default, rename = "ID", alias = "Id")]
+ pub id: String,
+ #[serde(default)]
+ pub namespace: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionCreateRequest {
+ pub name: String,
+ pub node: String,
+ pub lock_delay: Option<String>,
+ pub behavior: String,
+ pub ttl: Option<String>,
+ #[serde(default, alias = "checks")]
+ pub node_checks: Vec<String>,
+ #[serde(default)]
+ pub service_checks: Vec<ConsulSessionServiceCheck>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionHeldKey {
+ pub key: String,
+ pub modify_index: crate::agent_kv::KvInt64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionKeysResponse {
+ pub items: Vec<ConsulKvRecord>,
+ pub complete: bool,
+ pub filtered_by_acls: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionDestroyImpact {
+ pub session: ConsulSession,
+ pub held_keys: Vec<ConsulSessionHeldKey>,
+ pub complete: bool,
+ pub filtered_by_acls: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionDestroyRequest {
+ pub id: String,
+ pub expected_behavior: String,
+ pub expected_held_keys: Vec<ConsulSessionHeldKey>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct SessionCreateResponse {
+ #[serde(rename = "ID", alias = "Id")]
+ id: String,
+}
+
+impl ConsulClient {
+ pub async fn sessions(
+ &self,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulSession>>, String> {
+ self.read_list("/v1/session/list", options, "list Consul sessions").await
+ }
+
+ pub async fn node_sessions(
+ &self,
+ node: &str,
+ options: &ConsulReadOptions,
+ ) -> Result<ConsulListResponse<Vec<ConsulSession>>, String> {
+ self.read_list(
+ &format!("/v1/session/node/{}", encode_segment(required(node, "node")?)),
+ options,
+ "list Consul node sessions",
+ )
+ .await
+ }
+
+ pub async fn session(&self, id: &str) -> Result<Option<ConsulSession>, String> {
+ let mut url = self.api_url(&format!("/v1/session/info/{}", encode_segment(required(id, "session id")?)))?;
+ self.append_scope(&mut url, true);
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read Consul session", self.token()).await?;
+ let mut items = decode_json_response::<Vec<ConsulSession>>(response, "read Consul session").await?;
+ Ok(items.pop())
+ }
+
+ pub(super) async fn create_session(&self, request: ConsulSessionCreateRequest) -> Result<ConsulSession, String> {
+ let behavior = request.behavior.trim().to_ascii_lowercase();
+ if !matches!(behavior.as_str(), "release" | "delete") {
+ return Err("CONSUL_INVALID_REQUEST: Session behavior must be release or delete".to_string());
+ }
+ let ttl = validate_session_ttl(request.ttl.as_deref())?;
+ let lock_delay = validate_lock_delay(request.lock_delay.as_deref())?;
+ let mut url = self.api_url("/v1/session/create")?;
+ self.append_scope(&mut url, false);
+ let body = serde_json::to_vec(&serde_json::json!({
+ "Name": request.name,
+ "Node": request.node,
+ "LockDelay": lock_delay,
+ "Behavior": behavior,
+ "TTL": ttl,
+ "NodeChecks": request.node_checks,
+ "ServiceChecks": request.service_checks,
+ }))
+ .map_err(|error| format!("Failed to encode Consul session: {error}"))?;
+ let response =
+ ensure_success(self.send(Method::PUT, url, Some(body)).await?, "create Consul session", self.token())
+ .await?;
+ let created = decode_json_response::<SessionCreateResponse>(response, "create Consul session").await?;
+ self.session(&created.id)
+ .await?
+ .ok_or_else(|| "CONSUL_SESSION_NOT_FOUND: Created session was not returned by Consul".to_string())
+ }
+
+ pub(super) async fn renew_session(&self, id: &str) -> Result<ConsulSession, String> {
+ let mut url = self.api_url(&format!("/v1/session/renew/{}", encode_segment(required(id, "session id")?)))?;
+ self.append_scope(&mut url, false);
+ let response =
+ ensure_success(self.send(Method::PUT, url, None).await?, "renew Consul session", self.token()).await?;
+ let mut items = decode_json_response::<Vec<ConsulSession>>(response, "renew Consul session").await?;
+ items.pop().ok_or_else(|| "CONSUL_SESSION_NOT_FOUND: Session no longer exists".to_string())
+ }
+
+ pub(super) async fn destroy_session(&self, id: &str) -> Result<bool, String> {
+ let mut url = self.api_url(&format!("/v1/session/destroy/{}", encode_segment(required(id, "session id")?)))?;
+ self.append_scope(&mut url, false);
+ let response =
+ ensure_success(self.send(Method::PUT, url, None).await?, "destroy Consul session", self.token()).await?;
+ let result = decode_text_response(response, "destroy Consul session").await?;
+ if result.trim() != "true" {
+ return Err("CONSUL_SESSION_CONFLICT: Consul refused to destroy the session".to_string());
+ }
+ Ok(true)
+ }
+
+ pub async fn session_keys(&self, id: &str) -> Result<ConsulSessionKeysResponse, String> {
+ let id = required(id, "session id")?;
+ let response = self.list_recursive("", 10_000, 32 * 1024 * 1024).await?;
+ let filtered_by_acls = response.filtered_by_acls == Some(true);
+ Ok(ConsulSessionKeysResponse {
+ items: response.entries.into_iter().filter(|entry| entry.session.as_deref() == Some(id)).collect(),
+ complete: response.complete && !filtered_by_acls,
+ filtered_by_acls,
+ })
+ }
+
+ async fn session_destroy_impact(&self, id: &str) -> Result<ConsulSessionDestroyImpact, String> {
+ let session =
+ self.session(id).await?.ok_or_else(|| "CONSUL_SESSION_NOT_FOUND: Session no longer exists".to_string())?;
+ let recursive = self.list_recursive("", 10_000, 32 * 1024 * 1024).await?;
+ let mut held_keys = recursive
+ .entries
+ .into_iter()
+ .filter(|entry| entry.session.as_deref() == Some(session.id.as_str()))
+ .map(|entry| ConsulSessionHeldKey { key: entry.key, modify_index: entry.modify_index })
+ .collect::<Vec<_>>();
+ held_keys.sort_by(|left, right| left.key.cmp(&right.key));
+ let filtered_by_acls = recursive.filtered_by_acls == Some(true);
+ Ok(ConsulSessionDestroyImpact {
+ session,
+ held_keys,
+ complete: recursive.complete && !filtered_by_acls,
+ filtered_by_acls,
+ })
+ }
+}
+
+fn required<'a>(value: &'a str, field: &str) -> Result<&'a str, String> {
+ let value = value.trim();
+ if value.is_empty() {
+ Err(format!("CONSUL_INVALID_REQUEST: {field} is required"))
+ } else {
+ Ok(value)
+ }
+}
+
+fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
+where
+ D: Deserializer<'de>,
+ T: Deserialize<'de> + Default,
+{
+ Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
+}
+
+fn validate_session_ttl(value: Option<&str>) -> Result<Option<String>, String> {
+ let Some(value) = normalized_duration(value) else { return Ok(None) };
+ let milliseconds = parse_consul_duration_ms(&value, "Session TTL")?;
+ if !(10_000.0..=86_400_000.0).contains(&milliseconds) {
+ return Err("CONSUL_INVALID_REQUEST: Session TTL must be between 10s and 24h".to_string());
+ }
+ Ok(Some(value))
+}
+
+fn validate_lock_delay(value: Option<&str>) -> Result<Option<String>, String> {
+ let Some(value) = normalized_duration(value) else { return Ok(None) };
+ let milliseconds = parse_consul_duration_ms(&value, "Session LockDelay")?;
+ if !(0.0..=60_000.0).contains(&milliseconds) {
+ return Err("CONSUL_INVALID_REQUEST: Session LockDelay must be between 0s and 60s".to_string());
+ }
+ Ok(Some(value))
+}
+
+fn normalized_duration(value: Option<&str>) -> Option<String> {
+ value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string)
+}
+
+fn parse_consul_duration_ms(value: &str, field: &str) -> Result<f64, String> {
+ let bytes = value.as_bytes();
+ let mut offset = 0;
+ let mut total = 0.0;
+ while offset < bytes.len() {
+ let start = offset;
+ let mut dots = 0;
+ while offset < bytes.len() && (bytes[offset].is_ascii_digit() || bytes[offset] == b'.') {
+ if bytes[offset] == b'.' {
+ dots += 1;
+ }
+ offset += 1;
+ }
+ if offset == start || dots > 1 {
+ return Err(format!("CONSUL_INVALID_REQUEST: {field} must use duration units ms, s, m, or h"));
+ }
+ let amount = value[start..offset]
+ .parse::<f64>()
+ .map_err(|_| format!("CONSUL_INVALID_REQUEST: {field} is not a valid duration"))?;
+ let multiplier = if value[offset..].starts_with("ms") {
+ offset += 2;
+ 1.0
+ } else if offset < bytes.len() {
+ let multiplier = match bytes[offset] {
+ b's' => 1_000.0,
+ b'm' => 60_000.0,
+ b'h' => 3_600_000.0,
+ _ => return Err(format!("CONSUL_INVALID_REQUEST: {field} must use duration units ms, s, m, or h")),
+ };
+ offset += 1;
+ multiplier
+ } else {
+ return Err(format!("CONSUL_INVALID_REQUEST: {field} must include a duration unit"));
+ };
+ total += amount * multiplier;
+ }
+ if !total.is_finite() {
+ return Err(format!("CONSUL_INVALID_REQUEST: {field} is not a valid duration"));
+ }
+ Ok(total)
+}
+
+pub async fn consul_sessions_core(
+ state: &AppState,
+ connection_id: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulSession>>, String> {
+ client_for_state(state, connection_id).await?.sessions(&options).await
+}
+
+pub async fn consul_node_sessions_core(
+ state: &AppState,
+ connection_id: &str,
+ node: &str,
+ options: ConsulReadOptions,
+) -> Result<ConsulListResponse<Vec<ConsulSession>>, String> {
+ client_for_state(state, connection_id).await?.node_sessions(node, &options).await
+}
+
+pub async fn consul_session_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<Option<ConsulSession>, String> {
+ client_for_state(state, connection_id).await?.session(id).await
+}
+
+pub async fn consul_session_keys_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulSessionKeysResponse, String> {
+ client_for_state(state, connection_id).await?.session_keys(id).await
+}
+
+pub async fn consul_session_destroy_impact_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulSessionDestroyImpact, String> {
+ client_for_state(state, connection_id).await?.session_destroy_impact(id).await
+}
+
+pub async fn consul_create_session_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulSessionCreateRequest,
+) -> Result<ConsulSession, String> {
+ ensure_writable_core(state, connection_id, "create Consul session").await?;
+ client_for_state(state, connection_id).await?.create_session(request).await
+}
+
+pub async fn consul_renew_session_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulSession, String> {
+ ensure_writable_core(state, connection_id, "renew Consul session").await?;
+ client_for_state(state, connection_id).await?.renew_session(id).await
+}
+
+pub async fn consul_destroy_session_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulSessionDestroyRequest,
+) -> Result<bool, String> {
+ ensure_writable_core(state, connection_id, "destroy Consul session").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let impact = client.session_destroy_impact(&request.id).await?;
+ if !impact.complete {
+ return Err("CONSUL_IMPACT_INCOMPLETE: Session-held keys could not be enumerated completely".to_string());
+ }
+ validate_destroy_confirmation(&impact, &request)?;
+ client.destroy_session(&request.id).await
+}
+
+fn validate_destroy_confirmation(
+ impact: &ConsulSessionDestroyImpact,
+ request: &ConsulSessionDestroyRequest,
+) -> Result<(), String> {
+ let mut expected_keys = request.expected_held_keys.clone();
+ expected_keys.sort_by(|left, right| left.key.cmp(&right.key));
+ if impact.session.id != request.id
+ || impact.session.behavior != request.expected_behavior
+ || impact.held_keys != expected_keys
+ {
+ return Err("CONSUL_SESSION_CONFLICT: Session behavior or held keys changed after confirmation".to_string());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::consul::test_support::{serve_once, test_client};
+
+ #[test]
+ fn decodes_consul_two_session_checks_and_indexes() {
+ let session: ConsulSession = serde_json::from_str(
+ r#"{
+ "ID":"session-1",
+ "Name":"demo",
+ "Node":"node-1",
+ "LockDelay":15000000000,
+ "Behavior":"release",
+ "TTL":"",
+ "NodeChecks":["serfHealth"],
+ "ServiceChecks":[{"ID":"service:api:health","Namespace":"team-a"}],
+ "CreateIndex":12,
+ "ModifyIndex":18
+ }"#,
+ )
+ .unwrap();
+
+ assert_eq!(session.id, "session-1");
+ assert_eq!(session.node_checks, vec!["serfHealth"]);
+ assert_eq!(session.service_checks[0].id, "service:api:health");
+ assert_eq!(session.service_checks[0].namespace, "team-a");
+ assert_eq!(session.modify_index, 18);
+
+ let local_dev: ConsulSession =
+ serde_json::from_str(r#"{"ID":"session-2","NodeChecks":["serfHealth"],"ServiceChecks":null}"#).unwrap();
+ assert!(local_dev.service_checks.is_empty());
+ }
+
+ #[test]
+ fn accepts_legacy_checks_as_node_checks() {
+ let session: ConsulSession = serde_json::from_str(r#"{"ID":"legacy","Checks":["serfHealth"]}"#).unwrap();
+ assert_eq!(session.node_checks, vec!["serfHealth"]);
+ }
+
+ #[test]
+ fn validates_session_duration_boundaries() {
+ assert_eq!(validate_session_ttl(None).unwrap(), None);
+ assert_eq!(validate_session_ttl(Some("10s")).unwrap(), Some("10s".into()));
+ assert_eq!(validate_session_ttl(Some("24h")).unwrap(), Some("24h".into()));
+ assert!(validate_session_ttl(Some("9.999s")).is_err());
+ assert!(validate_session_ttl(Some("24h1s")).is_err());
+ assert_eq!(validate_lock_delay(Some("0s")).unwrap(), Some("0s".into()));
+ assert_eq!(validate_lock_delay(Some("1m")).unwrap(), Some("1m".into()));
+ assert!(validate_lock_delay(Some("60s1ms")).is_err());
+ }
+
+ #[tokio::test]
+ async fn renew_uses_put_encoded_id_scope_and_acl_header() {
+ let body = r#"[{"ID":"session/a","TTL":"30s","Behavior":"release"}]"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let (url, request_rx) = serve_once(response).await;
+ let client = test_client(url).await;
+ let renewed = client.renew_session("session/a").await.unwrap();
+
+ assert_eq!(renewed.id, "session/a");
+ assert_eq!(renewed.ttl, "30s");
+ let request = request_rx.await.unwrap();
+ let headers = request.split_once("\r\n\r\n").unwrap().0;
+ assert!(headers
+ .starts_with("PUT /proxy/v1/session/renew/session%2Fa?dc=dc1&ns=team-a&partition=partition-a HTTP/1.1"));
+ assert!(headers.to_ascii_lowercase().contains("x-consul-token: fixture-token"));
+ }
+
+ #[test]
+ fn destroy_confirmation_rejects_changed_held_keys() {
+ let impact = ConsulSessionDestroyImpact {
+ session: ConsulSession { id: "session-1".into(), behavior: "delete".into(), ..Default::default() },
+ held_keys: vec![ConsulSessionHeldKey {
+ key: "locks/a".into(),
+ modify_index: crate::agent_kv::KvInt64("4".into()),
+ }],
+ complete: true,
+ filtered_by_acls: false,
+ };
+ let stale = ConsulSessionDestroyRequest {
+ id: "session-1".into(),
+ expected_behavior: "delete".into(),
+ expected_held_keys: Vec::new(),
+ };
+ assert!(validate_destroy_confirmation(&impact, &stale).is_err());
+ let current = ConsulSessionDestroyRequest {
+ id: "session-1".into(),
+ expected_behavior: "delete".into(),
+ expected_held_keys: impact.held_keys.clone(),
+ };
+ assert!(validate_destroy_confirmation(&impact, &current).is_ok());
+ }
+}
diff --git a/crates/dbx-core/src/consul/status.rs b/crates/dbx-core/src/consul/status.rs
new file mode 100644
index 0000000000..a971fdb48e
--- /dev/null
+++ b/crates/dbx-core/src/consul/status.rs
@@ -0,0 +1,38 @@
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ConsulClient};
+use super::response::{decode_json_response, ensure_success};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulStatus {
+ pub leader: String,
+ pub peers: Vec<String>,
+}
+
+impl ConsulClient {
+ pub async fn status_leader(&self) -> Result<String, String> {
+ let url = self.api_url("/v1/status/leader")?;
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read Consul leader", self.token()).await?;
+ decode_json_response(response, "read Consul leader").await
+ }
+
+ pub async fn status_peers(&self) -> Result<Vec<String>, String> {
+ let url = self.api_url("/v1/status/peers")?;
+ let response =
+ ensure_success(self.send(Method::GET, url, None).await?, "read Consul peers", self.token()).await?;
+ decode_json_response(response, "read Consul peers").await
+ }
+}
+
+pub async fn consul_status_leader_core(state: &AppState, connection_id: &str) -> Result<String, String> {
+ client_for_state(state, connection_id).await?.status_leader().await
+}
+
+pub async fn consul_status_peers_core(state: &AppState, connection_id: &str) -> Result<Vec<String>, String> {
+ client_for_state(state, connection_id).await?.status_peers().await
+}
diff --git a/crates/dbx-core/src/consul/test_support.rs b/crates/dbx-core/src/consul/test_support.rs
new file mode 100644
index 0000000000..ba548d39cf
--- /dev/null
+++ b/crates/dbx-core/src/consul/test_support.rs
@@ -0,0 +1,72 @@
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+use tokio::sync::oneshot;
+
+use super::{ConsulClient, ConsulConfig, ConsulConsistency};
+
+pub(super) async fn serve_once(response: String) -> (reqwest::Url, oneshot::Receiver<String>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let (request_tx, request_rx) = oneshot::channel();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 4096];
+ loop {
+ let count = socket.read(&mut buffer).await.unwrap();
+ if count == 0 {
+ break;
+ }
+ request.extend_from_slice(&buffer[..count]);
+ let Some(header_end) = find_bytes(&request, b"\r\n\r\n") else {
+ assert!(request.len() <= 1024 * 1024);
+ continue;
+ };
+ let headers = String::from_utf8_lossy(&request[..header_end]);
+ let content_length = headers
+ .lines()
+ .find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse::<usize>().ok()).flatten()
+ })
+ .unwrap_or(0);
+ if request.len() >= header_end + 4 + content_length {
+ break;
+ }
+ }
+ let _ = request_tx.send(String::from_utf8(request).unwrap());
+ socket.write_all(response.as_bytes()).await.unwrap();
+ socket.shutdown().await.unwrap();
+ });
+ (reqwest::Url::parse(&format!("http://{address}/proxy")).unwrap(), request_rx)
+}
+
+pub(super) async fn test_client(base_url: reqwest::Url) -> ConsulClient {
+ ConsulClient::new(ConsulConfig {
+ base_url,
+ token: "fixture-token".to_string(),
+ datacenter: "dc1".to_string(),
+ namespace: "team-a".to_string(),
+ partition: "partition-a".to_string(),
+ consistency: ConsulConsistency::Consistent,
+ tls_skip_verify: false,
+ ca_cert_path: String::new(),
+ client_cert_path: String::new(),
+ client_key_path: String::new(),
+ connect_timeout_secs: 5,
+ request_timeout_secs: 5,
+ connect_override: None,
+ operator_snapshot_restore_enabled: false,
+ operator_autopilot_write_enabled: false,
+ operator_raft_write_enabled: false,
+ operator_keyring_write_enabled: false,
+ operator_license_write_enabled: false,
+ agent_target: None,
+ })
+ .await
+ .unwrap()
+}
+
+fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ haystack.windows(needle.len()).position(|window| window == needle)
+}
diff --git a/crates/dbx-core/src/consul/tools.rs b/crates/dbx-core/src/consul/tools.rs
new file mode 100644
index 0000000000..1d683f5627
--- /dev/null
+++ b/crates/dbx-core/src/consul/tools.rs
@@ -0,0 +1,560 @@
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
+use reqwest::Method;
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::KvInt64;
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+
+const MAX_EVENT_PAYLOAD_BYTES: usize = 100;
+const MAX_EVENT_NAME_BYTES: usize = 256;
+const MAX_EVENT_FILTER_BYTES: usize = 1_024;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedQueryService {
+ pub service: String,
+ #[serde(default)]
+ pub near: String,
+ #[serde(default)]
+ pub only_passing: bool,
+ #[serde(default, deserialize_with = "deserialize_null_default")]
+ pub tags: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedQuery {
+ #[serde(rename = "ID", alias = "Id", default)]
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub session: String,
+ pub service: ConsulPreparedQueryService,
+ #[serde(default = "zero_index")]
+ pub create_index: KvInt64,
+ #[serde(default = "zero_index")]
+ pub modify_index: KvInt64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulPreparedQueryInput {
+ pub name: String,
+ pub session: String,
+ pub service: ConsulPreparedQueryService,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "PascalCase")]
+struct ConsulPreparedQueryWrite<'a> {
+ name: &'a str,
+ session: &'a str,
+ service: &'a ConsulPreparedQueryService,
+}
+
+impl ConsulPreparedQueryInput {
+ fn wire(&self) -> ConsulPreparedQueryWrite<'_> {
+ ConsulPreparedQueryWrite { name: &self.name, session: &self.session, service: &self.service }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulPreparedQueryExecuteRequest {
+ pub query: String,
+ pub limit: usize,
+ pub connect: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedQueryNode {
+ pub node: ConsulPreparedNodeIdentity,
+ pub service: ConsulPreparedServiceIdentity,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedNodeIdentity {
+ pub node: String,
+ pub address: String,
+ #[serde(default)]
+ pub datacenter: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedServiceIdentity {
+ #[serde(rename = "ID", alias = "Id")]
+ pub id: String,
+ pub service: String,
+ #[serde(default)]
+ pub address: String,
+ pub port: u16,
+ #[serde(default, deserialize_with = "deserialize_null_default")]
+ pub tags: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedQueryExecuteResponse {
+ #[serde(default)]
+ pub service: String,
+ #[serde(default)]
+ pub nodes: Vec<ConsulPreparedQueryNode>,
+ #[serde(rename = "DNS", alias = "Dns", default)]
+ pub dns: ConsulPreparedQueryDns,
+ #[serde(default)]
+ pub datacenter: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulPreparedQueryDns {
+ #[serde(rename = "TTL", alias = "Ttl", default)]
+ pub ttl: String,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct ConsulPreparedQueryExplainResponse {
+ query: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulEventFireRequest {
+ pub name: String,
+ pub payload_base64: String,
+ pub node_filter: String,
+ pub service_filter: String,
+ pub tag_filter: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulEvent {
+ #[serde(rename = "ID", alias = "Id")]
+ pub id: String,
+ pub name: String,
+ #[serde(default)]
+ pub payload: Option<String>,
+ #[serde(default)]
+ pub node_filter: String,
+ #[serde(default)]
+ pub service_filter: String,
+ #[serde(default)]
+ pub tag_filter: String,
+ #[serde(default = "zero_index")]
+ pub l_time: KvInt64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulCoordinate {
+ pub node: String,
+ #[serde(default)]
+ pub segment: String,
+ pub coord: ConsulCoordinateValue,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct ConsulCoordinateValue {
+ #[serde(default)]
+ pub vec: Vec<f64>,
+ pub error: f64,
+ pub adjustment: f64,
+ pub height: f64,
+}
+
+impl ConsulClient {
+ async fn prepared_queries(&self) -> Result<Vec<ConsulPreparedQuery>, String> {
+ let url = self.api_url("/v1/query")?;
+ self.request_json(Method::GET, url, None::<&()>, true, "list prepared queries").await
+ }
+}
+
+pub async fn consul_prepared_query_list_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<Vec<ConsulPreparedQuery>, String> {
+ client_for_state(state, connection_id).await?.prepared_queries().await
+}
+
+pub async fn consul_prepared_query_read_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+) -> Result<ConsulPreparedQuery, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/query/{}", encode(id)))?;
+ client
+ .request_json::<Vec<ConsulPreparedQuery>, _>(Method::GET, url, None::<&()>, true, "read prepared query")
+ .await?
+ .into_iter()
+ .next()
+ .ok_or_else(|| "CONSUL_QUERY_NOT_FOUND: Prepared query not found".to_string())
+}
+
+pub async fn consul_prepared_query_create_core(
+ state: &AppState,
+ connection_id: &str,
+ input: ConsulPreparedQueryInput,
+) -> Result<String, String> {
+ ensure_writable_core(state, connection_id, "create Consul prepared query").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/query")?;
+ #[derive(Deserialize)]
+ struct Created {
+ #[serde(rename = "ID")]
+ id: String,
+ }
+ Ok(client
+ .request_json::<Created, _>(Method::POST, url, Some(&input.wire()), false, "create prepared query")
+ .await?
+ .id)
+}
+
+pub async fn consul_prepared_query_update_core(
+ state: &AppState,
+ connection_id: &str,
+ id: &str,
+ input: ConsulPreparedQueryInput,
+) -> Result<(), String> {
+ ensure_writable_core(state, connection_id, "update Consul prepared query").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let read_url = client.api_url(&format!("/v1/query/{}", encode(id)))?;
+ let mut existing = client
+ .request_json::<Vec<serde_json::Value>, _>(
+ Method::GET,
+ read_url,
+ None::<&()>,
+ true,
+ "read prepared query before update",
+ )
+ .await?
+ .into_iter()
+ .next()
+ .ok_or_else(|| "CONSUL_QUERY_NOT_FOUND: Prepared query not found".to_string())?;
+ apply_prepared_query_patch(&mut existing, &input)?;
+ let url = client.api_url(&format!("/v1/query/{}", encode(id)))?;
+ client.send_json(Method::PUT, url, Some(&existing), false, "update prepared query").await.map(|_| ())
+}
+
+fn apply_prepared_query_patch(
+ existing: &mut serde_json::Value,
+ input: &ConsulPreparedQueryInput,
+) -> Result<(), String> {
+ if input.name.trim().is_empty() || input.service.service.trim().is_empty() {
+ return Err("CONSUL_INVALID_REQUEST: Prepared query name and service are required".to_string());
+ }
+ let object = existing
+ .as_object_mut()
+ .ok_or_else(|| "CONSUL_INVALID_RESPONSE: Prepared query is not an object".to_string())?;
+ object.remove("ID");
+ object.remove("CreateIndex");
+ object.remove("ModifyIndex");
+ object.insert("Name".to_string(), serde_json::Value::String(input.name.trim().to_string()));
+ let service = object
+ .entry("Service")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .ok_or_else(|| "CONSUL_INVALID_RESPONSE: Prepared query Service is not an object".to_string())?;
+ service.insert("Service".to_string(), serde_json::Value::String(input.service.service.trim().to_string()));
+ Ok(())
+}
+
+pub async fn consul_prepared_query_delete_core(state: &AppState, connection_id: &str, id: &str) -> Result<(), String> {
+ ensure_writable_core(state, connection_id, "delete Consul prepared query").await?;
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/query/{}", encode(id)))?;
+ client.send_json(Method::DELETE, url, None::<&()>, false, "delete prepared query").await.map(|_| ())
+}
+
+pub async fn consul_prepared_query_execute_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulPreparedQueryExecuteRequest,
+) -> Result<ConsulPreparedQueryExecuteResponse, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url(&format!("/v1/query/{}/execute", encode(&request.query)))?;
+ url.query_pairs_mut()
+ .append_pair("limit", &request.limit.clamp(1, 1000).to_string())
+ .append_pair("connect", if request.connect { "true" } else { "false" });
+ client.request_json(Method::GET, url, None::<&()>, true, "execute prepared query").await
+}
+
+pub async fn consul_prepared_query_explain_core(
+ state: &AppState,
+ connection_id: &str,
+ query: &str,
+) -> Result<serde_json::Value, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url(&format!("/v1/query/{}/explain", encode(query)))?;
+ let response: ConsulPreparedQueryExplainResponse =
+ client.request_json(Method::GET, url, None::<&()>, true, "explain prepared query").await?;
+ let mut query = response.query;
+ redact_prepared_query_secrets(&mut query);
+ Ok(query)
+}
+
+fn redact_prepared_query_secrets(value: &mut serde_json::Value) {
+ match value {
+ serde_json::Value::Object(object) => {
+ for (key, value) in object {
+ if key.eq_ignore_ascii_case("token") {
+ *value = serde_json::Value::String("****************".to_string());
+ } else {
+ redact_prepared_query_secrets(value);
+ }
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for value in values {
+ redact_prepared_query_secrets(value);
+ }
+ }
+ _ => {}
+ }
+}
+
+pub async fn consul_event_list_core(
+ state: &AppState,
+ connection_id: &str,
+ name: Option<&str>,
+) -> Result<Vec<ConsulEvent>, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url("/v1/event/list")?;
+ if let Some(name) = name.filter(|name| !name.is_empty()) {
+ url.query_pairs_mut().append_pair("name", name);
+ }
+ client.request_json(Method::GET, url, None::<&()>, true, "list Consul events").await
+}
+
+pub async fn consul_event_fire_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulEventFireRequest,
+) -> Result<ConsulEvent, String> {
+ ensure_writable_core(state, connection_id, "fire Consul event").await?;
+ validate_event_text(&request.name, "name", MAX_EVENT_NAME_BYTES)?;
+ if request.name.starts_with('_') {
+ return Err("CONSUL_EVENT_NAME_RESERVED: Event names beginning with '_' are reserved by Consul".to_string());
+ }
+ for (name, value) in [
+ ("node filter", request.node_filter.as_str()),
+ ("service filter", request.service_filter.as_str()),
+ ("tag filter", request.tag_filter.as_str()),
+ ] {
+ if value.len() > MAX_EVENT_FILTER_BYTES {
+ return Err(format!("CONSUL_EVENT_FILTER_TOO_LARGE: {name} exceeds {MAX_EVENT_FILTER_BYTES} bytes"));
+ }
+ }
+ let encoded_payload = request.payload_base64.trim();
+ let max_encoded_len = MAX_EVENT_PAYLOAD_BYTES.div_ceil(3) * 4;
+ if encoded_payload.len() > max_encoded_len {
+ return Err(format!("CONSUL_EVENT_PAYLOAD_TOO_LARGE: Event payload exceeds {MAX_EVENT_PAYLOAD_BYTES} bytes"));
+ }
+ let payload = STANDARD.decode(encoded_payload).map_err(|error| format!("CONSUL_EVENT_PAYLOAD_INVALID: {error}"))?;
+ if payload.len() > MAX_EVENT_PAYLOAD_BYTES {
+ return Err(format!("CONSUL_EVENT_PAYLOAD_TOO_LARGE: Event payload exceeds {MAX_EVENT_PAYLOAD_BYTES} bytes"));
+ }
+ let client = client_for_state(state, connection_id).await?;
+ let mut url = client.api_url(&format!("/v1/event/fire/{}", encode(&request.name)))?;
+ {
+ let mut query = url.query_pairs_mut();
+ if !request.node_filter.is_empty() {
+ query.append_pair("node", &request.node_filter);
+ }
+ if !request.service_filter.is_empty() {
+ query.append_pair("service", &request.service_filter);
+ }
+ if !request.tag_filter.is_empty() {
+ query.append_pair("tag", &request.tag_filter);
+ }
+ }
+ client.append_scope(&mut url, false);
+ let response = client.send(Method::PUT, url, Some(payload)).await?;
+ let response = super::response::ensure_success(response, "fire Consul event", client.token()).await?;
+ super::response::decode_json_response(response, "fire Consul event").await
+}
+
+fn validate_event_text(value: &str, field: &str, max_bytes: usize) -> Result<(), String> {
+ if value.trim().is_empty() {
+ return Err(format!("CONSUL_INVALID_REQUEST: Event {field} is required"));
+ }
+ if value.len() > max_bytes {
+ return Err(format!("CONSUL_EVENT_INPUT_TOO_LARGE: Event {field} exceeds {max_bytes} bytes"));
+ }
+ Ok(())
+}
+
+pub async fn consul_coordinate_nodes_core(
+ state: &AppState,
+ connection_id: &str,
+) -> Result<Vec<ConsulCoordinate>, String> {
+ let client = client_for_state(state, connection_id).await?;
+ let url = client.api_url("/v1/coordinate/nodes")?;
+ client.request_json(Method::GET, url, None::<&()>, true, "list network coordinates").await
+}
+
+fn encode(value: &str) -> String {
+ utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
+}
+
+fn zero_index() -> KvInt64 {
+ KvInt64("0".to_string())
+}
+
+fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
+where
+ D: serde::Deserializer<'de>,
+ T: Deserialize<'de> + Default,
+{
+ Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn prepared_query_transport_input_maps_to_pascal_case_wire_body() {
+ let input = ConsulPreparedQueryInput {
+ name: "payments".into(),
+ session: "session-1".into(),
+ service: ConsulPreparedQueryService { service: "api".into(), ..Default::default() },
+ };
+ let value = serde_json::to_value(input.wire()).unwrap();
+ assert_eq!(value["Name"], "payments");
+ assert_eq!(value["Session"], "session-1");
+ assert_eq!(value["Service"]["Service"], "api");
+ assert!(value.get("name").is_none());
+ }
+
+ #[test]
+ fn prepared_query_update_preserves_advanced_and_sensitive_fields() {
+ let mut existing = serde_json::json!({
+ "ID": "query-1",
+ "Name": "old",
+ "Token": "keep-secret",
+ "Service": { "Service": "old-api", "Near": "_agent", "Tags": ["v1"], "Failover": { "Datacenters": ["dc2"] } },
+ "DNS": { "TTL": "5s" },
+ "CreateIndex": 10,
+ "ModifyIndex": 11
+ });
+ let input = ConsulPreparedQueryInput {
+ name: "new".into(),
+ session: String::new(),
+ service: ConsulPreparedQueryService { service: "new-api".into(), ..Default::default() },
+ };
+ apply_prepared_query_patch(&mut existing, &input).unwrap();
+ assert_eq!(existing["Name"], "new");
+ assert_eq!(existing["Service"]["Service"], "new-api");
+ assert_eq!(existing["Service"]["Near"], "_agent");
+ assert_eq!(existing["Token"], "keep-secret");
+ assert_eq!(existing["DNS"]["TTL"], "5s");
+ assert!(existing.get("ID").is_none());
+ assert!(existing.get("ModifyIndex").is_none());
+ }
+
+ #[test]
+ fn event_validation_rejects_reserved_names_and_oversized_encoded_payloads() {
+ assert!(validate_event_text("", "name", MAX_EVENT_NAME_BYTES).is_err());
+ assert!("_internal".starts_with('_'));
+ let oversized = vec![0_u8; MAX_EVENT_PAYLOAD_BYTES + 3];
+ assert!(STANDARD.encode(oversized).len() > MAX_EVENT_PAYLOAD_BYTES.div_ceil(3) * 4);
+ }
+
+ #[test]
+ fn official_event_response_uses_id_acronym() {
+ let event: ConsulEvent = serde_json::from_value(serde_json::json!({
+ "ID": "7f12d2f4-2cb8-4795-9e5f-f8e35e9912aa",
+ "Name": "deploy",
+ "Payload": "cmVsZWFzZS0x",
+ "NodeFilter": "",
+ "ServiceFilter": "api",
+ "TagFilter": "v1",
+ "Version": 1,
+ "LTime": 42
+ }))
+ .unwrap();
+ assert_eq!(event.id, "7f12d2f4-2cb8-4795-9e5f-f8e35e9912aa");
+ assert_eq!(event.l_time, KvInt64("42".into()));
+ let encoded = serde_json::to_value(event).unwrap();
+ assert_eq!(encoded["ID"], "7f12d2f4-2cb8-4795-9e5f-f8e35e9912aa");
+ assert!(encoded.get("Id").is_none());
+ }
+
+ #[test]
+ fn official_prepared_query_response_preserves_protocol_acronyms() {
+ let query: ConsulPreparedQuery = serde_json::from_value(serde_json::json!({
+ "ID": "query-1",
+ "Name": "payments",
+ "Session": "",
+ "Service": { "Service": "api", "Near": "", "OnlyPassing": true, "Tags": ["v1"] },
+ "CreateIndex": 10,
+ "ModifyIndex": 11
+ }))
+ .unwrap();
+ assert_eq!(query.id, "query-1");
+ let encoded = serde_json::to_value(query).unwrap();
+ assert_eq!(encoded["ID"], "query-1");
+ assert!(encoded.get("Id").is_none());
+ }
+
+ #[test]
+ fn official_prepared_query_execute_response_preserves_dns_ttl_and_service_id() {
+ let response: ConsulPreparedQueryExecuteResponse = serde_json::from_value(serde_json::json!({
+ "Service": "api",
+ "Nodes": [{
+ "Node": { "Node": "node-1", "Address": "10.0.0.1", "Datacenter": "dc1" },
+ "Service": { "ID": "api-1", "Service": "api", "Port": 8080, "Tags": null }
+ }],
+ "DNS": { "TTL": "5s" },
+ "Datacenter": "dc1"
+ }))
+ .unwrap();
+ assert_eq!(response.nodes[0].service.id, "api-1");
+ assert_eq!(response.nodes[0].service.address, "");
+ assert!(response.nodes[0].service.tags.is_empty());
+ assert_eq!(response.dns.ttl, "5s");
+ let encoded = serde_json::to_value(response).unwrap();
+ assert_eq!(encoded["Nodes"][0]["Service"]["ID"], "api-1");
+ assert_eq!(encoded["DNS"]["TTL"], "5s");
+ assert!(encoded.get("Dns").is_none());
+ }
+
+ #[test]
+ fn official_prepared_query_explain_response_unwraps_query_document() {
+ let response: ConsulPreparedQueryExplainResponse = serde_json::from_value(serde_json::json!({
+ "Query": {
+ "ID": "query-1",
+ "Name": "payments",
+ "Session": "",
+ "Token": "secret-management-token",
+ "Template": { "Type": "name_prefix_match", "Regexp": "^payments-(.*)$" },
+ "Service": { "Service": "api", "Near": "", "OnlyPassing": true, "Tags": [] },
+ "DNS": { "TTL": "5s" },
+ "CreateIndex": 10,
+ "ModifyIndex": 11
+ },
+ "Index": 11,
+ "KnownLeader": true
+ }))
+ .unwrap();
+ let mut query = response.query;
+ redact_prepared_query_secrets(&mut query);
+ assert_eq!(query["ID"], "query-1");
+ assert_eq!(query["Service"]["Service"], "api");
+ assert_eq!(query["Template"]["Type"], "name_prefix_match");
+ assert_eq!(query["DNS"]["TTL"], "5s");
+ assert_eq!(query["Token"], "****************");
+ }
+}
diff --git a/crates/dbx-core/src/consul/txn.rs b/crates/dbx-core/src/consul/txn.rs
new file mode 100644
index 0000000000..aad9bff83c
--- /dev/null
+++ b/crates/dbx-core/src/consul/txn.rs
@@ -0,0 +1,527 @@
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use reqwest::{Method, StatusCode};
+use serde::{Deserialize, Serialize};
+
+use crate::agent_kv::{KvInt64, KvValue, KvValueEncoding};
+use crate::connection::AppState;
+
+use super::client::{client_for_state, ensure_writable_core, ConsulClient};
+use super::response::{decode_json_response, ensure_success};
+
+pub const MAX_TXN_OPERATIONS: usize = 64;
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum ConsulTxnVerb {
+ Get,
+ GetTree,
+ Set,
+ Cas,
+ Delete,
+ DeleteCas,
+ DeleteTree,
+ Lock,
+ Unlock,
+ CheckIndex,
+ CheckNotExists,
+ CheckSession,
+}
+
+impl ConsulTxnVerb {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Get => "get",
+ Self::GetTree => "get-tree",
+ Self::Set => "set",
+ Self::Cas => "cas",
+ Self::Delete => "delete",
+ Self::DeleteCas => "delete-cas",
+ Self::DeleteTree => "delete-tree",
+ Self::Lock => "lock",
+ Self::Unlock => "unlock",
+ Self::CheckIndex => "check-index",
+ Self::CheckNotExists => "check-not-exists",
+ Self::CheckSession => "check-session",
+ }
+ }
+
+ fn writes(self) -> bool {
+ matches!(
+ self,
+ Self::Set | Self::Cas | Self::Delete | Self::DeleteCas | Self::DeleteTree | Self::Lock | Self::Unlock
+ )
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnKvOperation {
+ pub verb: ConsulTxnVerb,
+ pub key: String,
+ pub value: Option<KvValue>,
+ pub flags: Option<KvInt64>,
+ pub index: Option<KvInt64>,
+ pub session: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnRequest {
+ pub operations: Vec<ConsulTxnKvOperation>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnError {
+ pub op_index: usize,
+ pub message: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnResult {
+ pub committed: bool,
+ pub errors: Vec<ConsulTxnError>,
+ pub results: Vec<ConsulTxnKvResult>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnKvResult {
+ pub key: String,
+ pub value: Option<KvValue>,
+ pub flags: KvInt64,
+ pub create_index: KvInt64,
+ pub modify_index: KvInt64,
+ pub lock_index: KvInt64,
+ pub session: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct RawTxnResponse {
+ #[serde(default)]
+ errors: Option<Vec<RawTxnError>>,
+ #[serde(default)]
+ results: Option<Vec<RawTxnResult>>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct RawTxnResult {
+ #[serde(rename = "KV", alias = "Kv")]
+ kv: Option<RawTxnKvResult>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct RawTxnKvResult {
+ #[serde(default)]
+ key: String,
+ value: Option<String>,
+ #[serde(default)]
+ flags: u64,
+ #[serde(default)]
+ create_index: u64,
+ #[serde(default)]
+ modify_index: u64,
+ #[serde(default)]
+ lock_index: u64,
+ session: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+struct RawTxnError {
+ op_index: usize,
+ what: String,
+}
+
+impl ConsulClient {
+ pub(super) async fn txn(&self, request: ConsulTxnRequest) -> Result<ConsulTxnResult, String> {
+ validate_operations(&request.operations)?;
+ let body = serde_json::to_vec(&request.operations.iter().map(operation_json).collect::<Result<Vec<_>, _>>()?)
+ .map_err(|error| format!("Failed to encode Consul transaction: {error}"))?;
+ let mut url = self.api_url("/v1/txn")?;
+ self.append_scope(&mut url, false);
+ let response = self.send(Method::PUT, url, Some(body)).await?;
+ let status = response.status();
+ let response = if is_txn_result_status(response.status()) {
+ response
+ } else {
+ ensure_success(response, "execute transaction", self.token()).await?
+ };
+ let response = decode_json_response::<RawTxnResponse>(response, "execute transaction").await?;
+ map_txn_response(status, response)
+ }
+}
+
+fn map_txn_response(status: StatusCode, response: RawTxnResponse) -> Result<ConsulTxnResult, String> {
+ let errors = response
+ .errors
+ .unwrap_or_default()
+ .into_iter()
+ .map(|error| ConsulTxnError { op_index: error.op_index, message: error.what })
+ .collect::<Vec<_>>();
+ let results = response
+ .results
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|result| result.kv)
+ .map(txn_result)
+ .collect::<Result<_, _>>()?;
+ Ok(ConsulTxnResult { committed: status.is_success() && errors.is_empty(), errors, results })
+}
+
+fn is_txn_result_status(status: StatusCode) -> bool {
+ status.is_success() || status == StatusCode::CONFLICT
+}
+
+pub async fn consul_txn_core(
+ state: &AppState,
+ connection_id: &str,
+ request: ConsulTxnRequest,
+) -> Result<ConsulTxnResult, String> {
+ validate_public_operations(&request.operations)?;
+ if request.operations.iter().any(|operation| operation.verb.writes()) {
+ ensure_writable_core(state, connection_id, "execute Consul transaction").await?;
+ }
+ let client = client_for_state(state, connection_id).await?;
+ for operation in request
+ .operations
+ .iter()
+ .filter(|operation| matches!(operation.verb, ConsulTxnVerb::Cas | ConsulTxnVerb::DeleteCas))
+ {
+ let current = client.get_key(&operation.key).await?;
+ if current
+ .metadata
+ .as_ref()
+ .and_then(|metadata| metadata.session.as_deref())
+ .is_some_and(|session| !session.is_empty())
+ {
+ return Err(format!("CONSUL_KEY_LOCKED: The Consul KV key '{}' is held by a Session", operation.key));
+ }
+ }
+ client.txn(request).await
+}
+
+pub async fn consul_rename_key_core(
+ state: &AppState,
+ connection_id: &str,
+ source: &str,
+ target: &str,
+ expected_modify_index: KvInt64,
+ copy: bool,
+) -> Result<ConsulTxnResult, String> {
+ ensure_writable_core(state, connection_id, if copy { "copy Consul KV key" } else { "rename Consul KV key" })
+ .await?;
+ if source.is_empty() || target.is_empty() || source == target {
+ return Err("CONSUL_RENAME_INVALID: Source and target keys must be distinct and non-empty".to_string());
+ }
+ let expected = parse_index(&expected_modify_index)?;
+ let client = client_for_state(state, connection_id).await?;
+ let current = client.get_key(source).await?;
+ if !current.found {
+ return Err("CONSUL_KEY_NOT_FOUND: Source key no longer exists".to_string());
+ }
+ let current_index = current
+ .metadata
+ .as_ref()
+ .and_then(|metadata| metadata.mod_revision.as_ref())
+ .ok_or("CONSUL_CAS_REQUIRED: Source key has no ModifyIndex")?;
+ if parse_index(current_index)? != expected {
+ return Err("CONSUL_CAS_CONFLICT: Source key changed before the transaction".to_string());
+ }
+ if current.metadata.as_ref().and_then(|metadata| metadata.session.as_deref()).is_some_and(|value| !value.is_empty())
+ {
+ return Err("CONSUL_KEY_LOCKED: Source key is held by a Consul Session".to_string());
+ }
+ let mut operations = vec![
+ ConsulTxnKvOperation {
+ verb: ConsulTxnVerb::CheckIndex,
+ key: source.to_string(),
+ value: None,
+ flags: None,
+ index: Some(expected_modify_index.clone()),
+ session: None,
+ },
+ operation(ConsulTxnVerb::CheckNotExists, target),
+ ConsulTxnKvOperation {
+ verb: ConsulTxnVerb::Cas,
+ key: target.to_string(),
+ value: current.value,
+ flags: current.metadata.as_ref().and_then(|metadata| metadata.flags.clone()),
+ index: Some(KvInt64("0".to_string())),
+ session: None,
+ },
+ ];
+ if !copy {
+ operations.push(ConsulTxnKvOperation {
+ verb: ConsulTxnVerb::DeleteCas,
+ key: source.to_string(),
+ value: None,
+ flags: None,
+ index: Some(expected_modify_index),
+ session: None,
+ });
+ }
+ client.txn(ConsulTxnRequest { operations }).await
+}
+
+pub(crate) fn cas_operation(key: String, value: KvValue, flags: KvInt64, index: KvInt64) -> ConsulTxnKvOperation {
+ ConsulTxnKvOperation {
+ verb: ConsulTxnVerb::Cas,
+ key,
+ value: Some(value),
+ flags: Some(flags),
+ index: Some(index),
+ session: None,
+ }
+}
+
+pub(crate) fn delete_cas_operation(key: String, index: KvInt64) -> ConsulTxnKvOperation {
+ ConsulTxnKvOperation {
+ verb: ConsulTxnVerb::DeleteCas,
+ key,
+ value: None,
+ flags: None,
+ index: Some(index),
+ session: None,
+ }
+}
+
+fn operation(verb: ConsulTxnVerb, key: &str) -> ConsulTxnKvOperation {
+ ConsulTxnKvOperation { verb, key: key.to_string(), value: None, flags: None, index: None, session: None }
+}
+
+fn validate_operations(operations: &[ConsulTxnKvOperation]) -> Result<(), String> {
+ if operations.is_empty() {
+ return Err("CONSUL_TXN_EMPTY: A transaction requires at least one operation".to_string());
+ }
+ if operations.len() > MAX_TXN_OPERATIONS {
+ return Err(format!(
+ "CONSUL_TXN_LIMIT_EXCEEDED: Consul transactions support at most {MAX_TXN_OPERATIONS} operations"
+ ));
+ }
+ for operation in operations {
+ if operation.key.is_empty() {
+ return Err("CONSUL_TXN_KEY_REQUIRED: Transaction keys cannot be empty".to_string());
+ }
+ if operation.index.as_ref().is_some_and(|index| parse_index(index).is_err()) {
+ return Err(format!("CONSUL_TXN_INDEX_INVALID: Invalid Index for key {}", operation.key));
+ }
+ if operation.flags.as_ref().is_some_and(|flags| parse_index(flags).is_err()) {
+ return Err(format!("CONSUL_TXN_FLAGS_INVALID: Invalid Flags for key {}", operation.key));
+ }
+ if matches!(operation.verb, ConsulTxnVerb::Lock | ConsulTxnVerb::Unlock | ConsulTxnVerb::CheckSession)
+ && operation.session.as_deref().map(str::trim).is_none_or(str::is_empty)
+ {
+ return Err(format!(
+ "CONSUL_TXN_SESSION_REQUIRED: {:?} requires a Session for key {}",
+ operation.verb, operation.key
+ ));
+ }
+ if matches!(operation.verb, ConsulTxnVerb::Lock) && operation.value.is_none() {
+ return Err(format!("CONSUL_TXN_VALUE_REQUIRED: lock requires a value for key {}", operation.key));
+ }
+ }
+ Ok(())
+}
+
+fn validate_public_operations(operations: &[ConsulTxnKvOperation]) -> Result<(), String> {
+ validate_operations(operations)?;
+ for operation in operations {
+ match operation.verb {
+ ConsulTxnVerb::Set | ConsulTxnVerb::Delete | ConsulTxnVerb::DeleteTree => {
+ return Err(format!(
+ "CONSUL_TXN_UNSAFE_VERB: Public transactions cannot use unconditional {:?}; use CAS or a dedicated prefix workflow",
+ operation.verb
+ ));
+ }
+ ConsulTxnVerb::Cas | ConsulTxnVerb::DeleteCas if operation.index.is_none() => {
+ return Err(format!(
+ "CONSUL_CAS_REQUIRED: {:?} requires an Index for key {}",
+ operation.verb, operation.key
+ ));
+ }
+ ConsulTxnVerb::Cas if operation.value.is_none() => {
+ return Err(format!("CONSUL_TXN_VALUE_REQUIRED: cas requires a value for key {}", operation.key));
+ }
+ _ => {}
+ }
+ }
+ Ok(())
+}
+
+fn txn_result(raw: RawTxnKvResult) -> Result<ConsulTxnKvResult, String> {
+ let value = raw
+ .value
+ .as_deref()
+ .map(|encoded| {
+ let bytes = STANDARD
+ .decode(encoded)
+ .map_err(|error| format!("CONSUL_INVALID_RESPONSE: Invalid transaction Value: {error}"))?;
+ Ok::<_, String>(match String::from_utf8(bytes.clone()) {
+ Ok(value) => KvValue { encoding: KvValueEncoding::Utf8, data: value },
+ Err(_) => KvValue { encoding: KvValueEncoding::Base64, data: STANDARD.encode(bytes) },
+ })
+ })
+ .transpose()?;
+ Ok(ConsulTxnKvResult {
+ key: raw.key,
+ value,
+ flags: KvInt64(raw.flags.to_string()),
+ create_index: KvInt64(raw.create_index.to_string()),
+ modify_index: KvInt64(raw.modify_index.to_string()),
+ lock_index: KvInt64(raw.lock_index.to_string()),
+ session: raw.session.filter(|session| !session.is_empty()),
+ })
+}
+
+fn operation_json(operation: &ConsulTxnKvOperation) -> Result<serde_json::Value, String> {
+ let mut kv = serde_json::Map::new();
+ kv.insert("Verb".to_string(), operation.verb.as_str().into());
+ kv.insert("Key".to_string(), operation.key.clone().into());
+ if let Some(value) = &operation.value {
+ let bytes = match value.encoding {
+ KvValueEncoding::Utf8 => value.data.as_bytes().to_vec(),
+ KvValueEncoding::Base64 => STANDARD
+ .decode(value.data.chars().filter(|character| !character.is_whitespace()).collect::<String>())
+ .map_err(|error| format!("CONSUL_VALUE_ENCODING_INVALID: {error}"))?,
+ };
+ kv.insert("Value".to_string(), STANDARD.encode(bytes).into());
+ }
+ if let Some(flags) = &operation.flags {
+ kv.insert("Flags".to_string(), parse_index(flags)?.into());
+ }
+ if let Some(index) = &operation.index {
+ kv.insert("Index".to_string(), parse_index(index)?.into());
+ }
+ if let Some(session) = &operation.session {
+ kv.insert("Session".to_string(), session.clone().into());
+ }
+ Ok(serde_json::json!({ "KV": kv }))
+}
+
+fn parse_index(value: &KvInt64) -> Result<u64, String> {
+ value.as_str().parse::<u64>().map_err(|_| format!("Invalid unsigned 64-bit integer: {}", value.as_str()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::consul::test_support::{serve_once, test_client};
+
+ #[test]
+ fn enforces_transaction_limit() {
+ let operations =
+ (0..65).map(|index| operation(ConsulTxnVerb::Get, &format!("key-{index}"))).collect::<Vec<_>>();
+ assert!(validate_operations(&operations).unwrap_err().contains("CONSUL_TXN_LIMIT_EXCEEDED"));
+ }
+
+ #[test]
+ fn serializes_u64_as_json_number_and_value_as_base64() {
+ let value = KvValue { encoding: KvValueEncoding::Utf8, data: "hello".to_string() };
+ let encoded = operation_json(&cas_operation(
+ "a b".to_string(),
+ value,
+ KvInt64(u64::MAX.to_string()),
+ KvInt64("0".to_string()),
+ ))
+ .unwrap();
+ assert_eq!(encoded["KV"]["Value"], "aGVsbG8=");
+ assert_eq!(encoded["KV"]["Flags"], u64::MAX);
+ }
+
+ #[test]
+ fn public_transactions_reject_unconditional_writes_and_require_cas_fields() {
+ for verb in [ConsulTxnVerb::Set, ConsulTxnVerb::Delete, ConsulTxnVerb::DeleteTree] {
+ assert!(validate_public_operations(&[operation(verb, "key")]).unwrap_err().contains("UNSAFE_VERB"));
+ }
+ assert!(validate_public_operations(&[operation(ConsulTxnVerb::Cas, "key")])
+ .unwrap_err()
+ .contains("CAS_REQUIRED"));
+ let mut cas = cas_operation(
+ "key".into(),
+ KvValue { encoding: KvValueEncoding::Utf8, data: "value".into() },
+ KvInt64("0".into()),
+ KvInt64("0".into()),
+ );
+ assert!(validate_public_operations(&[cas.clone()]).is_ok());
+ cas.value = None;
+ assert!(validate_public_operations(&[cas]).unwrap_err().contains("VALUE_REQUIRED"));
+ }
+
+ #[test]
+ fn transaction_results_preserve_kv_data_and_indexes() {
+ let result = txn_result(RawTxnKvResult {
+ key: "binary".into(),
+ value: Some("AP+A".into()),
+ flags: u64::MAX,
+ create_index: 2,
+ modify_index: 3,
+ lock_index: 4,
+ session: Some("session-1".into()),
+ })
+ .unwrap();
+ assert_eq!(result.value.unwrap().encoding, KvValueEncoding::Base64);
+ assert_eq!(result.flags.as_str(), u64::MAX.to_string());
+ assert_eq!(result.modify_index.as_str(), "3");
+ assert_eq!(result.session.as_deref(), Some("session-1"));
+ }
+
+ #[test]
+ fn transaction_conflicts_are_decoded_as_results() {
+ assert!(is_txn_result_status(StatusCode::OK));
+ assert!(is_txn_result_status(StatusCode::CONFLICT));
+ assert!(!is_txn_result_status(StatusCode::BAD_REQUEST));
+ assert!(!is_txn_result_status(StatusCode::INTERNAL_SERVER_ERROR));
+ }
+
+ #[test]
+ fn empty_conflict_response_is_never_committed() {
+ let result =
+ map_txn_response(StatusCode::CONFLICT, RawTxnResponse { errors: Some(vec![]), results: Some(vec![]) })
+ .unwrap();
+ assert!(!result.committed);
+ assert!(result.errors.is_empty());
+ assert!(result.results.is_empty());
+ }
+
+ #[test]
+ fn committed_delete_response_accepts_consul_null_collections() {
+ // Consul returns this exact shape for a successful delete-cas transaction.
+ let raw: RawTxnResponse = serde_json::from_str(r#"{"Results":[],"Errors":null}"#).unwrap();
+ let result = map_txn_response(StatusCode::OK, raw).unwrap();
+ assert!(result.committed);
+ assert!(result.errors.is_empty());
+ assert!(result.results.is_empty());
+ }
+
+ #[tokio::test]
+ async fn conflict_response_preserves_results_errors_and_wire_contract() {
+ let body = r#"{"Results":[{"KV":{"Key":"source","Value":"aGVsbG8=","Flags":7,"CreateIndex":2,"ModifyIndex":3,"LockIndex":0}}],"Errors":[{"OpIndex":1,"What":"target exists"}]}"#;
+ let response = format!(
+ "HTTP/1.1 409 Conflict\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let (url, request_rx) = serve_once(response).await;
+ let client = test_client(url).await;
+ let result =
+ client.txn(ConsulTxnRequest { operations: vec![operation(ConsulTxnVerb::Get, "source")] }).await.unwrap();
+
+ assert!(!result.committed);
+ assert_eq!(result.errors[0].op_index, 1);
+ assert_eq!(result.results[0].key, "source");
+ assert_eq!(result.results[0].value.as_ref().unwrap().data, "hello");
+
+ let request = request_rx.await.unwrap();
+ let (headers, body) = request.split_once("\r\n\r\n").unwrap();
+ assert!(headers.starts_with("PUT /proxy/v1/txn?dc=dc1&ns=team-a&partition=partition-a HTTP/1.1"));
+ assert!(headers.to_ascii_lowercase().contains("x-consul-token: fixture-token"));
+ let wire: serde_json::Value = serde_json::from_str(body).unwrap();
+ assert_eq!(wire[0]["KV"]["Verb"], "get");
+ assert_eq!(wire[0]["KV"]["Key"], "source");
+ }
+}
diff --git a/crates/dbx-core/src/consul/types.rs b/crates/dbx-core/src/consul/types.rs
new file mode 100644
index 0000000000..66d4c16497
--- /dev/null
+++ b/crates/dbx-core/src/consul/types.rs
@@ -0,0 +1,13 @@
+use serde::Deserialize;
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub(super) struct ConsulKvEntry {
+ pub(super) create_index: u64,
+ pub(super) modify_index: u64,
+ pub(super) lock_index: u64,
+ pub(super) key: String,
+ pub(super) flags: u64,
+ pub(super) value: Option<String>,
+ pub(super) session: Option<String>,
+}
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index 14b91eb4dc..f86db4af11 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -25,6 +25,7 @@ pub mod cloud_sync;
pub mod config;
pub mod connection;
pub mod connection_secrets;
+pub mod consul;
pub mod correction;
pub mod csv_export;
pub mod data_compare;
diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs
index 3d5db0a105..016dda91d3 100644
--- a/crates/dbx-core/src/models/connection.rs
+++ b/crates/dbx-core/src/models/connection.rs
@@ -2,6 +2,7 @@ use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
+use std::fmt;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
@@ -68,7 +69,7 @@ pub fn database_info_from_protocol_value(value: &Value) -> Option<DatabaseConnec
serde_json::from_value::<DatabaseInfoEnvelope>(value.clone()).ok()?.database_info
}
-#[derive(Debug, Clone, Serialize, PartialEq)]
+#[derive(Clone, Serialize, PartialEq)]
pub struct ConnectionConfig {
pub id: String,
pub name: String,
@@ -182,6 +183,42 @@ pub struct ConnectionConfig {
pub database_info: Option<DatabaseConnectionInfo>,
}
+impl fmt::Debug for ConnectionConfig {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut value = serde_json::to_value(self).map_err(|_| fmt::Error)?;
+ redact_connection_debug_value(&mut value);
+ formatter.debug_tuple("ConnectionConfig").field(&value).finish()
+ }
+}
+
+fn redact_connection_debug_value(value: &mut serde_json::Value) {
+ match value {
+ serde_json::Value::Object(object) => {
+ for (key, value) in object {
+ let key = key.to_ascii_lowercase().replace(['_', '-'], "");
+ if key.contains("password")
+ || key.contains("passphrase")
+ || key.contains("token")
+ || key.contains("secret")
+ || key.contains("apikey")
+ || key == "connectionstring"
+ || key == "initscript"
+ {
+ *value = serde_json::Value::String("[REDACTED]".to_string());
+ } else {
+ redact_connection_debug_value(value);
+ }
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for value in values {
+ redact_connection_debug_value(value);
+ }
+ }
+ _ => {}
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TransportLayerConfig {
@@ -536,6 +573,7 @@ pub enum DatabaseType {
#[serde(rename = "zookeeper")]
ZooKeeper,
Nacos,
+ Consul,
#[serde(rename = "iris")]
Iris,
#[serde(rename = "turso")]
@@ -1123,6 +1161,7 @@ impl ConnectionConfig {
DatabaseType::MessageQueue => self.message_queue_admin_url(),
DatabaseType::Mqtt => self.mqtt_broker_url(),
DatabaseType::Nacos => self.nacos_admin_url(),
+ DatabaseType::Consul => self.consul_api_url(),
}
}
@@ -1365,6 +1404,7 @@ impl ConnectionConfig {
DatabaseType::MessageQueue => self.message_queue_admin_url(),
DatabaseType::Mqtt => self.mqtt_broker_url(),
DatabaseType::Nacos => self.nacos_admin_url(),
+ DatabaseType::Consul => self.consul_api_url(),
}
}
@@ -1401,6 +1441,20 @@ impl ConnectionConfig {
.to_string()
}
+ fn consul_api_url(&self) -> String {
+ self.external_config
+ .as_ref()
+ .and_then(|value| value.get("serverAddr").or_else(|| value.get("server_addr")))
+ .and_then(|value| value.as_str())
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ .unwrap_or_else(|| {
+ let scheme = if self.ssl { "https" } else { "http" };
+ format!("{scheme}://{}:{}", bracket_ipv6(&self.host), self.port)
+ })
+ }
+
fn mqtt_broker_url(&self) -> String {
#[cfg(feature = "mq-admin")]
{
@@ -2368,6 +2422,24 @@ mod tests {
}
}
+ #[test]
+ fn connection_debug_redacts_passwords_tokens_and_nested_secrets() {
+ let mut config = mysql_config("root", "database-password", Some("app"));
+ config.connection_string = Some("server=db;password=inline-secret".into());
+ config.init_script = Some("CREATE SECRET leaked".into());
+ config.external_config = Some(serde_json::json!({
+ "consulToken": "consul-secret",
+ "nested": { "OIDCClientSecret": "oidc-secret", "visible": "safe" }
+ }));
+
+ let output = format!("{config:?}");
+ for secret in ["database-password", "inline-secret", "CREATE SECRET leaked", "consul-secret", "oidc-secret"] {
+ assert!(!output.contains(secret));
+ }
+ assert!(output.contains("[REDACTED]"));
+ assert!(output.contains("safe"));
+ }
+
#[test]
fn legacy_mcp_access_is_ignored_and_not_serialized() {
let legacy: ConnectionConfig = serde_json::from_value(serde_json::json!({
diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rs
index f882500653..6d255d9056 100644
--- a/crates/dbx-core/src/query.rs
+++ b/crates/dbx-core/src/query.rs
@@ -1669,6 +1669,7 @@ async fn do_execute_typed(
.map(|result| truncate_result_with_max_rows(result, max_rows))
}
PoolKind::HBase(_) => Err("SQL execution is not supported for HBase connections".to_string()),
+ PoolKind::Consul(_) => Err("SQL execution is not supported for Consul connections".to_string()),
};
result
.map(normalize_query_result_for_js)
@@ -2852,6 +2853,7 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
| PoolKind::Agent(_) => true,
PoolKind::MessageQueue
| PoolKind::Nacos
+ | PoolKind::Consul(_)
| PoolKind::HBase(_)
| PoolKind::DuckDbWorker(_)
| PoolKind::Redis(_)
@@ -3095,7 +3097,7 @@ pub async fn execute_statements_in_transaction_on_pool_typed(
TxPath::Explicit
}
PoolKind::Agent(client) => TxPath::Agent(client.clone()),
- PoolKind::MessageQueue | PoolKind::Nacos | PoolKind::HBase(_) => TxPath::None,
+ PoolKind::MessageQueue | PoolKind::Nacos | PoolKind::Consul(_) | PoolKind::HBase(_) => TxPath::None,
#[cfg(feature = "mq-admin")]
PoolKind::Mqtt(_) => TxPath::None,
PoolKind::DuckDbWorker(_)
diff --git a/crates/dbx-core/src/sql_dialect/ddl_profile.rs b/crates/dbx-core/src/sql_dialect/ddl_profile.rs
index 76b03d8971..2b811c6c73 100644
--- a/crates/dbx-core/src/sql_dialect/ddl_profile.rs
+++ b/crates/dbx-core/src/sql_dialect/ddl_profile.rs
@@ -674,7 +674,7 @@ pub fn profile_for(db_type: DatabaseType) -> DdlDialectProfile {
// Non-tabular / not applicable for relational CREATE TABLE
Redis | MongoDb | Elasticsearch | Easysearch | Qdrant | Milvus | Weaviate | ChromaDb | Neo4j | Cassandra
- | Etcd | ZooKeeper | Nacos | InfluxDb | VictoriaMetrics | MessageQueue | Mqtt | Hbase => {
+ | Etcd | ZooKeeper | Nacos | Consul | InfluxDb | VictoriaMetrics | MessageQueue | Mqtt | Hbase => {
conservative_ansi(db_type)
}
}
diff --git a/crates/dbx-core/src/table_export.rs b/crates/dbx-core/src/table_export.rs
index 99879d10a5..0d38aa5c5d 100644
--- a/crates/dbx-core/src/table_export.rs
+++ b/crates/dbx-core/src/table_export.rs
@@ -2627,7 +2627,7 @@ mod tests {
)
.await;
- let export = run_external_driver_export(&fixture);
+ let export = Box::pin(run_external_driver_export(&fixture));
let cancel = async {
wait_for_external_driver_call(&fixture.calls, "executeQueryPage").await;
set_export_cancelled(&fixture.request.export_id).await;
@@ -2666,7 +2666,7 @@ mod tests {
)
.await;
- let export = run_external_driver_export(&fixture);
+ let export = Box::pin(run_external_driver_export(&fixture));
let cancel = async {
wait_for_external_driver_call(&fixture.calls, "fetchQueryPage").await;
set_export_cancelled(&fixture.request.export_id).await;
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 11623c720d..9db8eaa9f6 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -557,6 +557,109 @@ async fn main() {
.route("/zookeeper/get", post(routes::zookeeper::get))
.route("/zookeeper/put", post(routes::zookeeper::put))
.route("/zookeeper/delete", post(routes::zookeeper::delete))
+ // Consul
+ .route("/consul/capabilities", post(routes::consul::capabilities))
+ .route("/consul/txn", post(routes::consul::txn))
+ .route("/consul/rename-key", post(routes::consul::rename_key))
+ .route("/consul/blocking-query", post(routes::consul::blocking_query))
+ .route("/consul/domain-watch", post(routes::consul::domain_watch))
+ .route("/consul/cancel-blocking", post(routes::consul::cancel_blocking))
+ .route("/consul/list-prefix", post(routes::consul::list_prefix))
+ .route("/consul/list-recursive", post(routes::consul::list_recursive))
+ .route("/consul/search", post(routes::consul::search))
+ .route("/consul/search-progress", post(routes::consul::search_progress))
+ .route("/consul/cancel-search", post(routes::consul::cancel_search))
+ .route("/consul/export-bundle", post(routes::consul::export_bundle))
+ .route("/consul/import-preview", post(routes::consul::import_preview))
+ .route("/consul/import-execute", post(routes::consul::import_execute))
+ .route("/consul/delete-prefix-preview", post(routes::consul::delete_prefix_preview))
+ .route("/consul/delete-prefix-execute", post(routes::consul::delete_prefix_execute))
+ .route("/consul/get", post(routes::consul::get))
+ .route("/consul/put", post(routes::consul::put))
+ .route("/consul/delete", post(routes::consul::delete))
+ .route("/consul/prepared-query/list", post(routes::consul::prepared_query_list))
+ .route("/consul/prepared-query/read", post(routes::consul::prepared_query_read))
+ .route("/consul/prepared-query/create", post(routes::consul::prepared_query_create))
+ .route("/consul/prepared-query/update", post(routes::consul::prepared_query_update))
+ .route("/consul/prepared-query/delete", post(routes::consul::prepared_query_delete))
+ .route("/consul/prepared-query/execute", post(routes::consul::prepared_query_execute))
+ .route("/consul/prepared-query/explain", post(routes::consul::prepared_query_explain))
+ .route("/consul/event/list", post(routes::consul::event_list))
+ .route("/consul/event/fire", post(routes::consul::event_fire).layer(DefaultBodyLimit::max(16 * 1024)))
+ .route("/consul/coordinate/nodes", post(routes::consul::coordinate_nodes))
+ .route("/consul/operator/read", post(routes::consul::operator_read))
+ .route("/consul/operator/snapshot/generate", post(routes::consul::snapshot_generate))
+ .route("/consul/operator/snapshot/restore", post(routes::consul::snapshot_restore))
+ .route("/consul/operator/autopilot/update", post(routes::consul::autopilot_update))
+ .route("/consul/operator/raft/transfer", post(routes::consul::raft_transfer))
+ .route("/consul/operator/raft/remove", post(routes::consul::raft_remove))
+ .route("/consul/operator/keyring/write", post(routes::consul::keyring_write))
+ .route("/consul/operator/license/write", post(routes::consul::license_write))
+ .route("/consul/status/leader", post(routes::consul::status_leader))
+ .route("/consul/status/peers", post(routes::consul::status_peers))
+ .route("/consul/agent/self", post(routes::consul::agent_self))
+ .route("/consul/agent/members", post(routes::consul::agent_members))
+ .route("/consul/agent/metrics", post(routes::consul::agent_metrics))
+ .route("/consul/catalog/datacenters", post(routes::consul::catalog_datacenters))
+ .route("/consul/catalog/nodes", post(routes::consul::catalog_nodes))
+ .route("/consul/catalog/services", post(routes::consul::catalog_services))
+ .route("/consul/catalog/service-nodes", post(routes::consul::catalog_service_nodes))
+ .route("/consul/catalog/node-services", post(routes::consul::catalog_node_services))
+ .route("/consul/health/node", post(routes::consul::health_node))
+ .route("/consul/health/checks", post(routes::consul::health_checks))
+ .route("/consul/health/service", post(routes::consul::health_service))
+ .route("/consul/health/state", post(routes::consul::health_state))
+ .route("/consul/agent/services", post(routes::consul::agent_services))
+ .route("/consul/agent/service", post(routes::consul::agent_service))
+ .route("/consul/agent/checks", post(routes::consul::agent_checks))
+ .route("/consul/agent/service/register", post(routes::consul::agent_register_service))
+ .route("/consul/agent/service/deregister", post(routes::consul::agent_deregister_service))
+ .route("/consul/agent/service/maintenance", post(routes::consul::agent_service_maintenance))
+ .route("/consul/agent/check/register", post(routes::consul::agent_register_check))
+ .route("/consul/agent/check/deregister", post(routes::consul::agent_deregister_check))
+ .route("/consul/agent/check/ttl", post(routes::consul::agent_update_ttl))
+ .route("/consul/sessions", post(routes::consul::sessions))
+ .route("/consul/sessions/node", post(routes::consul::node_sessions))
+ .route("/consul/session", post(routes::consul::session))
+ .route("/consul/session/keys", post(routes::consul::session_keys))
+ .route("/consul/session/destroy-impact", post(routes::consul::session_destroy_impact))
+ .route("/consul/session/create", post(routes::consul::create_session))
+ .route("/consul/session/renew", post(routes::consul::renew_session))
+ .route("/consul/session/destroy", post(routes::consul::destroy_session))
+ .route("/consul/lock/acquire", post(routes::consul::acquire_lock))
+ .route("/consul/lock/release", post(routes::consul::release_lock))
+ .route("/consul/acl/list", post(routes::consul::acl_list))
+ .route("/consul/acl/token/self", post(routes::consul::acl_token_self))
+ .route("/consul/acl/token/clone", post(routes::consul::acl_token_clone))
+ .route("/consul/acl/get", post(routes::consul::acl_get))
+ .route("/consul/acl/apply", post(routes::consul::acl_apply))
+ .route("/consul/acl/references", post(routes::consul::acl_references))
+ .route("/consul/acl/delete", post(routes::consul::acl_delete))
+ .route("/consul/enterprise/list", post(routes::consul::enterprise_list))
+ .route("/consul/enterprise/get", post(routes::consul::enterprise_get))
+ .route("/consul/enterprise/apply", post(routes::consul::enterprise_apply))
+ .route("/consul/enterprise/impact", post(routes::consul::enterprise_impact))
+ .route("/consul/enterprise/delete", post(routes::consul::enterprise_delete))
+ .route("/consul/mesh/config/list", post(routes::consul::mesh_config_list))
+ .route("/consul/mesh/config/get", post(routes::consul::mesh_config_get))
+ .route("/consul/mesh/config/apply", post(routes::consul::mesh_config_apply))
+ .route("/consul/mesh/config/delete", post(routes::consul::mesh_config_delete))
+ .route("/consul/mesh/intentions/list", post(routes::consul::mesh_intentions_list))
+ .route("/consul/mesh/intentions/get", post(routes::consul::mesh_intention_get))
+ .route("/consul/mesh/intentions/get-exact", post(routes::consul::mesh_intention_get_exact))
+ .route("/consul/mesh/intentions/upsert", post(routes::consul::mesh_intention_upsert))
+ .route("/consul/mesh/intentions/delete", post(routes::consul::mesh_intention_delete))
+ .route("/consul/mesh/intentions/delete-exact", post(routes::consul::mesh_intention_delete_exact))
+ .route("/consul/mesh/intentions/match", post(routes::consul::mesh_intention_match))
+ .route("/consul/mesh/intentions/check", post(routes::consul::mesh_intention_check))
+ .route("/consul/mesh/discovery-chain", post(routes::consul::mesh_discovery_chain))
+ .route("/consul/mesh/peerings/list", post(routes::consul::mesh_peering_list))
+ .route("/consul/mesh/peerings/get", post(routes::consul::mesh_peering_get))
+ .route("/consul/mesh/peerings/generate-token", post(routes::consul::mesh_peering_generate_token))
+ .route("/consul/mesh/peerings/establish", post(routes::consul::mesh_peering_establish))
+ .route("/consul/mesh/peerings/delete", post(routes::consul::mesh_peering_delete))
+ .route("/consul/mesh/exported-services/list", post(routes::consul::mesh_exported_services_list))
+ .route("/consul/mesh/exported-services/apply", post(routes::consul::mesh_exported_services_apply))
// HBase REST
.route("/hbase/table-schema", post(routes::hbase::get_table_schema))
.route("/hbase/scan-rows", post(routes::hbase::scan_rows))
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index 1a246749f1..556c0c6ca9 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -180,6 +180,41 @@ async fn run_temporary_connection_test(
None
};
+ // Keep all fallible post-connect checks inside this block so cleanup below
+ // runs before either a successful result or an error is returned.
+ let result: Result<ConnectionTestResult, String> = async {
+ let success_message = if pool_result.is_ok() && config.db_type == DatabaseType::Consul {
+ let client = {
+ let connections = app.connections.read().await;
+ match connections.get(&temp_id) {
+ Some(PoolKind::Consul(client)) => Some(client.clone()),
+ _ => None,
+ }
+ };
+ if let Some(client) = client {
+ let configured_target =
+ dbx_core::consul::ConsulConfig::from_connection(&config)?.agent_target.is_some();
+ let identity = if configured_target {
+ Some(client.validate_configured_agent_target().await?)
+ } else {
+ client.agent_self().await.ok()
+ };
+ identity
+ .map(|identity| format!("Connection successful (Agent: {} at {})", identity.node, identity.address))
+ .unwrap_or_else(|| {
+ "Connection successful (Agent identity unavailable; Agent writes disabled)".to_string()
+ })
+ } else {
+ "Connection successful (Agent identity unavailable; Agent writes disabled)".to_string()
+ }
+ } else {
+ "Connection successful".to_string()
+ };
+
+ pool_result.map(|_| ConnectionTestResult::success(success_message).with_database_info(database_info))
+ }
+ .await;
+
app.remove_connection_pools(&temp_id).await;
// Pool drain intentionally keeps durable MQ adapters for reconnect reuse; temporary
// probes must still release any registry entry if a cached path was used.
@@ -188,7 +223,7 @@ async fn run_temporary_connection_test(
app.reset_connection_transport_for_config(&temp_id, &config).await;
app.configs.write().await.remove(&temp_id);
- pool_result.map(|_| ConnectionTestResult::success("Connection successful").with_database_info(database_info))
+ result
}
pub async fn test_connection(
@@ -484,9 +519,10 @@ async fn remove_connection_pools_for_connection_ids(state: &WebState, connection
mod tests {
use super::{
apply_mongo_legacy_driver_profile, connect_db, connection_final_proxy_port, disconnect_db, load_connections,
- mark_mongo_legacy_driver, mcp_add_connection, mcp_remove_connection, save_connection_database_info,
- save_connections, test_connection, test_connection_with_info, ConnectRequest, DisconnectRequest,
- McpAddConnectionRequest, McpRemoveConnectionRequest, SaveConnectionDatabaseInfoRequest, SaveConnectionsRequest,
+ mark_mongo_legacy_driver, mcp_add_connection, mcp_remove_connection, run_temporary_connection_test,
+ save_connection_database_info, save_connections, test_connection, test_connection_with_info, ConnectRequest,
+ DisconnectRequest, McpAddConnectionRequest, McpRemoveConnectionRequest, SaveConnectionDatabaseInfoRequest,
+ SaveConnectionsRequest,
};
use crate::state::WebState;
use axum::extract::State;
@@ -498,9 +534,7 @@ mod tests {
};
use dbx_core::storage::{McpGlobalPolicy, Storage};
use std::sync::Arc;
- #[cfg(feature = "mq-admin")]
use tokio::io::{AsyncReadExt, AsyncWriteExt};
- #[cfg(feature = "mq-admin")]
use tokio::net::TcpListener;
fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
@@ -575,6 +609,23 @@ mod tests {
config
}
+ fn consul_config(id: &str, server_addr: &str) -> ConnectionConfig {
+ let parsed = reqwest::Url::parse(server_addr).unwrap();
+ let mut config = sqlite_config(id, "");
+ config.name = "Consul".to_string();
+ config.db_type = DatabaseType::Consul;
+ config.host = parsed.host_str().unwrap().to_string();
+ config.port = parsed.port().unwrap();
+ config.external_config = Some(serde_json::json!({
+ "serverAddr": server_addr,
+ "agentTarget": {
+ "node": "expected-agent",
+ "address": "127.0.0.1"
+ }
+ }));
+ config
+ }
+
#[test]
fn mongo_legacy_marker_updates_only_mongodb_profiles() {
let mut mongo = sqlite_config("mongo", "");
@@ -675,6 +726,51 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
+ #[tokio::test]
+ async fn failed_consul_agent_target_validation_cleans_up_temporary_state() {
+ let (state, dir) = test_web_state().await;
+ let server_addr = spawn_consul_agent_server().await;
+ let config = consul_config("consul-test", &server_addr);
+
+ let error = run_temporary_connection_test(&state.app, config, false).await.unwrap_err();
+
+ assert!(error.contains("CONSUL_AGENT_TARGET_MISMATCH"), "unexpected error: {error}");
+ assert!(state.app.configs.read().await.keys().all(|key| !key.starts_with("__test_")));
+ assert!(state.app.connections.read().await.keys().all(|key| !key.starts_with("__test_")));
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ async fn spawn_consul_agent_server() -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ loop {
+ let Ok((mut stream, _)) = listener.accept().await else {
+ break;
+ };
+ tokio::spawn(async move {
+ let mut buf = [0_u8; 2048];
+ let Ok(n) = stream.read(&mut buf).await else {
+ return;
+ };
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let body = if request.starts_with("GET /v1/agent/self ") {
+ r#"{"Config":{"NodeName":"actual-agent","Datacenter":"dc1"},"Member":{"Addr":"127.0.0.1","Tags":{}}}"#
+ } else {
+ "[]"
+ };
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://{addr}")
+ }
+
#[cfg(feature = "mq-admin")]
#[tokio::test]
async fn mq_connection_test_does_not_retain_temporary_adapter() {
diff --git a/crates/dbx-web/src/routes/consul.rs b/crates/dbx-web/src/routes/consul.rs
new file mode 100644
index 0000000000..a577cb071d
--- /dev/null
+++ b/crates/dbx-web/src/routes/consul.rs
@@ -0,0 +1,1537 @@
+use std::sync::Arc;
+
+use axum::extract::State;
+use axum::Json;
+use serde::Deserialize;
+
+use crate::error::AppError;
+use crate::state::WebState;
+
+async fn ensure_writable(
+ app: &dbx_core::connection::AppState,
+ connection_id: &str,
+ action: &str,
+) -> Result<(), AppError> {
+ if let Some(name) = dbx_core::query::connection_readonly_name(app, connection_id).await {
+ return Err(AppError::from(format!(
+ "Read-only mode: connection '{}' has read-only protection enabled. {} blocked.",
+ name, action
+ )));
+ }
+ Ok(())
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulListPrefixRequest {
+ pub connection_id: String,
+ pub prefix: String,
+ pub limit: usize,
+ pub continuation: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulListRecursiveRequest {
+ pub connection_id: String,
+ pub prefix: String,
+ pub max_entries: usize,
+ pub max_value_bytes: usize,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulSearchRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSearchControlRequest {
+ pub connection_id: String,
+ pub request_id: String,
+ pub scope: dbx_core::consul::ConsulScope,
+ pub generation: u64,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulExportApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulExportRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulImportApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulImportRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeletePrefixPreviewRequest {
+ pub connection_id: String,
+ pub prefix: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDeletePrefixExecuteRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulDeletePrefixRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulConnectionRequest {
+ pub connection_id: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTxnApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulTxnRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulRenameApiRequest {
+ pub connection_id: String,
+ pub source: String,
+ pub target: String,
+ pub expected_modify_index: dbx_core::agent_kv::KvInt64,
+ pub copy: bool,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulBlockingApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulBlockingRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulDomainWatchApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulDomainWatchRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulCancelBlockingApiRequest {
+ pub connection_id: String,
+ pub scope: dbx_core::consul::ConsulScope,
+ pub generation: u64,
+ pub operation_id: String,
+}
+
+pub async fn txn(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulTxnApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulTxnResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Execute Consul transaction").await?;
+ Ok(Json(
+ dbx_core::consul::consul_txn_core(&state.app, &req.connection_id, req.request).await.map_err(AppError::from)?,
+ ))
+}
+
+pub async fn rename_key(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulRenameApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulTxnResult>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_rename_key_core(
+ &state.app,
+ &req.connection_id,
+ &req.source,
+ &req.target,
+ req.expected_modify_index,
+ req.copy,
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn blocking_query(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulBlockingApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulBlockingResponse>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_blocking_query_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn domain_watch(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulDomainWatchApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulDomainWatchResponse>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_domain_watch_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn cancel_blocking(Json(req): Json<ConsulCancelBlockingApiRequest>) -> Result<Json<bool>, AppError> {
+ Ok(Json(dbx_core::consul::consul_cancel_blocking_core(
+ &req.connection_id,
+ &req.scope,
+ req.generation,
+ &req.operation_id,
+ )))
+}
+
+pub async fn capabilities(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<dbx_core::consul::ConsulCapabilities>, AppError> {
+ let result =
+ dbx_core::consul::consul_capabilities_core(&state.app, &req.connection_id).await.map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulKeyRequest {
+ pub connection_id: String,
+ pub key: String,
+ pub options: Option<dbx_core::agent_kv::KvDeleteOptions>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulPutRequest {
+ pub connection_id: String,
+ pub key: String,
+ pub value: dbx_core::agent_kv::KvValue,
+ pub options: Option<dbx_core::agent_kv::KvPutOptions>,
+}
+
+pub async fn list_prefix(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulListPrefixRequest>,
+) -> Result<Json<dbx_core::agent_kv::KvListPrefixResponse>, AppError> {
+ let result = dbx_core::consul::consul_list_prefix_core(
+ &state.app,
+ &req.connection_id,
+ &req.prefix,
+ req.limit,
+ req.continuation.as_deref(),
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn list_recursive(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulListRecursiveRequest>,
+) -> Result<Json<dbx_core::consul::ConsulRecursiveListResponse>, AppError> {
+ let result = dbx_core::consul::consul_list_recursive_core(
+ &state.app,
+ &req.connection_id,
+ &req.prefix,
+ req.max_entries,
+ req.max_value_bytes,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn search(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulSearchApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSearchResponse>, AppError> {
+ let result = dbx_core::consul::consul_search_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn search_progress(
+ Json(req): Json<ConsulSearchControlRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSearchProgress>, AppError> {
+ Ok(Json(dbx_core::consul::consul_search_progress_core(
+ &req.connection_id,
+ &req.scope,
+ req.generation,
+ &req.request_id,
+ )))
+}
+
+pub async fn cancel_search(Json(req): Json<ConsulSearchControlRequest>) -> Result<Json<bool>, AppError> {
+ Ok(Json(dbx_core::consul::consul_cancel_search_core(
+ &req.connection_id,
+ &req.scope,
+ req.generation,
+ &req.request_id,
+ )))
+}
+
+pub async fn export_bundle(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulExportApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulKvBundle>, AppError> {
+ let result = dbx_core::consul::consul_export_bundle_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn import_preview(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulImportApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulImportPreview>, AppError> {
+ let result = dbx_core::consul::consul_import_preview_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn import_execute(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulImportApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulImportReport>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Import Consul KV bundle").await?;
+ let result = dbx_core::consul::consul_import_execute_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn delete_prefix_preview(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulDeletePrefixPreviewRequest>,
+) -> Result<Json<dbx_core::consul::ConsulDeletePrefixPreview>, AppError> {
+ let result = dbx_core::consul::consul_delete_prefix_preview_core(&state.app, &req.connection_id, &req.prefix)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn delete_prefix_execute(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulDeletePrefixExecuteRequest>,
+) -> Result<Json<dbx_core::consul::ConsulDeletePrefixReport>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul KV prefix").await?;
+ let result = dbx_core::consul::consul_delete_prefix_execute_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulKeyRequest>,
+) -> Result<Json<dbx_core::agent_kv::KvGetResponse>, AppError> {
+ let result =
+ dbx_core::consul::consul_get_core(&state.app, &req.connection_id, &req.key).await.map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn put(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulPutRequest>,
+) -> Result<Json<dbx_core::agent_kv::KvPutResponse>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Put Consul KV key").await?;
+ let result = dbx_core::consul::consul_put_core(
+ &state.app,
+ &req.connection_id,
+ &req.key,
+ req.value,
+ req.options.unwrap_or_default(),
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulKeyRequest>,
+) -> Result<Json<dbx_core::agent_kv::KvDeleteResponse>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul KV key").await?;
+ let result =
+ dbx_core::consul::consul_delete_core(&state.app, &req.connection_id, &req.key, req.options.unwrap_or_default())
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulIdRequest {
+ pub connection_id: String,
+ pub id: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulQueryInputRequest {
+ pub connection_id: String,
+ pub id: Option<String>,
+ pub input: dbx_core::consul::ConsulPreparedQueryInput,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulQueryExecuteApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulPreparedQueryExecuteRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulNameRequest {
+ pub connection_id: String,
+ pub name: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulEventFireApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulEventFireRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulOperatorReadRequest {
+ pub connection_id: String,
+ pub kind: dbx_core::consul::ConsulOperatorReadKind,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSnapshotRestoreApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulSnapshotRestoreRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAutopilotApiRequest {
+ pub connection_id: String,
+ pub update: dbx_core::consul::ConsulAutopilotUpdate,
+ pub confirmation: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulRaftApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulRaftWriteRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulKeyringApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulKeyringWriteRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulLicenseApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulLicenseWriteRequest,
+}
+
+pub async fn prepared_query_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<Vec<dbx_core::consul::ConsulPreparedQuery>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_prepared_query_list_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn prepared_query_read(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulPreparedQuery>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_prepared_query_read_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn prepared_query_create(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulQueryInputRequest>,
+) -> Result<Json<String>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Create Consul prepared query").await?;
+ Ok(Json(
+ dbx_core::consul::consul_prepared_query_create_core(&state.app, &req.connection_id, req.input)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn prepared_query_update(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulQueryInputRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Update Consul prepared query").await?;
+ dbx_core::consul::consul_prepared_query_update_core(
+ &state.app,
+ &req.connection_id,
+ req.id.as_deref().unwrap_or(""),
+ req.input,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn prepared_query_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul prepared query").await?;
+ dbx_core::consul::consul_prepared_query_delete_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn prepared_query_execute(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulQueryExecuteApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulPreparedQueryExecuteResponse>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_prepared_query_execute_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn prepared_query_explain(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_prepared_query_explain_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn event_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNameRequest>,
+) -> Result<Json<Vec<dbx_core::consul::ConsulEvent>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_event_list_core(&state.app, &req.connection_id, req.name.as_deref())
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn event_fire(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEventFireApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulEvent>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Fire Consul event").await?;
+ Ok(Json(
+ dbx_core::consul::consul_event_fire_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn coordinate_nodes(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<Vec<dbx_core::consul::ConsulCoordinate>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_coordinate_nodes_core(&state.app, &req.connection_id).await.map_err(AppError::from)?,
+ ))
+}
+pub async fn operator_read(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulOperatorReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulOperatorDocument>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_operator_read_core(&state.app, &req.connection_id, req.kind)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn snapshot_generate(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSnapshot>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_snapshot_generate_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn snapshot_restore(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulSnapshotRestoreApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Restore Consul snapshot").await?;
+ dbx_core::consul::consul_snapshot_restore_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn autopilot_update(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAutopilotApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Update Consul Autopilot").await?;
+ dbx_core::consul::consul_autopilot_update_core(&state.app, &req.connection_id, req.update, &req.confirmation)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn raft_transfer(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulRaftApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Transfer Consul Raft leadership").await?;
+ dbx_core::consul::consul_raft_transfer_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn raft_remove(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulRaftApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Remove Consul Raft peer").await?;
+ dbx_core::consul::consul_raft_remove_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn keyring_write(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulKeyringApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Modify Consul gossip keyring").await?;
+ dbx_core::consul::consul_keyring_write_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+pub async fn license_write(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulLicenseApiRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Update Consul license").await?;
+ dbx_core::consul::consul_license_write_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulReadOptionsRequest {
+ pub connection_id: String,
+ #[serde(default)]
+ pub options: dbx_core::consul::ConsulReadOptions,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulNamedReadRequest {
+ pub connection_id: String,
+ pub name: String,
+ #[serde(default)]
+ pub options: dbx_core::consul::ConsulReadOptions,
+}
+
+pub async fn status_leader(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<String>, AppError> {
+ Ok(Json(dbx_core::consul::consul_status_leader_core(&state.app, &req.connection_id).await.map_err(AppError::from)?))
+}
+
+pub async fn status_peers(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<Vec<String>>, AppError> {
+ Ok(Json(dbx_core::consul::consul_status_peers_core(&state.app, &req.connection_id).await.map_err(AppError::from)?))
+}
+
+pub async fn agent_self(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentIdentity>, AppError> {
+ Ok(Json(dbx_core::consul::consul_agent_self_core(&state.app, &req.connection_id).await.map_err(AppError::from)?))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentMembersRequest {
+ pub connection_id: String,
+ #[serde(default)]
+ pub wan: bool,
+ pub segment: Option<String>,
+}
+
+pub async fn agent_members(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAgentMembersRequest>,
+) -> Result<Json<Vec<dbx_core::consul::ConsulAgentMember>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_agent_members_core(&state.app, &req.connection_id, req.wan, req.segment.as_deref())
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn agent_metrics(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentMetrics>, AppError> {
+ Ok(Json(dbx_core::consul::consul_agent_metrics_core(&state.app, &req.connection_id).await.map_err(AppError::from)?))
+}
+
+pub async fn catalog_datacenters(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<Vec<String>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_catalog_datacenters_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn catalog_nodes(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulReadOptionsRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulCatalogNode>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_catalog_nodes_core(&state.app, &req.connection_id, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn catalog_services(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulReadOptionsRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<std::collections::BTreeMap<String, Vec<String>>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_catalog_services_core(&state.app, &req.connection_id, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn catalog_service_nodes(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulCatalogServiceNode>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_catalog_service_nodes_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn catalog_node_services(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<dbx_core::consul::ConsulNodeServices>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_catalog_node_services_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn health_node(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_health_node_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn health_checks(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_health_checks_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulHealthServiceRequest {
+ pub connection_id: String,
+ pub name: String,
+ pub passing: Option<bool>,
+ #[serde(default)]
+ pub options: dbx_core::consul::ConsulReadOptions,
+}
+
+pub async fn health_service(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulHealthServiceRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulServiceInstance>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_health_service_core(
+ &state.app,
+ &req.connection_id,
+ &req.name,
+ req.passing,
+ req.options,
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn health_state(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_health_state_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn agent_services(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<std::collections::BTreeMap<String, dbx_core::consul::ConsulAgentService>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_agent_services_core(&state.app, &req.connection_id).await.map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentServiceRequest {
+ pub connection_id: String,
+ pub id: String,
+}
+
+pub async fn agent_service(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAgentServiceRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentService>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_agent_service_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn agent_checks(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<std::collections::BTreeMap<String, dbx_core::consul::ConsulHealthCheck>>, AppError> {
+ Ok(Json(dbx_core::consul::consul_agent_checks_core(&state.app, &req.connection_id).await.map_err(AppError::from)?))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentServiceWriteRequest {
+ pub connection_id: String,
+ pub registration: dbx_core::consul::ConsulAgentServiceRegistration,
+}
+
+pub async fn agent_register_service(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAgentServiceWriteRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Register Consul Agent service").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_register_service_core(&state.app, &req.connection_id, req.registration)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn agent_deregister_service(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Deregister Consul Agent service").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_deregister_service_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulMaintenanceRequest {
+ pub connection_id: String,
+ pub id: String,
+ pub enable: bool,
+ pub reason: Option<String>,
+}
+
+pub async fn agent_service_maintenance(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMaintenanceRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Change Consul Agent service maintenance").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_service_maintenance_core(
+ &state.app,
+ &req.connection_id,
+ &req.id,
+ req.enable,
+ req.reason.as_deref(),
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAgentCheckWriteRequest {
+ pub connection_id: String,
+ pub registration: dbx_core::consul::ConsulAgentCheckRegistration,
+}
+
+pub async fn agent_register_check(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAgentCheckWriteRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Register Consul Agent check").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_register_check_core(&state.app, &req.connection_id, req.registration)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn agent_deregister_check(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Deregister Consul Agent check").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_deregister_check_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulTtlUpdateRequest {
+ pub connection_id: String,
+ pub id: String,
+ pub status: dbx_core::consul::ConsulCheckStatus,
+ pub output: Option<String>,
+}
+
+pub async fn agent_update_ttl(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulTtlUpdateRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAgentWriteResult>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Update Consul Agent TTL check").await?;
+ Ok(Json(
+ dbx_core::consul::consul_agent_update_ttl_core(
+ &state.app,
+ &req.connection_id,
+ &req.id,
+ req.status,
+ req.output.as_deref(),
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn sessions(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulReadOptionsRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulSession>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_sessions_core(&state.app, &req.connection_id, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn node_sessions(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulNamedReadRequest>,
+) -> Result<Json<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulSession>>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_node_sessions_core(&state.app, &req.connection_id, &req.name, req.options)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn session(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<Option<dbx_core::consul::ConsulSession>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_session_core(&state.app, &req.connection_id, &req.id).await.map_err(AppError::from)?,
+ ))
+}
+
+pub async fn session_keys(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSessionKeysResponse>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_session_keys_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn session_destroy_impact(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSessionDestroyImpact>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_session_destroy_impact_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionCreateApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulSessionCreateRequest,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulSessionDestroyApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulSessionDestroyRequest,
+}
+
+pub async fn create_session(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulSessionCreateApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSession>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Create Consul Session").await?;
+ Ok(Json(
+ dbx_core::consul::consul_create_session_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn renew_session(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulIdRequest>,
+) -> Result<Json<dbx_core::consul::ConsulSession>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Renew Consul Session").await?;
+ Ok(Json(
+ dbx_core::consul::consul_renew_session_core(&state.app, &req.connection_id, &req.id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn destroy_session(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulSessionDestroyApiRequest>,
+) -> Result<Json<bool>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Destroy Consul Session").await?;
+ Ok(Json(
+ dbx_core::consul::consul_destroy_session_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAcquireLockApiRequest {
+ pub connection_id: String,
+ pub request: dbx_core::consul::ConsulLockRequest,
+}
+
+pub async fn acquire_lock(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAcquireLockApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulLockResponse>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Acquire Consul KV lock").await?;
+ Ok(Json(
+ dbx_core::consul::consul_acquire_lock_core(&state.app, &req.connection_id, req.request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulReleaseLockApiRequest {
+ pub connection_id: String,
+ pub key: String,
+ pub session: String,
+}
+
+pub async fn release_lock(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulReleaseLockApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulLockResponse>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Release Consul KV lock").await?;
+ Ok(Json(
+ dbx_core::consul::consul_release_lock_core(&state.app, &req.connection_id, &req.key, &req.session)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulAclApiRequest {
+ pub connection_id: String,
+ pub kind: Option<dbx_core::consul::ConsulAclKind>,
+ pub id: Option<String>,
+ pub value: Option<dbx_core::consul::ConsulAclWrite>,
+ pub description: Option<String>,
+}
+
+pub async fn acl_token_self(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulConnectionRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclToken>, AppError> {
+ Ok(Json(
+ dbx_core::consul::consul_acl_token_self_core(&state.app, &req.connection_id).await.map_err(AppError::from)?,
+ ))
+}
+pub async fn acl_token_clone(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclToken>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Clone Consul ACL token").await?;
+ let accessor_id = req.id.ok_or_else(|| AppError::from("ACL token AccessorID is required".to_string()))?;
+ let request = dbx_core::consul::ConsulAclTokenClone { description: req.description.unwrap_or_default() };
+ Ok(Json(
+ dbx_core::consul::consul_acl_token_clone_core(&state.app, &req.connection_id, &accessor_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+pub async fn acl_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclList>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("ACL kind is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_acl_list_core(&state.app, &req.connection_id, kind).await.map_err(AppError::from)?,
+ ))
+}
+pub async fn acl_get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclItem>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("ACL kind is required".to_string()))?;
+ let id = req.id.ok_or_else(|| AppError::from("ACL identifier is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_acl_get_core(&state.app, &req.connection_id, kind, &id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn acl_apply(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclItem>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Write Consul ACL resource").await?;
+ let value = req.value.ok_or_else(|| AppError::from("ACL value is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_acl_apply_core(&state.app, &req.connection_id, req.id.as_deref(), value)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn acl_references(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclReferences>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("ACL kind is required".to_string()))?;
+ let id = req.id.ok_or_else(|| AppError::from("ACL identifier is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_acl_references_core(&state.app, &req.connection_id, kind, &id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn acl_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulAclApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulAclReferences>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul ACL resource").await?;
+ let kind = req.kind.ok_or_else(|| AppError::from("ACL kind is required".to_string()))?;
+ let id = req.id.ok_or_else(|| AppError::from("ACL identifier is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_acl_delete_core(&state.app, &req.connection_id, kind, &id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulEnterpriseApiRequest {
+ pub connection_id: String,
+ pub kind: Option<dbx_core::consul::ConsulEnterpriseKind>,
+ pub name: Option<String>,
+ pub existing_name: Option<String>,
+ pub item: Option<dbx_core::consul::ConsulEnterpriseWrite>,
+}
+pub async fn enterprise_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEnterpriseApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulEnterpriseList>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("Enterprise kind is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_enterprise_list_core(&state.app, &req.connection_id, kind)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn enterprise_get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEnterpriseApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulEnterpriseItem>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("Enterprise kind is required".to_string()))?;
+ let name = req.name.ok_or_else(|| AppError::from("Enterprise resource name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_enterprise_get_core(&state.app, &req.connection_id, kind, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn enterprise_apply(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEnterpriseApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulEnterpriseItem>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Write Consul Enterprise scope").await?;
+ let item = req.item.ok_or_else(|| AppError::from("Enterprise resource is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_enterprise_apply_core(
+ &state.app,
+ &req.connection_id,
+ req.existing_name.as_deref(),
+ item,
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn enterprise_impact(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEnterpriseApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulScopeImpact>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("Enterprise kind is required".to_string()))?;
+ let name = req.name.ok_or_else(|| AppError::from("Enterprise resource name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_enterprise_impact_core(&state.app, &req.connection_id, kind, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn enterprise_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulEnterpriseApiRequest>,
+) -> Result<Json<dbx_core::consul::ConsulScopeImpact>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul Enterprise scope").await?;
+ let kind = req.kind.ok_or_else(|| AppError::from("Enterprise kind is required".to_string()))?;
+ let name = req.name.ok_or_else(|| AppError::from("Enterprise resource name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::consul_enterprise_delete_core(&state.app, &req.connection_id, kind, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulMeshConfigApiRequest {
+ pub connection_id: String,
+ pub kind: Option<String>,
+ pub name: Option<String>,
+ pub expected_modify_index: Option<u64>,
+ pub request: Option<dbx_core::consul::mesh::ConsulConfigEntryApply>,
+ pub raw: Option<serde_json::Value>,
+}
+pub async fn mesh_config_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshConfigApiRequest>,
+) -> Result<Json<Vec<dbx_core::consul::mesh::ConsulConfigEntry>>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("Config kind is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_config_list_core(&state.app, &req.connection_id, &kind)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_config_get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshConfigApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulConfigEntry>, AppError> {
+ let kind = req.kind.ok_or_else(|| AppError::from("Config kind is required".to_string()))?;
+ let name = req.name.ok_or_else(|| AppError::from("Config name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_config_get_core(&state.app, &req.connection_id, &kind, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_config_apply(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshConfigApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulConfigEntry>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Write Consul Service Mesh config entry").await?;
+ let request = req.request.ok_or_else(|| AppError::from("Config request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_config_apply_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_config_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshConfigApiRequest>,
+) -> Result<Json<bool>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul Service Mesh config entry").await?;
+ let kind = req.kind.ok_or_else(|| AppError::from("Config kind is required".to_string()))?;
+ let name = req.name.ok_or_else(|| AppError::from("Config name is required".to_string()))?;
+ let index =
+ req.expected_modify_index.ok_or_else(|| AppError::from("Expected ModifyIndex is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_config_delete_core(&state.app, &req.connection_id, &kind, &name, index)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsulMeshApiRequest {
+ pub connection_id: String,
+ pub id: Option<String>,
+ pub name: Option<String>,
+ pub service: Option<String>,
+ pub intention: Option<dbx_core::consul::mesh::ConsulIntention>,
+ pub exact_request: Option<dbx_core::consul::mesh::ConsulIntentionExactRequest>,
+ pub match_request: Option<dbx_core::consul::mesh::ConsulIntentionMatchRequest>,
+ pub check_request: Option<dbx_core::consul::mesh::ConsulIntentionCheckRequest>,
+ pub generate_request: Option<dbx_core::consul::mesh::ConsulPeeringGenerateRequest>,
+ pub establish_request: Option<dbx_core::consul::mesh::ConsulPeeringEstablishRequest>,
+}
+pub async fn mesh_intentions_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<Vec<dbx_core::consul::mesh::ConsulIntention>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intentions_list_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulIntention>, AppError> {
+ let id = req.id.ok_or_else(|| AppError::from("Intention ID is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_get_core(&state.app, &req.connection_id, &id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_get_exact(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulIntention>, AppError> {
+ let request = req.exact_request.ok_or_else(|| AppError::from("Exact intention request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_get_exact_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_upsert(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulIntention>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Write Consul intention").await?;
+ let item = req.intention.ok_or_else(|| AppError::from("Intention is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_upsert_core(&state.app, &req.connection_id, item)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<bool>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul intention").await?;
+ let id = req.id.ok_or_else(|| AppError::from("Intention ID is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_delete_core(&state.app, &req.connection_id, &id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_delete_exact(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<bool>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete exact Consul intention").await?;
+ let request = req.exact_request.ok_or_else(|| AppError::from("Exact intention request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_delete_exact_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_match(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<Vec<dbx_core::consul::mesh::ConsulIntention>>, AppError> {
+ let request = req.match_request.ok_or_else(|| AppError::from("Intention match request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_match_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_intention_check(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulIntentionCheckResponse>, AppError> {
+ let request = req.check_request.ok_or_else(|| AppError::from("Intention check request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_intention_check_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_discovery_chain(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulDiscoveryChain>, AppError> {
+ let service = req.service.ok_or_else(|| AppError::from("Service is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_discovery_chain_core(&state.app, &req.connection_id, &service)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_peering_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<Vec<dbx_core::consul::mesh::ConsulPeering>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_peering_list_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_peering_get(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulPeering>, AppError> {
+ let name = req.name.ok_or_else(|| AppError::from("Peering name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_peering_get_core(&state.app, &req.connection_id, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_peering_generate_token(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulPeeringToken>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Generate Consul peering token").await?;
+ let request =
+ req.generate_request.ok_or_else(|| AppError::from("Peering token request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_peering_generate_token_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_peering_establish(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulPeering>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Establish Consul peering").await?;
+ let request =
+ req.establish_request.ok_or_else(|| AppError::from("Peering establish request is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_peering_establish_core(&state.app, &req.connection_id, request)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_peering_delete(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<bool>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete Consul peering").await?;
+ let name = req.name.ok_or_else(|| AppError::from("Peering name is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_peering_delete_core(&state.app, &req.connection_id, &name)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_exported_services_list(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshApiRequest>,
+) -> Result<Json<Vec<dbx_core::consul::mesh::ConsulExportedService>>, AppError> {
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_exported_services_list_core(&state.app, &req.connection_id)
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
+pub async fn mesh_exported_services_apply(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<ConsulMeshConfigApiRequest>,
+) -> Result<Json<dbx_core::consul::mesh::ConsulConfigEntry>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Write Consul exported services").await?;
+ let name = req.name.ok_or_else(|| AppError::from("Exported services name is required".to_string()))?;
+ let index =
+ req.expected_modify_index.ok_or_else(|| AppError::from("Expected ModifyIndex is required".to_string()))?;
+ let raw = req.raw.ok_or_else(|| AppError::from("Raw exported-services JSON is required".to_string()))?;
+ Ok(Json(
+ dbx_core::consul::mesh::consul_mesh_exported_services_apply_core(
+ &state.app,
+ &req.connection_id,
+ &name,
+ index,
+ raw,
+ )
+ .await
+ .map_err(AppError::from)?,
+ ))
+}
diff --git a/crates/dbx-web/src/routes/mod.rs b/crates/dbx-web/src/routes/mod.rs
index 8a715cf098..47d3fa747b 100644
--- a/crates/dbx-web/src/routes/mod.rs
+++ b/crates/dbx-web/src/routes/mod.rs
@@ -3,6 +3,7 @@ pub mod ai;
pub mod app_settings;
pub mod cloud_sync;
pub mod connection;
+pub mod consul;
pub mod data_compare;
pub mod database_export;
pub mod dialect;
diff --git a/docs/content/docs/databases.cn.mdx b/docs/content/docs/databases.cn.mdx
index 318477379e..8eb4ab5215 100644
--- a/docs/content/docs/databases.cn.mdx
+++ b/docs/content/docs/databases.cn.mdx
@@ -34,7 +34,7 @@ Desktop 的文件路径属于本机。Docker/Web 的文件路径属于服务器
- Qdrant、Milvus、Weaviate、ChromaDB
- HBase
- Pulsar、Kafka、RocketMQ、RabbitMQ
-- etcd、ZooKeeper、Nacos
+- etcd、ZooKeeper、Nacos、Consul KV
- InfluxDB、IoTDB、TDengine 和其它时序/IoT profile
这些连接使用键值、文档、搜索、向量、消息或配置中心工作区,不应套用关系型表格和 SQL 的全部概念。入口详见 [专用工作区](/cn/docs/specialized-workspaces)。
diff --git a/docs/content/docs/databases.mdx b/docs/content/docs/databases.mdx
index 5400501946..bfe72c760a 100644
--- a/docs/content/docs/databases.mdx
+++ b/docs/content/docs/databases.mdx
@@ -34,7 +34,7 @@ Desktop file paths belong to the local computer. Docker/Web paths belong to the
- Qdrant, Milvus, Weaviate, and ChromaDB
- HBase
- Pulsar, Kafka, RocketMQ, and RabbitMQ
-- etcd, ZooKeeper, and Nacos
+- etcd, ZooKeeper, Nacos, and Consul KV
- InfluxDB, IoTDB, TDengine, and other time-series or IoT profiles
These connections use key-value, document, search, vector, messaging, or configuration-center workspaces. They do not inherit every relational grid or SQL concept. See [Specialized Workspaces](/en/docs/specialized-workspaces).
diff --git a/docs/content/docs/specialized-workspaces.cn.mdx b/docs/content/docs/specialized-workspaces.cn.mdx
index d9fa99ef59..6f215a0ab3 100644
--- a/docs/content/docs/specialized-workspaces.cn.mdx
+++ b/docs/content/docs/specialized-workspaces.cn.mdx
@@ -1,9 +1,9 @@
---
title: 专项工作台
-description: 使用 DBX 管理 Redis、MongoDB、搜索与向量数据库、HBase、消息队列、etcd、ZooKeeper 和 Nacos。
+description: 使用 DBX 管理 Redis、MongoDB、搜索与向量数据库、HBase、消息队列、etcd、ZooKeeper、Nacos 和 Consul KV。
---
-除了 SQL 编辑器和数据表格,DBX 还会根据连接类型打开专项工作台。它们直接使用对应系统的对象模型和管理 API,例如 Redis Key、MongoDB 文档、向量集合、消息队列 Topic、etcd Key、ZooKeeper ZNode 和 Nacos 配置。
+除了 SQL 编辑器和数据表格,DBX 还会根据连接类型打开专项工作台。它们直接使用对应系统的对象模型和管理 API,例如 Redis Key、MongoDB 文档、向量集合、消息队列 Topic、etcd Key、ZooKeeper ZNode、Nacos 配置和 Consul KV。
<Callout type="info">专项能力按数据库类型、服务端版本、驱动和当前账号权限动态开放。界面没有显示某个入口时,先查看 [数据库支持](/cn/docs/databases)、连接测试结果和账号权限。</Callout>
@@ -16,7 +16,7 @@ description: 使用 DBX 管理 Redis、MongoDB、搜索与向量数据库、HBas
| 向量数据库 | Qdrant、Milvus、Weaviate、ChromaDB | Collection 浏览、向量检索、Upsert、删除和请求预览 |
| 宽表与列族 | HBase | Namespace、表结构、Column Family 和行数据浏览 |
| 消息队列 | Pulsar、Kafka、RocketMQ、RabbitMQ | Topic、订阅/消费者、消息、监控、权限、策略和管理 API |
-| 注册与配置中心 | etcd、ZooKeeper、Nacos | Key/ZNode、集群状态、访问控制、配置、服务和实例 |
+| 注册与配置中心 | etcd、ZooKeeper、Nacos、Consul | Key/ZNode、集群状态、访问控制、配置、服务和实例 |
| 运行状态 | MySQL、PostgreSQL、Redis、etcd、Nacos 等 | Dashboard、进程/会话、指标和数据库专属管理视图 |
## Redis 与 MongoDB
@@ -81,7 +81,7 @@ Pulsar、Kafka、RocketMQ 和 RabbitMQ 共用消息队列控制台框架,但
<Callout type="info">消息队列面板根据 Agent 返回的 capability 动态显示。服务端版本、管理 API、账号权限或未配置的管理端口都可能让某些标签页不可用。</Callout>
-## etcd、ZooKeeper 与 Nacos
+## etcd、ZooKeeper、Nacos 与 Consul
### etcd
@@ -103,6 +103,20 @@ Nacos 工作台覆盖配置和服务两个主要视图,并可管理 Namespace
Nacos 的配置历史可能依赖额外的控制台地址和凭据。连接成功但历史入口不可用时,检查连接表单中的控制台设置。
+### Consul
+
+Consul 工作台按需加载概览、KV、服务、健康检查、Session、ACL、作用域、Service Mesh、工具和 Operator 领域。能力探测会区分 supported、unsupported、forbidden 和 unknown,因此单个领域权限不足不会清空其他已经加载的数据。
+
+连接项支持 HTTP/HTTPS API 地址、ACL Token、Datacenter、Namespace、Admin Partition、读取一致性、CA 证书、mTLS 客户端身份、跳过证书校验、超时和 DBX Transport Layer。Agent Service/Check 写入还必须配置并验证明确的 Agent target;经过负载均衡而目标不明确时,DBX 会硬性拒绝写入。
+
+KV 已支持递归搜索、版本化前缀导出、不可变导入预览、CAS 冲突处理、事务、原子重命名/复制、受限事务前缀删除和可取消的 Blocking Query Watch。Consul 单事务最多 64 个操作;更大的导入和删除会按确定顺序分批,并明确标记跨批次不具备整体原子性。跨连接或跨 Datacenter 迁移是 DBX 客户端读写流程,不是 Consul 原生复制。
+
+Catalog 与 Health 保持只读浏览。Agent Service/Check、Session/Lock、ACL Token/Policy/Role、Enterprise Namespace/Partition 和 Service Mesh 使用各自领域 DTO 与确认流程。ACL Secret 和 Peering Token 作为一次性敏感值处理,不进入 Consul 前端缓存或普通导出格式。
+
+Prepared Query、Event 和 Coordinate 位于工具区。Operator 读取和 Snapshot 下载为实验性能力。Snapshot 恢复、Autopilot 修改、Raft 修改、Keyring 修改和 License 修改分别由默认关闭的独立开关控制,启用一个不会连带启用其他能力。
+
+<Callout type="warn">Consul 不提供单 Key 历史 API,也不提供原生跨 Datacenter KV 复制 API。`ModifyIndex`、Blocking Index 和 Snapshot 都不会被包装成 Key 历史。Enterprise 与 Operator 能力取决于 Consul 版本、Edition、Agent 角色、ACL 权限和显式启用的 DBX 安全设置。</Callout>
+
## Dashboard 与管理视图
部分连接会在对象树或标签页中提供运行状态页面,例如:
diff --git a/docs/content/docs/specialized-workspaces.mdx b/docs/content/docs/specialized-workspaces.mdx
index 21e4810bcc..74d2e79a7f 100644
--- a/docs/content/docs/specialized-workspaces.mdx
+++ b/docs/content/docs/specialized-workspaces.mdx
@@ -1,9 +1,9 @@
---
title: Specialized Workspaces
-description: Manage Redis, MongoDB, search and vector databases, HBase, message queues, etcd, ZooKeeper, and Nacos in DBX.
+description: Manage Redis, MongoDB, search and vector databases, HBase, message queues, etcd, ZooKeeper, Nacos, and Consul KV in DBX.
---
-In addition to the SQL editor and data grid, DBX opens specialized workspaces for specific connection types. These interfaces use each system's native object model and management APIs, including Redis keys, MongoDB documents, vector collections, message queue topics, etcd keys, ZooKeeper ZNodes, and Nacos configurations.
+In addition to the SQL editor and data grid, DBX opens specialized workspaces for specific connection types. These interfaces use each system's native object model and management APIs, including Redis keys, MongoDB documents, vector collections, message queue topics, etcd keys, ZooKeeper ZNodes, Nacos configurations, and Consul KV entries.
<Callout type="info">Specialized capabilities are enabled dynamically based on database type, server version, driver, and account privileges. If an entry point is missing, check [Database Support](/en/docs/databases), the connection test result, and server permissions.</Callout>
@@ -16,7 +16,7 @@ In addition to the SQL editor and data grid, DBX opens specialized workspaces fo
| Vector databases | Qdrant, Milvus, Weaviate, ChromaDB | Collection browsing, vector search, upsert, delete, and request preview |
| Wide-column and column family | HBase | Namespaces, table structure, column families, and row data |
| Message queues | Pulsar, Kafka, RocketMQ, RabbitMQ | Topics, subscriptions or consumers, messages, monitoring, permissions, policies, and admin APIs |
-| Registry and configuration | etcd, ZooKeeper, Nacos | Keys/ZNodes, cluster status, access control, configuration, services, and instances |
+| Registry and configuration | etcd, ZooKeeper, Nacos, Consul | Keys/ZNodes, cluster status, access control, configuration, services, and instances |
| Runtime status | MySQL, PostgreSQL, Redis, etcd, Nacos, and others | Dashboards, processes or sessions, metrics, and database-specific administration views |
## Redis and MongoDB
@@ -81,7 +81,7 @@ Pulsar emphasizes tenants, namespaces, and subscriptions; Kafka uses topics, con
<Callout type="info">Message queue panels are capability-driven. Server versions, management APIs, account privileges, or a missing management port can make individual tabs unavailable.</Callout>
-## etcd, ZooKeeper, and Nacos
+## etcd, ZooKeeper, Nacos, and Consul
### etcd
@@ -103,6 +103,20 @@ The Nacos workspace covers configuration and services and can also manage namesp
Configuration history can require an additional console URL and credentials. If the connection works but history is unavailable, check the console settings in the connection form.
+### Consul
+
+The Consul workspace is split into independently loaded Overview, KV, Services, Health, Sessions, ACL, Scope, Service Mesh, Tools, and Operator domains. Capability probes distinguish supported, unsupported, forbidden, and unknown endpoints, so a permission failure in one domain does not clear data loaded by another.
+
+Connections accept an HTTP or HTTPS API address, ACL Token, Datacenter, Namespace, Admin Partition, read consistency, CA certificate, mTLS identity, certificate-verification override, timeout, and DBX Transport Layer. Agent Service and Check writes additionally require a verified, explicit Agent target; DBX refuses those writes when a load balancer makes the target ambiguous.
+
+KV supports recursive search, versioned prefix export, immutable import preview, CAS conflict handling, transactions, atomic rename/copy, bounded transactional prefix deletion, and cancellable blocking-query Watch. Consul transactions are limited to 64 operations; larger imports and deletes are deterministically split and explicitly reported as non-atomic across batches. Cross-connection or cross-Datacenter migration is a DBX client read/write workflow, not native Consul replication.
+
+Catalog and Health remain read-only discovery views. Agent Service/Check, Session/Lock, ACL Token/Policy/Role, Enterprise Namespace/Partition, and Service Mesh resources use domain-specific DTOs and confirmations. ACL secrets and peering tokens are treated as one-time sensitive values and are not stored in the Consul frontend cache or normal export formats.
+
+Prepared Query, Event, and Coordinate are available under Tools. Operator reads and snapshot download are experimental. Snapshot restore, Autopilot updates, Raft changes, Keyring changes, and License updates are disabled by default with separate feature switches; enabling one does not enable another.
+
+<Callout type="warn">Consul has no per-Key history API and no native cross-Datacenter KV replication API. `ModifyIndex`, blocking indexes, and snapshots are not presented as Key history. Enterprise and Operator availability depends on Consul edition, version, Agent role, ACL policy, and explicitly enabled DBX safety settings.</Callout>
+
## Dashboards and Administration Views
Some connections expose runtime status pages from the object tree or a tab, including:
diff --git a/packages/app-tests/i18nAutofillParser.test.ts b/packages/app-tests/i18nAutofillParser.test.ts
index 64de2281ae..398028a9e3 100644
--- a/packages/app-tests/i18nAutofillParser.test.ts
+++ b/packages/app-tests/i18nAutofillParser.test.ts
@@ -7,5 +7,7 @@ test("i18n autofill parses locale roots with imported shorthand sections", () =>
encoding: "utf8",
});
- assert.match(output, /(?:No new zh-CN i18n keys compared with HEAD|Found \d+ new zh-CN i18n key\(s\):)/);
+ // Accept every "no new keys / no changes needed" wording used across
+ // recent PRs (e.g. mongo-clone, consul) plus the "found N new keys" path.
+ assert.match(output, /(?:No new zh-CN i18n keys compared with HEAD|Found \d+ new zh-CN i18n key\(s\):|No locale files needed changes)/);
});
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 99d487a1a9..c2ef4be664 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -1092,6 +1092,27 @@ async fn test_connection_with_info_inner(
adapter.test_connection().await?;
Ok("Connection successful".to_string())
}
+ DatabaseType::Consul => {
+ let mut consul_config = dbx_core::consul::ConsulConfig::from_connection(&config)?;
+ let validate_agent_target = consul_config.agent_target.is_some();
+ let original_host = consul_config.base_url.host_str().unwrap_or_default();
+ let original_port = consul_config.base_url.port_or_known_default().unwrap_or(config.port);
+ if host != original_host || port != original_port {
+ consul_config = consul_config.with_connect_override(&host, port);
+ }
+ let client = dbx_core::consul::ConsulClient::new(consul_config).await?;
+ client.probe().await?;
+ let identity = if validate_agent_target {
+ Some(client.validate_configured_agent_target().await?)
+ } else {
+ client.agent_self().await.ok()
+ };
+ Ok(identity
+ .map(|identity| format!("Connection successful (Agent: {} at {})", identity.node, identity.address))
+ .unwrap_or_else(|| {
+ "Connection successful (Agent identity unavailable; Agent writes disabled)".to_string()
+ }))
+ }
#[cfg(feature = "mq-admin")]
DatabaseType::MessageQueue => {
// Probe with a transient adapter so Test Connection never retains/replaces
@@ -1435,6 +1456,17 @@ pub async fn connect_db(
adapter.test_connection().await?;
PoolKind::Nacos
}
+ DatabaseType::Consul => {
+ let mut consul_config = dbx_core::consul::ConsulConfig::from_connection(&db_config)?;
+ let original_host = consul_config.base_url.host_str().unwrap_or_default();
+ let original_port = consul_config.base_url.port_or_known_default().unwrap_or(db_config.port);
+ if host != original_host || port != original_port {
+ consul_config = consul_config.with_connect_override(&host, port);
+ }
+ let client = dbx_core::consul::ConsulClient::new(consul_config).await?;
+ client.probe().await?;
+ PoolKind::Consul(client)
+ }
#[cfg(feature = "mq-admin")]
DatabaseType::MessageQueue => {
let mqc = state.mq_admin_config_for_connection(&id, &config).await?;
diff --git a/src-tauri/src/commands/consul_cmd.rs b/src-tauri/src/commands/consul_cmd.rs
new file mode 100644
index 0000000000..b010b0386e
--- /dev/null
+++ b/src-tauri/src/commands/consul_cmd.rs
@@ -0,0 +1,1017 @@
+use std::sync::Arc;
+
+use serde::Serialize;
+use tauri::{AppHandle, Emitter, State};
+
+use crate::commands::connection::{ensure_connection_writable, AppState};
+use dbx_core::agent_kv::{
+ KvDeleteOptions, KvDeleteResponse, KvGetResponse, KvListPrefixResponse, KvPutOptions, KvPutResponse, KvValue,
+};
+
+#[tauri::command]
+pub async fn consul_capabilities(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<dbx_core::consul::ConsulCapabilities, String> {
+ dbx_core::consul::consul_capabilities_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_list_prefix(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ prefix: String,
+ limit: usize,
+ continuation: Option<String>,
+) -> Result<KvListPrefixResponse, String> {
+ dbx_core::consul::consul_list_prefix_core(&state, &connection_id, &prefix, limit, continuation.as_deref()).await
+}
+
+#[tauri::command]
+pub async fn consul_list_recursive(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ prefix: String,
+ max_entries: usize,
+ max_value_bytes: usize,
+) -> Result<dbx_core::consul::ConsulRecursiveListResponse, String> {
+ dbx_core::consul::consul_list_recursive_core(&state, &connection_id, &prefix, max_entries, max_value_bytes).await
+}
+
+#[tauri::command]
+pub async fn consul_search(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulSearchRequest,
+) -> Result<dbx_core::consul::ConsulSearchResponse, String> {
+ dbx_core::consul::consul_search_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_search_progress(
+ connection_id: String,
+ request_id: String,
+ scope: dbx_core::consul::ConsulScope,
+ generation: u64,
+) -> Result<dbx_core::consul::ConsulSearchProgress, String> {
+ Ok(dbx_core::consul::consul_search_progress_core(&connection_id, &scope, generation, &request_id))
+}
+
+#[tauri::command]
+pub async fn consul_cancel_search(
+ connection_id: String,
+ request_id: String,
+ scope: dbx_core::consul::ConsulScope,
+ generation: u64,
+) -> Result<bool, String> {
+ Ok(dbx_core::consul::consul_cancel_search_core(&connection_id, &scope, generation, &request_id))
+}
+
+#[tauri::command]
+pub async fn consul_txn(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulTxnRequest,
+) -> Result<dbx_core::consul::ConsulTxnResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Execute Consul transaction").await?;
+ dbx_core::consul::consul_txn_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_rename_key(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ source: String,
+ target: String,
+ expected_modify_index: dbx_core::agent_kv::KvInt64,
+ copy: bool,
+) -> Result<dbx_core::consul::ConsulTxnResult, String> {
+ dbx_core::consul::consul_rename_key_core(&state, &connection_id, &source, &target, expected_modify_index, copy)
+ .await
+}
+
+#[tauri::command]
+pub async fn consul_blocking_query(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulBlockingRequest,
+) -> Result<dbx_core::consul::ConsulBlockingResponse, String> {
+ dbx_core::consul::consul_blocking_query_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_domain_watch(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulDomainWatchRequest,
+) -> Result<dbx_core::consul::ConsulDomainWatchResponse, String> {
+ dbx_core::consul::consul_domain_watch_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_cancel_blocking(
+ connection_id: String,
+ scope: dbx_core::consul::ConsulScope,
+ generation: u64,
+ operation_id: String,
+) -> Result<bool, String> {
+ Ok(dbx_core::consul::consul_cancel_blocking_core(&connection_id, &scope, generation, &operation_id))
+}
+
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ConsulWatchEvent {
+ connection_id: String,
+ operation_id: String,
+ generation: u64,
+ result: Option<dbx_core::consul::ConsulBlockingResponse>,
+ error: Option<String>,
+}
+
+#[tauri::command]
+pub async fn consul_watch_start(
+ app: AppHandle,
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulBlockingRequest,
+) -> Result<String, String> {
+ let operation_id = request.operation_id.clone();
+ let event_operation_id = operation_id.clone();
+ let generation = request.generation;
+ let app_state = Arc::clone(state.inner());
+ tauri::async_runtime::spawn(async move {
+ let response = dbx_core::consul::consul_blocking_query_core(&app_state, &connection_id, request).await;
+ let event = match response {
+ Ok(result) => ConsulWatchEvent {
+ connection_id,
+ operation_id: event_operation_id,
+ generation,
+ result: Some(result),
+ error: None,
+ },
+ Err(error) => ConsulWatchEvent {
+ connection_id,
+ operation_id: event_operation_id,
+ generation,
+ result: None,
+ error: Some(error),
+ },
+ };
+ let _ = app.emit("consul-watch", event);
+ });
+ Ok(operation_id)
+}
+
+#[tauri::command]
+pub async fn consul_export_bundle(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulExportRequest,
+) -> Result<dbx_core::consul::ConsulKvBundle, String> {
+ dbx_core::consul::consul_export_bundle_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_import_preview(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulImportRequest,
+) -> Result<dbx_core::consul::ConsulImportPreview, String> {
+ dbx_core::consul::consul_import_preview_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_import_execute(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulImportRequest,
+) -> Result<dbx_core::consul::ConsulImportReport, String> {
+ ensure_connection_writable(&state, &connection_id, "Import Consul KV bundle").await?;
+ dbx_core::consul::consul_import_execute_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_delete_prefix_preview(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ prefix: String,
+) -> Result<dbx_core::consul::ConsulDeletePrefixPreview, String> {
+ dbx_core::consul::consul_delete_prefix_preview_core(&state, &connection_id, &prefix).await
+}
+
+#[tauri::command]
+pub async fn consul_delete_prefix_execute(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulDeletePrefixRequest,
+) -> Result<dbx_core::consul::ConsulDeletePrefixReport, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul KV prefix").await?;
+ dbx_core::consul::consul_delete_prefix_execute_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ key: String,
+) -> Result<KvGetResponse, String> {
+ dbx_core::consul::consul_get_core(&state, &connection_id, &key).await
+}
+
+#[tauri::command]
+pub async fn consul_put(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ key: String,
+ value: KvValue,
+ options: Option<KvPutOptions>,
+) -> Result<KvPutResponse, String> {
+ ensure_connection_writable(&state, &connection_id, "Put Consul KV key").await?;
+ dbx_core::consul::consul_put_core(&state, &connection_id, &key, value, options.unwrap_or_default()).await
+}
+
+#[tauri::command]
+pub async fn consul_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ key: String,
+ options: Option<KvDeleteOptions>,
+) -> Result<KvDeleteResponse, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul KV key").await?;
+ dbx_core::consul::consul_delete_core(&state, &connection_id, &key, options.unwrap_or_default()).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<dbx_core::consul::ConsulPreparedQuery>, String> {
+ dbx_core::consul::consul_prepared_query_list_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_read(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulPreparedQuery, String> {
+ dbx_core::consul::consul_prepared_query_read_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_create(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ input: dbx_core::consul::ConsulPreparedQueryInput,
+) -> Result<String, String> {
+ ensure_connection_writable(&state, &connection_id, "Create Consul prepared query").await?;
+ dbx_core::consul::consul_prepared_query_create_core(&state, &connection_id, input).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_update(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+ input: dbx_core::consul::ConsulPreparedQueryInput,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Update Consul prepared query").await?;
+ dbx_core::consul::consul_prepared_query_update_core(&state, &connection_id, &id, input).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul prepared query").await?;
+ dbx_core::consul::consul_prepared_query_delete_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_execute(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulPreparedQueryExecuteRequest,
+) -> Result<dbx_core::consul::ConsulPreparedQueryExecuteResponse, String> {
+ dbx_core::consul::consul_prepared_query_execute_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_prepared_query_explain(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ query: String,
+) -> Result<serde_json::Value, String> {
+ dbx_core::consul::consul_prepared_query_explain_core(&state, &connection_id, &query).await
+}
+
+#[tauri::command]
+pub async fn consul_event_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ name: Option<String>,
+) -> Result<Vec<dbx_core::consul::ConsulEvent>, String> {
+ dbx_core::consul::consul_event_list_core(&state, &connection_id, name.as_deref()).await
+}
+
+#[tauri::command]
+pub async fn consul_event_fire(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulEventFireRequest,
+) -> Result<dbx_core::consul::ConsulEvent, String> {
+ ensure_connection_writable(&state, &connection_id, "Fire Consul event").await?;
+ dbx_core::consul::consul_event_fire_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_coordinate_nodes(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<dbx_core::consul::ConsulCoordinate>, String> {
+ dbx_core::consul::consul_coordinate_nodes_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_operator_read(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulOperatorReadKind,
+) -> Result<dbx_core::consul::ConsulOperatorDocument, String> {
+ dbx_core::consul::consul_operator_read_core(&state, &connection_id, kind).await
+}
+
+#[tauri::command]
+pub async fn consul_snapshot_generate(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<dbx_core::consul::ConsulSnapshot, String> {
+ dbx_core::consul::consul_snapshot_generate_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_snapshot_restore(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulSnapshotRestoreRequest,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Restore Consul snapshot").await?;
+ dbx_core::consul::consul_snapshot_restore_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_autopilot_update(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ update: dbx_core::consul::ConsulAutopilotUpdate,
+ confirmation: String,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Update Consul Autopilot").await?;
+ dbx_core::consul::consul_autopilot_update_core(&state, &connection_id, update, &confirmation).await
+}
+
+#[tauri::command]
+pub async fn consul_raft_transfer(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulRaftWriteRequest,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Transfer Consul Raft leadership").await?;
+ dbx_core::consul::consul_raft_transfer_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_raft_remove(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulRaftWriteRequest,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Remove Consul Raft peer").await?;
+ dbx_core::consul::consul_raft_remove_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_keyring_write(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulKeyringWriteRequest,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Modify Consul gossip keyring").await?;
+ dbx_core::consul::consul_keyring_write_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_license_write(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulLicenseWriteRequest,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Update Consul license").await?;
+ dbx_core::consul::consul_license_write_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_status_leader(state: State<'_, Arc<AppState>>, connection_id: String) -> Result<String, String> {
+ dbx_core::consul::consul_status_leader_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_status_peers(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<String>, String> {
+ dbx_core::consul::consul_status_peers_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_self(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<dbx_core::consul::ConsulAgentIdentity, String> {
+ dbx_core::consul::consul_agent_self_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_members(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ wan: bool,
+ segment: Option<String>,
+) -> Result<Vec<dbx_core::consul::ConsulAgentMember>, String> {
+ dbx_core::consul::consul_agent_members_core(&state, &connection_id, wan, segment.as_deref()).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_metrics(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<dbx_core::consul::ConsulAgentMetrics, String> {
+ dbx_core::consul::consul_agent_metrics_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_catalog_datacenters(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<String>, String> {
+ dbx_core::consul::consul_catalog_datacenters_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_catalog_nodes(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulCatalogNode>>, String> {
+ dbx_core::consul::consul_catalog_nodes_core(&state, &connection_id, options).await
+}
+
+#[tauri::command]
+pub async fn consul_catalog_services(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<std::collections::BTreeMap<String, Vec<String>>>, String> {
+ dbx_core::consul::consul_catalog_services_core(&state, &connection_id, options).await
+}
+
+#[tauri::command]
+pub async fn consul_catalog_service_nodes(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ service: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulCatalogServiceNode>>, String> {
+ dbx_core::consul::consul_catalog_service_nodes_core(&state, &connection_id, &service, options).await
+}
+
+#[tauri::command]
+pub async fn consul_catalog_node_services(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ node: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<dbx_core::consul::ConsulNodeServices>, String> {
+ dbx_core::consul::consul_catalog_node_services_core(&state, &connection_id, &node, options).await
+}
+
+#[tauri::command]
+pub async fn consul_health_node(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ node: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>, String> {
+ dbx_core::consul::consul_health_node_core(&state, &connection_id, &node, options).await
+}
+
+#[tauri::command]
+pub async fn consul_health_checks(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ service: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>, String> {
+ dbx_core::consul::consul_health_checks_core(&state, &connection_id, &service, options).await
+}
+
+#[tauri::command]
+pub async fn consul_health_service(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ service: String,
+ passing: Option<bool>,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulServiceInstance>>, String> {
+ dbx_core::consul::consul_health_service_core(&state, &connection_id, &service, passing, options).await
+}
+
+#[tauri::command]
+pub async fn consul_health_state(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ health_state: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulHealthCheck>>, String> {
+ dbx_core::consul::consul_health_state_core(&state, &connection_id, &health_state, options).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_services(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<std::collections::BTreeMap<String, dbx_core::consul::ConsulAgentService>, String> {
+ dbx_core::consul::consul_agent_services_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_service(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAgentService, String> {
+ dbx_core::consul::consul_agent_service_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_checks(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<std::collections::BTreeMap<String, dbx_core::consul::ConsulHealthCheck>, String> {
+ dbx_core::consul::consul_agent_checks_core(&state, &connection_id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_register_service(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ registration: dbx_core::consul::ConsulAgentServiceRegistration,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Register Consul Agent service").await?;
+ dbx_core::consul::consul_agent_register_service_core(&state, &connection_id, registration).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_deregister_service(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Deregister Consul Agent service").await?;
+ dbx_core::consul::consul_agent_deregister_service_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_service_maintenance(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+ enable: bool,
+ reason: Option<String>,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Change Consul Agent service maintenance").await?;
+ dbx_core::consul::consul_agent_service_maintenance_core(&state, &connection_id, &id, enable, reason.as_deref())
+ .await
+}
+
+#[tauri::command]
+pub async fn consul_agent_register_check(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ registration: dbx_core::consul::ConsulAgentCheckRegistration,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Register Consul Agent check").await?;
+ dbx_core::consul::consul_agent_register_check_core(&state, &connection_id, registration).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_deregister_check(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Deregister Consul Agent check").await?;
+ dbx_core::consul::consul_agent_deregister_check_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_agent_update_ttl(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+ status: dbx_core::consul::ConsulCheckStatus,
+ output: Option<String>,
+) -> Result<dbx_core::consul::ConsulAgentWriteResult, String> {
+ ensure_connection_writable(&state, &connection_id, "Update Consul Agent TTL check").await?;
+ dbx_core::consul::consul_agent_update_ttl_core(&state, &connection_id, &id, status, output.as_deref()).await
+}
+
+#[tauri::command]
+pub async fn consul_sessions(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulSession>>, String> {
+ dbx_core::consul::consul_sessions_core(&state, &connection_id, options).await
+}
+
+#[tauri::command]
+pub async fn consul_node_sessions(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ node: String,
+ options: dbx_core::consul::ConsulReadOptions,
+) -> Result<dbx_core::consul::ConsulListResponse<Vec<dbx_core::consul::ConsulSession>>, String> {
+ dbx_core::consul::consul_node_sessions_core(&state, &connection_id, &node, options).await
+}
+
+#[tauri::command]
+pub async fn consul_session(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<Option<dbx_core::consul::ConsulSession>, String> {
+ dbx_core::consul::consul_session_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_session_keys(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulSessionKeysResponse, String> {
+ dbx_core::consul::consul_session_keys_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_session_destroy_impact(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulSessionDestroyImpact, String> {
+ dbx_core::consul::consul_session_destroy_impact_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_create_session(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulSessionCreateRequest,
+) -> Result<dbx_core::consul::ConsulSession, String> {
+ ensure_connection_writable(&state, &connection_id, "Create Consul Session").await?;
+ dbx_core::consul::consul_create_session_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_renew_session(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::ConsulSession, String> {
+ ensure_connection_writable(&state, &connection_id, "Renew Consul Session").await?;
+ dbx_core::consul::consul_renew_session_core(&state, &connection_id, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_destroy_session(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulSessionDestroyRequest,
+) -> Result<bool, String> {
+ ensure_connection_writable(&state, &connection_id, "Destroy Consul Session").await?;
+ dbx_core::consul::consul_destroy_session_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_acquire_lock(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::ConsulLockRequest,
+) -> Result<dbx_core::consul::ConsulLockResponse, String> {
+ ensure_connection_writable(&state, &connection_id, "Acquire Consul KV lock").await?;
+ dbx_core::consul::consul_acquire_lock_core(&state, &connection_id, request).await
+}
+
+#[tauri::command]
+pub async fn consul_release_lock(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ key: String,
+ session: String,
+) -> Result<dbx_core::consul::ConsulLockResponse, String> {
+ ensure_connection_writable(&state, &connection_id, "Release Consul KV lock").await?;
+ dbx_core::consul::consul_release_lock_core(&state, &connection_id, &key, &session).await
+}
+
+#[tauri::command]
+pub async fn consul_acl_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulAclKind,
+) -> Result<dbx_core::consul::ConsulAclList, String> {
+ dbx_core::consul::consul_acl_list_core(&state, &connection_id, kind).await
+}
+#[tauri::command]
+pub async fn consul_acl_token_self(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<dbx_core::consul::ConsulAclToken, String> {
+ dbx_core::consul::consul_acl_token_self_core(&state, &connection_id).await
+}
+#[tauri::command]
+pub async fn consul_acl_token_clone(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ accessor_id: String,
+ request: dbx_core::consul::ConsulAclTokenClone,
+) -> Result<dbx_core::consul::ConsulAclToken, String> {
+ ensure_connection_writable(&state, &connection_id, "Clone Consul ACL token").await?;
+ dbx_core::consul::consul_acl_token_clone_core(&state, &connection_id, &accessor_id, request).await
+}
+#[tauri::command]
+pub async fn consul_acl_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulAclKind,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAclItem, String> {
+ dbx_core::consul::consul_acl_get_core(&state, &connection_id, kind, &id).await
+}
+#[tauri::command]
+pub async fn consul_acl_apply(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: Option<String>,
+ value: dbx_core::consul::ConsulAclWrite,
+) -> Result<dbx_core::consul::ConsulAclItem, String> {
+ ensure_connection_writable(&state, &connection_id, "Write Consul ACL resource").await?;
+ dbx_core::consul::consul_acl_apply_core(&state, &connection_id, id.as_deref(), value).await
+}
+#[tauri::command]
+pub async fn consul_acl_references(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulAclKind,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAclReferences, String> {
+ dbx_core::consul::consul_acl_references_core(&state, &connection_id, kind, &id).await
+}
+#[tauri::command]
+pub async fn consul_acl_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulAclKind,
+ id: String,
+) -> Result<dbx_core::consul::ConsulAclReferences, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul ACL resource").await?;
+ dbx_core::consul::consul_acl_delete_core(&state, &connection_id, kind, &id).await
+}
+
+#[tauri::command]
+pub async fn consul_enterprise_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulEnterpriseKind,
+) -> Result<dbx_core::consul::ConsulEnterpriseList, String> {
+ dbx_core::consul::consul_enterprise_list_core(&state, &connection_id, kind).await
+}
+#[tauri::command]
+pub async fn consul_enterprise_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulEnterpriseKind,
+ name: String,
+) -> Result<dbx_core::consul::ConsulEnterpriseItem, String> {
+ dbx_core::consul::consul_enterprise_get_core(&state, &connection_id, kind, &name).await
+}
+#[tauri::command]
+pub async fn consul_enterprise_apply(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ existing_name: Option<String>,
+ item: dbx_core::consul::ConsulEnterpriseWrite,
+) -> Result<dbx_core::consul::ConsulEnterpriseItem, String> {
+ ensure_connection_writable(&state, &connection_id, "Write Consul Enterprise scope").await?;
+ dbx_core::consul::consul_enterprise_apply_core(&state, &connection_id, existing_name.as_deref(), item).await
+}
+#[tauri::command]
+pub async fn consul_enterprise_impact(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulEnterpriseKind,
+ name: String,
+) -> Result<dbx_core::consul::ConsulScopeImpact, String> {
+ dbx_core::consul::consul_enterprise_impact_core(&state, &connection_id, kind, &name).await
+}
+#[tauri::command]
+pub async fn consul_enterprise_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: dbx_core::consul::ConsulEnterpriseKind,
+ name: String,
+) -> Result<dbx_core::consul::ConsulScopeImpact, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul Enterprise scope").await?;
+ dbx_core::consul::consul_enterprise_delete_core(&state, &connection_id, kind, &name).await
+}
+
+#[tauri::command]
+pub async fn consul_mesh_config_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: String,
+) -> Result<Vec<dbx_core::consul::mesh::ConsulConfigEntry>, String> {
+ dbx_core::consul::mesh::consul_mesh_config_list_core(&state, &connection_id, &kind).await
+}
+#[tauri::command]
+pub async fn consul_mesh_config_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: String,
+ name: String,
+) -> Result<dbx_core::consul::mesh::ConsulConfigEntry, String> {
+ dbx_core::consul::mesh::consul_mesh_config_get_core(&state, &connection_id, &kind, &name).await
+}
+#[tauri::command]
+pub async fn consul_mesh_config_apply(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulConfigEntryApply,
+) -> Result<dbx_core::consul::mesh::ConsulConfigEntry, String> {
+ ensure_connection_writable(&state, &connection_id, "Write Consul Service Mesh config entry").await?;
+ dbx_core::consul::mesh::consul_mesh_config_apply_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_config_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ kind: String,
+ name: String,
+ expected_modify_index: u64,
+) -> Result<bool, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul Service Mesh config entry").await?;
+ dbx_core::consul::mesh::consul_mesh_config_delete_core(&state, &connection_id, &kind, &name, expected_modify_index)
+ .await
+}
+#[tauri::command]
+pub async fn consul_mesh_intentions_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<dbx_core::consul::mesh::ConsulIntention>, String> {
+ dbx_core::consul::mesh::consul_mesh_intentions_list_core(&state, &connection_id).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<dbx_core::consul::mesh::ConsulIntention, String> {
+ dbx_core::consul::mesh::consul_mesh_intention_get_core(&state, &connection_id, &id).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_get_exact(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulIntentionExactRequest,
+) -> Result<dbx_core::consul::mesh::ConsulIntention, String> {
+ dbx_core::consul::mesh::consul_mesh_intention_get_exact_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_upsert(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ item: dbx_core::consul::mesh::ConsulIntention,
+) -> Result<dbx_core::consul::mesh::ConsulIntention, String> {
+ ensure_connection_writable(&state, &connection_id, "Write Consul intention").await?;
+ dbx_core::consul::mesh::consul_mesh_intention_upsert_core(&state, &connection_id, item).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ id: String,
+) -> Result<bool, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul intention").await?;
+ dbx_core::consul::mesh::consul_mesh_intention_delete_core(&state, &connection_id, &id).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_delete_exact(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulIntentionExactRequest,
+) -> Result<bool, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete exact Consul intention").await?;
+ dbx_core::consul::mesh::consul_mesh_intention_delete_exact_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_match(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulIntentionMatchRequest,
+) -> Result<Vec<dbx_core::consul::mesh::ConsulIntention>, String> {
+ dbx_core::consul::mesh::consul_mesh_intention_match_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_intention_check(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulIntentionCheckRequest,
+) -> Result<dbx_core::consul::mesh::ConsulIntentionCheckResponse, String> {
+ dbx_core::consul::mesh::consul_mesh_intention_check_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_discovery_chain(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ service: String,
+) -> Result<dbx_core::consul::mesh::ConsulDiscoveryChain, String> {
+ dbx_core::consul::mesh::consul_mesh_discovery_chain_core(&state, &connection_id, &service).await
+}
+#[tauri::command]
+pub async fn consul_mesh_peering_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<dbx_core::consul::mesh::ConsulPeering>, String> {
+ dbx_core::consul::mesh::consul_mesh_peering_list_core(&state, &connection_id).await
+}
+#[tauri::command]
+pub async fn consul_mesh_peering_get(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ name: String,
+) -> Result<dbx_core::consul::mesh::ConsulPeering, String> {
+ dbx_core::consul::mesh::consul_mesh_peering_get_core(&state, &connection_id, &name).await
+}
+#[tauri::command]
+pub async fn consul_mesh_peering_generate_token(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulPeeringGenerateRequest,
+) -> Result<dbx_core::consul::mesh::ConsulPeeringToken, String> {
+ ensure_connection_writable(&state, &connection_id, "Generate Consul peering token").await?;
+ dbx_core::consul::mesh::consul_mesh_peering_generate_token_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_peering_establish(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ request: dbx_core::consul::mesh::ConsulPeeringEstablishRequest,
+) -> Result<dbx_core::consul::mesh::ConsulPeering, String> {
+ ensure_connection_writable(&state, &connection_id, "Establish Consul peering").await?;
+ dbx_core::consul::mesh::consul_mesh_peering_establish_core(&state, &connection_id, request).await
+}
+#[tauri::command]
+pub async fn consul_mesh_peering_delete(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ name: String,
+) -> Result<bool, String> {
+ ensure_connection_writable(&state, &connection_id, "Delete Consul peering").await?;
+ dbx_core::consul::mesh::consul_mesh_peering_delete_core(&state, &connection_id, &name).await
+}
+#[tauri::command]
+pub async fn consul_mesh_exported_services_list(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<Vec<dbx_core::consul::mesh::ConsulExportedService>, String> {
+ dbx_core::consul::mesh::consul_mesh_exported_services_list_core(&state, &connection_id).await
+}
+#[tauri::command]
+pub async fn consul_mesh_exported_services_apply(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ name: String,
+ expected_modify_index: u64,
+ raw: serde_json::Value,
+) -> Result<dbx_core::consul::mesh::ConsulConfigEntry, String> {
+ ensure_connection_writable(&state, &connection_id, "Write Consul exported services").await?;
+ dbx_core::consul::mesh::consul_mesh_exported_services_apply_core(
+ &state,
+ &connection_id,
+ &name,
+ expected_modify_index,
+ raw,
+ )
+ .await
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 1ca267d7b8..127927e8ef 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -7,6 +7,7 @@ pub mod config_cmd;
pub mod connection;
#[allow(dead_code, unused_imports)]
mod connection_secrets;
+pub mod consul_cmd;
pub mod csv_export;
pub mod data_compare;
pub mod database_export;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 70325b59ad..ebd199be5e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1818,6 +1818,109 @@ pub fn run() {
commands::zookeeper_cmd::zookeeper_get,
commands::zookeeper_cmd::zookeeper_put,
commands::zookeeper_cmd::zookeeper_delete,
+ commands::consul_cmd::consul_capabilities,
+ commands::consul_cmd::consul_txn,
+ commands::consul_cmd::consul_rename_key,
+ commands::consul_cmd::consul_blocking_query,
+ commands::consul_cmd::consul_domain_watch,
+ commands::consul_cmd::consul_cancel_blocking,
+ commands::consul_cmd::consul_watch_start,
+ commands::consul_cmd::consul_list_prefix,
+ commands::consul_cmd::consul_list_recursive,
+ commands::consul_cmd::consul_search,
+ commands::consul_cmd::consul_search_progress,
+ commands::consul_cmd::consul_cancel_search,
+ commands::consul_cmd::consul_export_bundle,
+ commands::consul_cmd::consul_import_preview,
+ commands::consul_cmd::consul_import_execute,
+ commands::consul_cmd::consul_delete_prefix_preview,
+ commands::consul_cmd::consul_delete_prefix_execute,
+ commands::consul_cmd::consul_get,
+ commands::consul_cmd::consul_put,
+ commands::consul_cmd::consul_delete,
+ commands::consul_cmd::consul_prepared_query_list,
+ commands::consul_cmd::consul_prepared_query_read,
+ commands::consul_cmd::consul_prepared_query_create,
+ commands::consul_cmd::consul_prepared_query_update,
+ commands::consul_cmd::consul_prepared_query_delete,
+ commands::consul_cmd::consul_prepared_query_execute,
+ commands::consul_cmd::consul_prepared_query_explain,
+ commands::consul_cmd::consul_event_list,
+ commands::consul_cmd::consul_event_fire,
+ commands::consul_cmd::consul_coordinate_nodes,
+ commands::consul_cmd::consul_operator_read,
+ commands::consul_cmd::consul_snapshot_generate,
+ commands::consul_cmd::consul_snapshot_restore,
+ commands::consul_cmd::consul_autopilot_update,
+ commands::consul_cmd::consul_raft_transfer,
+ commands::consul_cmd::consul_raft_remove,
+ commands::consul_cmd::consul_keyring_write,
+ commands::consul_cmd::consul_license_write,
+ commands::consul_cmd::consul_status_leader,
+ commands::consul_cmd::consul_status_peers,
+ commands::consul_cmd::consul_agent_self,
+ commands::consul_cmd::consul_agent_members,
+ commands::consul_cmd::consul_agent_metrics,
+ commands::consul_cmd::consul_catalog_datacenters,
+ commands::consul_cmd::consul_catalog_nodes,
+ commands::consul_cmd::consul_catalog_services,
+ commands::consul_cmd::consul_catalog_service_nodes,
+ commands::consul_cmd::consul_catalog_node_services,
+ commands::consul_cmd::consul_health_node,
+ commands::consul_cmd::consul_health_checks,
+ commands::consul_cmd::consul_health_service,
+ commands::consul_cmd::consul_health_state,
+ commands::consul_cmd::consul_agent_services,
+ commands::consul_cmd::consul_agent_service,
+ commands::consul_cmd::consul_agent_checks,
+ commands::consul_cmd::consul_agent_register_service,
+ commands::consul_cmd::consul_agent_deregister_service,
+ commands::consul_cmd::consul_agent_service_maintenance,
+ commands::consul_cmd::consul_agent_register_check,
+ commands::consul_cmd::consul_agent_deregister_check,
+ commands::consul_cmd::consul_agent_update_ttl,
+ commands::consul_cmd::consul_sessions,
+ commands::consul_cmd::consul_node_sessions,
+ commands::consul_cmd::consul_session,
+ commands::consul_cmd::consul_session_keys,
+ commands::consul_cmd::consul_session_destroy_impact,
+ commands::consul_cmd::consul_create_session,
+ commands::consul_cmd::consul_renew_session,
+ commands::consul_cmd::consul_destroy_session,
+ commands::consul_cmd::consul_acquire_lock,
+ commands::consul_cmd::consul_release_lock,
+ commands::consul_cmd::consul_acl_list,
+ commands::consul_cmd::consul_acl_token_self,
+ commands::consul_cmd::consul_acl_token_clone,
+ commands::consul_cmd::consul_acl_get,
+ commands::consul_cmd::consul_acl_apply,
+ commands::consul_cmd::consul_acl_references,
+ commands::consul_cmd::consul_acl_delete,
+ commands::consul_cmd::consul_enterprise_list,
+ commands::consul_cmd::consul_enterprise_get,
+ commands::consul_cmd::consul_enterprise_apply,
+ commands::consul_cmd::consul_enterprise_impact,
+ commands::consul_cmd::consul_enterprise_delete,
+ commands::consul_cmd::consul_mesh_config_list,
+ commands::consul_cmd::consul_mesh_config_get,
+ commands::consul_cmd::consul_mesh_config_apply,
+ commands::consul_cmd::consul_mesh_config_delete,
+ commands::consul_cmd::consul_mesh_intentions_list,
+ commands::consul_cmd::consul_mesh_intention_get,
+ commands::consul_cmd::consul_mesh_intention_get_exact,
+ commands::consul_cmd::consul_mesh_intention_upsert,
+ commands::consul_cmd::consul_mesh_intention_delete,
+ commands::consul_cmd::consul_mesh_intention_delete_exact,
+ commands::consul_cmd::consul_mesh_intention_match,
+ commands::consul_cmd::consul_mesh_intention_check,
+ commands::consul_cmd::consul_mesh_discovery_chain,
+ commands::consul_cmd::consul_mesh_peering_list,
+ commands::consul_cmd::consul_mesh_peering_get,
+ commands::consul_cmd::consul_mesh_peering_generate_token,
+ commands::consul_cmd::consul_mesh_peering_establish,
+ commands::consul_cmd::consul_mesh_peering_delete,
+ commands::consul_cmd::consul_mesh_exported_services_list,
+ commands::consul_cmd::consul_mesh_exported_services_apply,
commands::nacos_cmd::nacos_test_connection,
commands::nacos_cmd::nacos_list_namespaces,
commands::nacos_cmd::nacos_create_namespace,