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(connection): auto disconnect idle connections

HighBigSky4722a49ab9ea
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 1b9b3cc49d..a27799aebd 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -4980,7 +4980,45 @@ async function syncConnectionLivenessSubscription(active: boolean): Promise<void
}
}
-watch(appReady, (ready) => void syncConnectionLivenessSubscription(ready), { immediate: true });
+// Backend idle-closed notifications (#12112). Registered through the same `api` layer and the
+// same appReady gate as the liveness channel above, so neither transport opens a stream before
+// auth is settled.
+let connectionIdleClosedUnlisten: (() => void) | null = null;
+let connectionIdleClosedSubscribing = false;
+
+async function syncConnectionIdleClosedSubscription(active: boolean): Promise<void> {
+ if (!active) {
+ connectionIdleClosedUnlisten?.();
+ connectionIdleClosedUnlisten = null;
+ return;
+ }
+ if (connectionIdleClosedUnlisten || connectionIdleClosedSubscribing) return;
+ connectionIdleClosedSubscribing = true;
+ try {
+ const unlisten = await api.subscribeConnectionIdleClosed((payload) => {
+ void connectionStore.handleConnectionIdleClosed(payload);
+ });
+ if (!appReady.value) {
+ // Auth flipped off while the subscription was being established.
+ unlisten();
+ return;
+ }
+ connectionIdleClosedUnlisten = unlisten;
+ } catch (error) {
+ console.error("[DBX] subscribeConnectionIdleClosed error:", error);
+ } finally {
+ connectionIdleClosedSubscribing = false;
+ }
+}
+
+watch(
+ appReady,
+ (ready) => {
+ void syncConnectionLivenessSubscription(ready);
+ void syncConnectionIdleClosedSubscription(ready);
+ },
+ { immediate: true },
+);
onMounted(async () => {
clearStartupPreloadRetry();
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index d4ce1934ec..89311d9630 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -79,9 +79,11 @@ import { applyMeilisearchBasePathToExternalConfig, applyParsedConnectionUrl, nor
import { loadVisibleDatabasesPickerNames } from "@/lib/connection/visibleDatabasesPickerLoad";
import { hasXuguConnectionDatabase } from "@/lib/connection/xuguDatabase";
import {
+ DEFAULT_IDLE_DISCONNECT_ENABLED_SECS,
DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS,
DEFAULT_QUERY_TIMEOUT_SECS,
MAX_CONNECT_TIMEOUT_SECS,
+ MAX_IDLE_DISCONNECT_SECS,
MAX_IDLE_TIMEOUT_SECS,
MAX_MANUAL_TRANSACTION_TIMEOUT_SECS,
MAX_QUERY_TIMEOUT_SECS,
@@ -435,6 +437,8 @@ const defaultForm = (): ConnectionForm => ({
query_timeout_inherit: true,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS,
+ // 空闲自动断开默认不启用(0)。
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 30,
ssl: false,
ca_cert_path: "",
@@ -808,6 +812,30 @@ const keepaliveEnabled = computed({
}
},
});
+
+const idleDisconnectEnabled = computed({
+ get: () => Number(form.value.idle_disconnect_secs) > 0,
+ set: (enabled: boolean) => {
+ if (enabled) {
+ const current = Number(form.value.idle_disconnect_secs);
+ form.value.idle_disconnect_secs = Number.isFinite(current) && current > 0 ? current : DEFAULT_IDLE_DISCONNECT_ENABLED_SECS;
+ } else {
+ form.value.idle_disconnect_secs = 0;
+ }
+ },
+});
+
+/**
+ * 「空闲自动断开」的软校验:开启后阈值若不大于「保持连接间隔」,保活探测还没来得及跑一次,
+ * 连接就已经被关掉了,等于保活白开。这里只提示、不阻止保存——两者相等或更短的组合仍有
+ * 合理场景(例如用户只是不想要保活),不该把配置挡在门外。
+ */
+const idleDisconnectKeepaliveWarning = computed(() => {
+ const idle = Number(form.value.idle_disconnect_secs);
+ const keepalive = Number(form.value.keepalive_interval_secs);
+ return idle > 0 && keepalive > 0 && idle <= keepalive;
+});
+
const selectedTransportLayerId = ref<string | null>(null);
const draggedTransportLayerId = ref<string | null>(null);
const selectedType = ref("mysql");
@@ -3123,6 +3151,7 @@ watch(
query_timeout_inherit: config.query_timeout_inherit === true,
idle_timeout_secs: config.idle_timeout_secs ?? 60,
manual_transaction_timeout_secs: normalizeManualTransactionTimeoutSecs(config.manual_transaction_timeout_secs),
+ idle_disconnect_secs: config.idle_disconnect_secs ?? 0,
keepalive_interval_secs: config.keepalive_interval_secs ?? 30,
sysdba: config.sysdba || isOracleSysUser(config),
oracle_oci_nls_lang: config.oracle_oci_nls_lang || "",
@@ -4851,6 +4880,7 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
config.query_timeout_inherit = form.value.query_timeout_inherit;
config.idle_timeout_secs = form.value.idle_timeout_secs;
config.manual_transaction_timeout_secs = normalizeManualTransactionTimeoutSecs(form.value.manual_transaction_timeout_secs);
+ config.idle_disconnect_secs = form.value.idle_disconnect_secs;
config.keepalive_interval_secs = form.value.keepalive_interval_secs;
config.read_only = form.value.read_only;
config.save_password = form.value.save_password;
@@ -6623,6 +6653,15 @@ function clampIdleTimeoutInput(event: Event) {
form.value.idle_timeout_secs = MAX_IDLE_TIMEOUT_SECS;
}
+function clampIdleDisconnectInput(event: Event) {
+ const input = event.target as HTMLInputElement;
+ if (input.value === "") return;
+ const value = Number(input.value);
+ if (!Number.isFinite(value) || value <= MAX_IDLE_DISCONNECT_SECS) return;
+ input.value = String(MAX_IDLE_DISCONNECT_SECS);
+ form.value.idle_disconnect_secs = MAX_IDLE_DISCONNECT_SECS;
+}
+
async function persistGlobalTimeoutDrafts() {
const nextConnect = normalizeGlobalConnectTimeoutSecs(editGlobalConnectTimeoutSecs.value);
const nextQuery = normalizeGlobalQueryTimeoutSecs(editGlobalQueryTimeoutSecs.value);
@@ -10366,6 +10405,22 @@ function openExternalUrl(url: string) {
<p class="text-xs leading-5 text-muted-foreground">{{ t("connection.manualTransactionTimeoutHint", { min: MIN_MANUAL_TRANSACTION_TIMEOUT_SECS, max: MAX_MANUAL_TRANSACTION_TIMEOUT_SECS }) }}</p>
</div>
</div>
+ <!-- 空闲自动断开由后端在连接池层面实现,所有方言均适用,故不做方言门控:
+ 即使上面的「空闲超时」被 v-show 隐藏,这里也要展示。 -->
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallPaddedClass">
+ <span class="inline-flex items-center gap-1">{{ t("connection.idleDisconnect") }} <HelpTooltip :label="t('connection.idleDisconnectHint')" content-class="max-w-[280px]" /></span>
+ </Label>
+ <div class="col-span-3 space-y-1">
+ <div class="flex items-center gap-2">
+ <Switch v-model="idleDisconnectEnabled" />
+ <Input v-model.number="form.idle_disconnect_secs" type="number" min="1" :max="MAX_IDLE_DISCONNECT_SECS" step="1" class="flex-1" :disabled="!idleDisconnectEnabled" @input="clampIdleDisconnectInput($event)" />
+ </div>
+ <p v-if="idleDisconnectKeepaliveWarning" class="rounded-md border border-amber-500/30 bg-amber-500/5 px-2 py-1 text-xs leading-5 text-amber-700 dark:text-amber-400">
+ {{ t("connection.idleDisconnectKeepaliveWarning") }}
+ </p>
+ </div>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelSmallClass">{{ t("connection.keepaliveInterval") }}</Label>
<div class="col-span-3 flex items-center gap-2">
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 4a24711110..bb036238d5 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -1314,9 +1314,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Aralıq: 0–3600 saniyə. Vaxt limitini ləğv etmək üçün 0 təyin edin.",
useConnectionQueryTimeout: "Əlaqə",
idleTimeout: "Boşdayanma vaxt limiti (saniyə)",
- idleTimeoutHint: "Bağlantı hovuzundakı boşda qalan bağlantıların geri qaytarılmasına tətbiq edilir.",
manualTransactionTimeout: "Tranzaksiyanın boşdayanma vaxt limiti (saniyə)",
manualTransactionTimeoutHint: "Bu müddət ərzində heç bir ifadə icra edilməyən əl ilə idarə olunan tranzaksiya avtomatik geri qaytarılır. İcazə verilən aralıq: {min}–{max} saniyə.",
+ idleTimeoutHint: "Yalnız MySQL ailəsi və MongoDB üçün keçərlidir: hovuzdakı boşda qalan fiziki bağlantıları geri qaytarır, bağlantı statusunu dəyişmir (bağlı olaraq qalır).",
+ idleDisconnect: "Boşda avtomatik ayırma (saniyə)",
+ idleDisconnectHint: "Bu saniyə müddətində heç bir sorğu fəaliyyəti olmadıqda bağlantı hovuzu avtomatik bağlanır; yuxarıdaki «Boşdayanma vaxt limiti» fərqli olaraq, o yalnız hovuz daxilindəki boşda qalan fiziki bağlantıları geri qaytarır.",
+ idleDisconnectKeepaliveWarning: "Keepalive intervalından böyük deyil, buna görə keepalive yoxlamaları işləməyəcək; dəyəri artırın.",
+ idleDisconnectToast: "{name} bağlantısı {seconds} saniyədən çox boşda qaldığı üçün avtomatik ayrıldı; açıq sorğu tabları və nəticələri saxlanıldı.",
keepaliveInterval: "Əlaqənin canlı saxlanma intervalı (saniyə)",
readOnly: "Yalnız oxuma",
readOnlyHint: "Bütün yazma əməliyyatlarını blokla (INSERT, UPDATE, DELETE və s.)",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 996973fa1b..917615a20b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1961,9 +1961,13 @@ export default {
globalQueryTimeoutHint: "Range: 0 to 3600 seconds. Set to 0 for no timeout.",
useConnectionQueryTimeout: "Connection",
idleTimeout: "Idle Timeout (seconds)",
- idleTimeoutHint: "Applies to idle connection reclamation within the connection pool.",
manualTransactionTimeout: "Transaction Idle Timeout (seconds)",
manualTransactionTimeoutHint: "A manual transaction with no statement executed for this long is rolled back automatically. Allowed range: {min}–{max} seconds.",
+ idleTimeoutHint: "Only applies to MySQL-family and MongoDB: reclaims idle physical connections inside the pool without changing the connection state (it stays connected).",
+ idleDisconnect: "Auto-disconnect when idle (seconds)",
+ idleDisconnectHint: "The connection's pool is closed automatically after this many seconds without any query activity; unlike the “Idle Timeout” above, which only reclaims idle physical connections inside the pool.",
+ idleDisconnectKeepaliveWarning: "Not larger than the keepalive interval, so keepalive probes will not take effect; increase this value.",
+ idleDisconnectToast: "Connection {name} was disconnected automatically after being idle for more than {seconds} seconds; open query tabs and results were kept.",
keepaliveInterval: "Keepalive Interval (seconds)",
readOnly: "Read Only",
readOnlyHint: "Block all write operations (INSERT, UPDATE, DELETE, etc.)",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8e15700a68..d752b3fee6 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1541,9 +1541,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Rango: de 0 a 3600 segundos. Establece 0 para no aplicar límite.",
useConnectionQueryTimeout: "Conexión",
idleTimeout: "Tiempo de espera inactivo (segundos)",
- idleTimeoutHint: "Se aplica a la recuperación de conexiones inactivas dentro del grupo de conexiones.",
manualTransactionTimeout: "Tiempo de inactividad de la transacción (segundos)",
manualTransactionTimeoutHint: "Una transacción manual sin ninguna sentencia ejecutada durante este tiempo se revierte automáticamente. Rango permitido: {min}–{max} segundos.",
+ idleTimeoutHint: "Solo se aplica a la familia MySQL y MongoDB: recupera las conexiones físicas inactivas del grupo sin cambiar el estado de la conexión (sigue conectada).",
+ idleDisconnect: "Desconexión automática por inactividad (segundos)",
+ idleDisconnectHint: "El grupo de conexiones se cierra automáticamente tras este número de segundos sin actividad de consultas; a diferencia del «Tiempo de espera inactivo» anterior, que solo recupera las conexiones físicas inactivas dentro del grupo.",
+ idleDisconnectKeepaliveWarning: "No es mayor que el intervalo de keepalive, por lo que las comprobaciones de keepalive no llegarán a ejecutarse; aumenta este valor.",
+ idleDisconnectToast: "La conexión {name} se desconectó automáticamente tras estar inactiva más de {seconds} segundos; las pestañas de consulta abiertas y sus resultados se conservaron.",
keepaliveInterval: "Intervalo de keepalive (segundos)",
readOnly: "Solo lectura",
readOnlyHint: "Bloquear todas las operaciones de escritura (INSERT, UPDATE, DELETE, etc.)",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 2c16b34383..f03ff1e536 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -1577,9 +1577,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Rentang: 0 hingga 3600 detik. Tetapkan ke 0 untuk tanpa timeout.",
useConnectionQueryTimeout: "Koneksi",
idleTimeout: "Timeout Idle (detik)",
- idleTimeoutHint: "Berlaku untuk pemulihan koneksi idle dalam connection pool.",
manualTransactionTimeout: "Timeout Idle Transaksi (detik)",
manualTransactionTimeoutHint: "Transaksi manual tanpa pernyataan yang dijalankan selama durasi ini akan di-rollback otomatis. Rentang yang diizinkan: {min}–{max} detik.",
+ idleTimeoutHint: "Hanya berlaku untuk keluarga MySQL dan MongoDB: memulihkan koneksi fisik idle di dalam pool tanpa mengubah status koneksi (tetap terhubung).",
+ idleDisconnect: "Putus otomatis saat idle (detik)",
+ idleDisconnectHint: "Kumpulan koneksi ditutup secara otomatis setelah jumlah detik ini tanpa aktivitas kueri; berbeda dengan “Timeout Idle” di atas, yang hanya memulihkan koneksi fisik idle di dalam kumpulan.",
+ idleDisconnectKeepaliveWarning: "Tidak lebih besar dari interval keepalive, sehingga pemeriksaan keepalive tidak akan berjalan; perbesar nilai ini.",
+ idleDisconnectToast: "Koneksi {name} diputus secara otomatis setelah idle lebih dari {seconds} detik; tab kueri yang terbuka dan hasilnya tetap dipertahankan.",
keepaliveInterval: "Interval Keepalive (detik)",
readOnly: "Read Only",
readOnlyHint: "Blokir semua operasi tulis (INSERT, UPDATE, DELETE, dll.)",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 6415b89a58..24d22b4863 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1463,9 +1463,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Intervallo: da 0 a 3600 secondi. Imposta 0 per nessun limite.",
useConnectionQueryTimeout: "Connessione",
idleTimeout: "Timeout Inattività (secondi)",
- idleTimeoutHint: "Si applica al recupero delle connessioni inattive all'interno del pool di connessioni.",
manualTransactionTimeout: "Timeout inattività transazione (secondi)",
manualTransactionTimeoutHint: "Una transazione manuale senza istruzioni eseguite per questo periodo viene annullata automaticamente. Intervallo consentito: {min}–{max} secondi.",
+ idleTimeoutHint: "Si applica solo alla famiglia MySQL e a MongoDB: recupera le connessioni fisiche inattive nel pool senza cambiare lo stato della connessione (rimane connessa).",
+ idleDisconnect: "Disconnessione automatica in caso di inattività (secondi)",
+ idleDisconnectHint: "Il pool di connessioni viene chiuso automaticamente dopo questo numero di secondi senza attività di query; a differenza del «Timeout Inattività» sopra, che recupera solo le connessioni fisiche inattive all'interno del pool.",
+ idleDisconnectKeepaliveWarning: "Non è maggiore dell'intervallo keepalive, quindi i controlli keepalive non verranno eseguiti; aumenta questo valore.",
+ idleDisconnectToast: "La connessione {name} è stata disconnessa automaticamente dopo essere rimasta inattiva per più di {seconds} secondi; le schede di query aperte e i relativi risultati sono stati mantenuti.",
keepaliveInterval: "Intervallo keepalive (secondi)",
readOnly: "Sola lettura",
readOnlyHint: "Blocca tutte le operazioni di scrittura (INSERT, UPDATE, DELETE, ecc.)",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 41cecf29a8..596a7da2c8 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1433,9 +1433,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "0~3600 秒の範囲で指定します。0 はタイムアウトなしです。",
useConnectionQueryTimeout: "接続",
idleTimeout: "アイドルタイムアウト(秒)",
- idleTimeoutHint: "コネクションプール内のアイドル接続の回収・解放に適用されます。",
manualTransactionTimeout: "トランザクションのアイドルタイムアウト(秒)",
manualTransactionTimeoutHint: "手動トランザクションでこの時間ステートメントが実行されない場合、自動的にロールバックされます。指定可能な範囲: {min}~{max} 秒。",
+ idleTimeoutHint: "MySQL 系と MongoDB のみ有効:プール内のアイドル状態の物理接続を回収しますが、接続状態は変わりません(「接続済み」のまま)。",
+ idleDisconnect: "アイドル時に自動切断(秒)",
+ idleDisconnectHint: "この秒数以内にクエリ操作がない場合、接続プールを自動的に閉じます。上記の「アイドルタイムアウト」とは異なり、後者は接続プール内のアイドル物理接続のみを回収します。",
+ idleDisconnectKeepaliveWarning: "「Keepalive 間隔」以下であるため、Keepalive の疎通確認は実行されません。値を大きくしてください。",
+ idleDisconnectToast: "接続 {name} は {seconds} 秒を超えてアイドル状態だったため自動的に切断されました。開いているクエリタブと結果は保持されています。",
keepaliveInterval: "Keepalive 間隔(秒)",
readOnly: "読み取り専用",
readOnlyHint: "すべての書き込み操作(INSERT, UPDATE, DELETEなど)をブロックします",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 2a16dbf4ef..69f258abfc 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1628,9 +1628,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "범위: 0~3600초. 0으로 설정하면 제한이 없습니다.",
useConnectionQueryTimeout: "연결",
idleTimeout: "유휴 제한 시간 (초)",
- idleTimeoutHint: "연결 풀 내 유휴 연결의 회수 및 해제에 적용됩니다.",
manualTransactionTimeout: "트랜잭션 유휴 제한 시간 (초)",
manualTransactionTimeoutHint: "수동 트랜잭션에서 이 시간 동안 문이 실행되지 않으면 자동으로 롤백됩니다. 허용 범위: {min}~{max}초.",
+ idleTimeoutHint: "MySQL 계열과 MongoDB에만 적용됩니다: 풀 내 유휴 물리 연결을 회수할 뿐 연결 상태는 바뀌지 않습니다(계속 「연결됨」으로 표시).",
+ idleDisconnect: "유휴 시 자동 연결 해제 (초)",
+ idleDisconnectHint: "이 초 수 동안 쿼리 활동이 없으면 연결 풀을 자동으로 닫습니다. 위의 「유휴 제한 시간」과 달리 후자는 연결 풀 내의 유휴 물리 연결만 회수합니다.",
+ idleDisconnectKeepaliveWarning: "「킵얼라이브 간격」 이하이므로 킵얼라이브 확인이 실행되지 않습니다. 값을 늘리는 것을 권장합니다.",
+ idleDisconnectToast: "연결 {name}이(가) {seconds}초 이상 유휴 상태여서 자동으로 연결 해제되었습니다. 열린 쿼리 탭과 결과는 유지됩니다.",
keepaliveInterval: "킵얼라이브 간격 (초)",
readOnly: "읽기 전용",
readOnlyHint: "모든 쓰기 작업 차단 (INSERT, UPDATE, DELETE 등)",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index ce9bfacb5f..81abe95c1f 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1464,9 +1464,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Intervalo: de 0 a 3600 segundos. Defina 0 para não haver limite.",
useConnectionQueryTimeout: "Conexão",
idleTimeout: "Timeout de Inatividade (segundos)",
- idleTimeoutHint: "Aplica-se à recuperação de conexões inativas no pool de conexões.",
manualTransactionTimeout: "Tempo limite de inatividade da transação (segundos)",
manualTransactionTimeoutHint: "Uma transação manual sem nenhuma instrução executada durante esse período é revertida automaticamente. Intervalo permitido: {min}–{max} segundos.",
+ idleTimeoutHint: "Aplica-se apenas à família MySQL e ao MongoDB: recupera conexões físicas inativas do pool sem alterar o estado da conexão (ela continua conectada).",
+ idleDisconnect: "Desconexão automática por inatividade (segundos)",
+ idleDisconnectHint: "O pool de conexões é fechado automaticamente após esse número de segundos sem qualquer atividade de consulta; diferente do “Timeout de Inatividade” acima, que apenas recupera conexões físicas inativas dentro do pool.",
+ idleDisconnectKeepaliveWarning: "Não é maior que o intervalo de keepalive, então as verificações de keepalive não chegam a ser executadas; aumente este valor.",
+ idleDisconnectToast: "A conexão {name} foi desconectada automaticamente após ficar inativa por mais de {seconds} segundos; as abas de consulta abertas e os resultados foram mantidos.",
keepaliveInterval: "Intervalo de keepalive (segundos)",
readOnly: "Somente leitura",
readOnlyHint: "Bloquear todas as operações de escrita (INSERT, UPDATE, DELETE, etc.)",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index d01a4c2f9a..0448fe6cda 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1726,9 +1726,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Диапазон: от 0 до 3600 секунд. Установите 0, чтобы отключить тайм-аут.",
useConnectionQueryTimeout: "Подключение",
idleTimeout: "Тайм-аут простоя (секунды)",
- idleTimeoutHint: "Применяется для освобождения простаивающих соединений в пуле соединений.",
manualTransactionTimeout: "Тайм-аут простоя транзакции (секунды)",
manualTransactionTimeoutHint: "Ручная транзакция, в которой за это время не выполнялось ни одной инструкции, автоматически откатывается. Допустимый диапазон: {min}–{max} секунд.",
+ idleTimeoutHint: "Только для MySQL-семейства и MongoDB: освобождает простаивающие физические соединения в пуле, не меняя состояние соединения (оно остаётся подключённым).",
+ idleDisconnect: "Автоотключение при простое (секунды)",
+ idleDisconnectHint: "Пул соединений автоматически закрывается после указанного числа секунд без запросов. В отличие от «Тайм-аута простоя» выше, который лишь освобождает простаивающие физические соединения в пуле.",
+ idleDisconnectKeepaliveWarning: "Значение не больше интервала keepalive, поэтому проверки keepalive не будут выполняться; увеличьте его.",
+ idleDisconnectToast: "Соединение {name} автоматически отключено после простоя более {seconds} с; открытые вкладки запросов и результаты сохранены.",
keepaliveInterval: "Интервал keepalive (секунды)",
readOnly: "Только чтение",
readOnlyHint: "Блокировать все операции записи (INSERT, UPDATE, DELETE и т. д.)",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 91970acd82..3371a48d5e 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -1923,9 +1923,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "ช่วง: 0 ถึง 3600 วินาที ตั้งเป็น 0 เพื่อไม่จำกัดเวลา",
useConnectionQueryTimeout: "การเชื่อมต่อ",
idleTimeout: "Timeout เมื่อไม่มีการใช้งาน (วินาที)",
- idleTimeoutHint: "มีผลกับการเรียกคืนการเชื่อมต่อที่ไม่มีการใช้งานภายใน Pool การเชื่อมต่อ",
manualTransactionTimeout: "Timeout ของ Transaction เมื่อไม่มีการใช้งาน (วินาที)",
manualTransactionTimeoutHint: "Transaction แบบ Manual ที่ไม่มีการรันคำสั่งภายในเวลานี้จะถูก Rollback อัตโนมัติ ช่วงที่อนุญาต: {min}–{max} วินาที",
+ idleTimeoutHint: "ใช้ได้เฉพาะตระกูล MySQL และ MongoDB: เรียกคืนการเชื่อมต่อทางกายภาพที่ไม่มีการใช้งานภายใน Pool โดยไม่เปลี่ยนสถานะการเชื่อมต่อ (ยังคงแสดงว่าเชื่อมต่ออยู่)",
+ idleDisconnect: "ตัดการเชื่อมต่ออัตโนมัติเมื่อไม่มีการใช้งาน (วินาที)",
+ idleDisconnectHint: "ระบบจะปิด Pool การเชื่อมต่ออัตโนมัติเมื่อไม่มีการทำ Query ภายในจำนวนวินาทีนี้ ต่างจาก “Timeout เมื่อไม่มีการใช้งาน” ด้านบน ซึ่งเรียกคืนเฉพาะการเชื่อมต่อทางกายภาพที่ไม่มีการใช้งานภายใน Pool",
+ idleDisconnectKeepaliveWarning: "ค่านี้ไม่มากกว่า «ช่วง Keepalive» การตรวจสอบ Keepalive จึงจะไม่ทำงาน ควรเพิ่มค่านี้",
+ idleDisconnectToast: "การเชื่อมต่อ {name} ถูกตัดอัตโนมัติหลังจากไม่มีการใช้งานเกิน {seconds} วินาที โดยยังคงแท็บ Query และผลลัพธ์ไว้",
keepaliveInterval: "ช่วง Keepalive (วินาที)",
readOnly: "อ่านอย่างเดียว",
readOnlyHint: "บล็อกการดำเนินการเขียนทั้งหมด (INSERT, UPDATE, DELETE ฯลฯ)",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index e009e5cb87..490b132ad1 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -1314,9 +1314,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "Aralık: 0 ile 3600 saniye. Zaman aşımı istemiyorsanız 0 yapın.",
useConnectionQueryTimeout: "Bağlantı",
idleTimeout: "Boşta Kalma Zaman Aşımı (saniye)",
- idleTimeoutHint: "Bağlantı havuzundaki boşta kalan bağlantıların geri kazanılması için geçerlidir.",
manualTransactionTimeout: "İşlem Boşta Kalma Zaman Aşımı (saniye)",
manualTransactionTimeoutHint: "Bu süre boyunca hiçbir ifade çalıştırılmayan manuel işlem otomatik olarak geri alınır. İzin verilen aralık: {min}–{max} saniye.",
+ idleTimeoutHint: "Yalnızca MySQL ailesi ve MongoDB için geçerlidir: havuzdaki boşta kalan fiziksel bağlantıları geri kazanır, bağlantı durumunu değiştirmez (bağlı olarak kalır).",
+ idleDisconnect: "Boşta otomatik bağlantı kesme (saniye)",
+ idleDisconnectHint: "Bağlantı havuzu, bu saniye sayısı boyunca sorgu etkinliği olmadan otomatik olarak kapatılır; yukarıdaki «Boşta Kalma Zaman Aşımı»'ndan farklı olarak, o yalnızca havuz içindeki boşta kalan fiziksel bağlantıları geri kazanır.",
+ idleDisconnectKeepaliveWarning: "Keepalive aralığından büyük değil, bu nedenle keepalive denetimleri çalışmayacak; değeri artırın.",
+ idleDisconnectToast: "{name} bağlantısı {seconds} saniyeden uzun süre boşta kaldığı için otomatik olarak kesildi; açık sorgu sekmeleri ve sonuçları korundu.",
keepaliveInterval: "Keepalive Aralığı (saniye)",
readOnly: "Salt Okunur",
readOnlyHint: "Tüm yazma işlemlerini engelle (INSERT, UPDATE, DELETE vb.)",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 8664d1f793..243d310fd6 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1899,9 +1899,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "范围为0~3600秒。设为0表示不限制",
useConnectionQueryTimeout: "当前连接",
idleTimeout: "空闲超时(秒)",
- idleTimeoutHint: "作用于连接池内空闲连接的回收释放。",
manualTransactionTimeout: "事务空闲超时(秒)",
manualTransactionTimeoutHint: "手动事务在此时长内没有执行任何语句时将自动回滚,范围 {min}–{max} 秒。",
+ idleTimeoutHint: "仅 MySQL 系与 MongoDB 生效:回收连接池内的空闲物理连接,不改变连接状态(仍显示为已连接)。",
+ idleDisconnect: "空闲自动断开(秒)",
+ idleDisconnectHint: "连接在此秒数内无任何查询活动时自动关闭其连接池;与上方「空闲超时」不同,后者只回收连接池内的空闲物理连接。",
+ idleDisconnectKeepaliveWarning: "该值不大于「保持连接间隔」,保活探测不会生效,建议调大。",
+ idleDisconnectToast: "连接 {name} 因空闲超过 {seconds} 秒已自动断开,已保留查询标签与结果。",
keepaliveInterval: "保持连接间隔(秒)",
readOnly: "只读模式",
readOnlyHint: "阻止所有写操作(INSERT、UPDATE、DELETE 等)",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 44c3a59120..851849c2f2 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1474,9 +1474,13 @@ export default withEnglishFallback({
globalQueryTimeoutHint: "範圍為0~3600秒。設為0表示不限制",
useConnectionQueryTimeout: "目前連線",
idleTimeout: "閒置逾時(秒)",
- idleTimeoutHint: "作用於連線池內閒置連線的回收釋放。",
manualTransactionTimeout: "交易閒置逾時(秒)",
manualTransactionTimeoutHint: "手動交易在此時間內未執行任何語句時將自動回滾,範圍 {min}–{max} 秒。",
+ idleTimeoutHint: "僅 MySQL 系與 MongoDB 生效:回收連線集區內的閒置實體連線,不改變連線狀態(仍顯示為已連線)。",
+ idleDisconnect: "閒置自動斷開(秒)",
+ idleDisconnectHint: "連線在此秒數內無任何查詢活動時自動關閉其連線集區;與上方「閒置逾時」不同,後者只回收連線集區內的閒置實體連線。",
+ idleDisconnectKeepaliveWarning: "該值不大於「保持連線間隔」,保活探測不會生效,建議調大。",
+ idleDisconnectToast: "連線 {name} 因閒置超過 {seconds} 秒已自動斷開,已保留查詢頁籤與結果。",
keepaliveInterval: "保持連線間隔(秒)",
readOnly: "唯讀模式",
readOnlyHint: "阻止所有寫入操作(INSERT、UPDATE、DELETE 等)",
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
index 798c7165ad..691ba8c1e2 100644
--- a/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/connectionDialogTimeouts.spec.ts
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
-import { DEFAULT_CONNECT_TIMEOUT_SECS, DEFAULT_IDLE_TIMEOUT_SECS, MAX_IDLE_TIMEOUT_SECS, normalizeConnectTimeoutSecs, normalizeIdleTimeoutSecs, supportsIdleTimeout } from "@/lib/connection/timeoutLimits";
+import { DEFAULT_CONNECT_TIMEOUT_SECS, DEFAULT_IDLE_DISCONNECT_SECS, DEFAULT_IDLE_TIMEOUT_SECS, MAX_IDLE_DISCONNECT_SECS, MAX_IDLE_TIMEOUT_SECS, normalizeConnectTimeoutSecs, normalizeIdleDisconnectSecs, normalizeIdleTimeoutSecs, supportsIdleTimeout } from "@/lib/connection/timeoutLimits";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
@@ -19,6 +19,17 @@ describe("ConnectionDialog timeout controls", () => {
expect(normalizeIdleTimeoutSecs(5000)).toBe(MAX_IDLE_TIMEOUT_SECS);
});
+ it("defaults auto-disconnect-when-idle to disabled and bounds its values", () => {
+ // 0 是合法值(不启用),必须与非法输入区分:只有非数字/NaN/负数才回落默认 0。
+ expect(normalizeIdleDisconnectSecs("")).toBe(DEFAULT_IDLE_DISCONNECT_SECS);
+ expect(normalizeIdleDisconnectSecs(Number.NaN)).toBe(DEFAULT_IDLE_DISCONNECT_SECS);
+ expect(normalizeIdleDisconnectSecs(-1)).toBe(DEFAULT_IDLE_DISCONNECT_SECS);
+ expect(normalizeIdleDisconnectSecs(0)).toBe(0);
+ expect(normalizeIdleDisconnectSecs(300)).toBe(300);
+ expect(normalizeIdleDisconnectSecs(120.4)).toBe(120);
+ expect(normalizeIdleDisconnectSecs(999999)).toBe(MAX_IDLE_DISCONNECT_SECS);
+ });
+
it("identifies database dialects that support idle connection timeouts", () => {
expect(supportsIdleTimeout("mongodb")).toBe(true);
expect(supportsIdleTimeout("mysql")).toBe(true);
@@ -39,4 +50,24 @@ describe("ConnectionDialog timeout controls", () => {
expect(dialogSource).toContain("clampIdleTimeoutInput($event)");
expect(dialogSource).toContain('t("connection.idleTimeoutHint")');
});
+
+ it("binds the auto-disconnect-when-idle input for every dialect", () => {
+ // 该输入框不做方言门控:不挂在 supportsIdleTimeoutSetting 的 v-show 块内,也没用
+ // supportsIdleTimeout 之类的判断。
+ expect(dialogSource).toContain("clampIdleDisconnectInput($event)");
+ expect(dialogSource).toContain('t("connection.idleDisconnect")');
+ expect(dialogSource).toContain('v-model.number="form.idle_disconnect_secs"');
+ // 开关+输入框与「保持连接间隔」一行保持一致;说明文案收进小问号 tooltip,
+ // 避免和「空闲超时」的说明挤在一起。
+ expect(dialogSource).toContain('v-model="idleDisconnectEnabled"');
+ expect(dialogSource).toContain(':disabled="!idleDisconnectEnabled"');
+ expect(dialogSource).toContain(":label=\"t('connection.idleDisconnectHint')\"");
+ });
+
+ it("warns when the idle auto-disconnect threshold can never beat keepalive", () => {
+ // 软校验:阈值不大于「保持连接间隔」时给出提示,但不阻止保存。
+ expect(dialogSource).toContain("idleDisconnectKeepaliveWarning");
+ expect(dialogSource).toContain('t("connection.idleDisconnectKeepaliveWarning")');
+ expect(dialogSource).toContain("const idleDisconnectKeepaliveWarning = computed");
+ });
});
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 911d85a021..eb6a0bf574 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -77,6 +77,7 @@ export const replaceNacosSessionCredential = forward("replaceNacosSessionCredent
export const checkConnectionHealth = forward("checkConnectionHealth");
export const connectionIsOpen = forward("connectionIsOpen");
export const subscribeConnectionLiveness = forward("subscribeConnectionLiveness");
+export const subscribeConnectionIdleClosed = forward("subscribeConnectionIdleClosed");
export const prewarmConnection = forward("prewarmConnection");
export const connectionIdentifierQuote = forward("connectionIdentifierQuote");
export const closeDatabaseConnection = forward("closeDatabaseConnection");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index abca22d992..23efa74fc9 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -262,6 +262,7 @@ import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, Da
import { apiUrl, apiWebSocketUrl } from "@/lib/common/webPath";
import type {
ActivePluginSession,
+ ConnectionIdleClosedEvent,
ConnectionLivenessMessage,
PluginBinaryEvent,
PluginConnectionActionResult,
@@ -825,6 +826,19 @@ export async function subscribeConnectionLiveness(onEvent: (event: ConnectionLiv
return () => source.close();
}
+/**
+ * 「空闲自动断开」事件(issue #12112):后端在某个连接的连接池因空闲超过
+ * `idle_disconnect_secs` 被关闭时下发。与 liveness 一样走 SSE,载荷也是同一份
+ * `{ connectionId }`,因此前端在 desktop(Tauri 事件)与 web 两种传输上解析同一种结构。
+ */
+export async function subscribeConnectionIdleClosed(onEvent: (event: ConnectionIdleClosedEvent) => void): Promise<() => void> {
+ const source = new EventSource(apiUrl("/api/connection/idle-closed-events"));
+ source.onmessage = (message) => {
+ onEvent(JSON.parse(message.data) as ConnectionIdleClosedEvent);
+ };
+ return () => source.close();
+}
+
async function pluginAssetPayload(path: string): Promise<PluginUiAssetPayload> {
const response = await fetch(apiUrl(path));
if (!response.ok) throw new Error(await response.text());
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 9908a97a64..59649a7fe5 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -125,6 +125,7 @@ import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
import type {
ActivePluginSession,
+ ConnectionIdleClosedEvent,
ConnectionLivenessMessage,
PluginBinaryEvent,
PluginConnectionActionResult,
@@ -3103,6 +3104,16 @@ export async function subscribeConnectionLiveness(onEvent: (event: ConnectionLiv
return listen<ConnectionLivenessMessage>("dbx-connection-liveness", (event) => onEvent(event.payload));
}
+/**
+ * 订阅后端「空闲自动断开」事件(issue #12112)。
+ *
+ * 后端在连接池因空闲超过 `idle_disconnect_secs` 关闭时发送 `dbx:connection-idle-closed`;
+ * 监听器收到的就是载荷本身(前端把该连接标记为未连接并保留已打开页签)。
+ */
+export async function subscribeConnectionIdleClosed(onEvent: (event: ConnectionIdleClosedEvent) => void): Promise<UnlistenFn> {
+ return listen<ConnectionIdleClosedEvent>("dbx:connection-idle-closed", (event) => onEvent(event.payload));
+}
+
export async function listJdbcDrivers(): Promise<JdbcDriverInfo[]> {
return invoke("list_jdbc_drivers");
}
diff --git a/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts b/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts
index 3b86f1ff41..4f292065e3 100644
--- a/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts
+++ b/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts
@@ -29,13 +29,19 @@ describe("connection submit normalization", () => {
});
it("normalizes invalid timeout values and inherited global values", () => {
- const inherited = config({ connect_timeout_inherit: true, query_timeout_inherit: true, idle_timeout_secs: -1, keepalive_interval_secs: Number.NaN });
+ const inherited = config({ connect_timeout_inherit: true, query_timeout_inherit: true, idle_timeout_secs: -1, idle_disconnect_secs: -1, keepalive_interval_secs: Number.NaN });
normalizeConnectionTimeouts(inherited, 12, 34);
- expect(inherited).toMatchObject({ connect_timeout_secs: 12, query_timeout_secs: 34, idle_timeout_secs: 60, keepalive_interval_secs: 30 });
+ expect(inherited).toMatchObject({ connect_timeout_secs: 12, query_timeout_secs: 34, idle_timeout_secs: 60, idle_disconnect_secs: 0, keepalive_interval_secs: 30 });
- const invalid = config({ query_timeout_secs: Number.NaN, idle_timeout_secs: -1, keepalive_interval_secs: -2 });
+ const invalid = config({ query_timeout_secs: Number.NaN, idle_timeout_secs: -1, idle_disconnect_secs: 120, keepalive_interval_secs: -2 });
normalizeConnectionTimeouts(invalid, 12, 34);
- expect(invalid).toMatchObject({ query_timeout_secs: 60, idle_timeout_secs: 60, keepalive_interval_secs: 30 });
+ expect(invalid).toMatchObject({ query_timeout_secs: 60, idle_timeout_secs: 60, idle_disconnect_secs: 120, keepalive_interval_secs: 30 });
+ });
+
+ it("defaults auto-disconnect-when-idle to disabled when the field is absent", () => {
+ const value = config();
+ normalizeConnectionTimeouts(value, 12, 34);
+ expect(value.idle_disconnect_secs).toBe(0);
});
it("clamps the manual transaction idle timeout and falls back to the default for unset values", () => {
diff --git a/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts b/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts
index 4342e24eef..a381f08fe0 100644
--- a/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts
+++ b/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts
@@ -1,5 +1,5 @@
import { sidebarProductionBadgeScope } from "@/lib/sidebar/sidebarProductionBadge";
-import { normalizeIdleTimeoutSecs, normalizeManualTransactionTimeoutSecs } from "@/lib/connection/timeoutLimits";
+import { normalizeIdleDisconnectSecs, normalizeIdleTimeoutSecs, normalizeManualTransactionTimeoutSecs } from "@/lib/connection/timeoutLimits";
import { isSingleDatabase } from "@/lib/database/databaseFeatureSupport";
import { normalizeGlobalConnectTimeoutSecs, normalizeGlobalQueryTimeoutSecs } from "@/stores/settingsStore";
import type { ConnectionConfig } from "@/types/database";
@@ -10,6 +10,7 @@ export function normalizeConnectionTimeouts(config: ConnectionConfig, connectTim
config.query_timeout_secs = config.query_timeout_inherit === true ? normalizeGlobalQueryTimeoutSecs(queryTimeoutSecs) : normalizeGlobalQueryTimeoutSecs(queryTimeout);
config.idle_timeout_secs = normalizeIdleTimeoutSecs(config.idle_timeout_secs);
config.manual_transaction_timeout_secs = normalizeManualTransactionTimeoutSecs(config.manual_transaction_timeout_secs);
+ config.idle_disconnect_secs = normalizeIdleDisconnectSecs(config.idle_disconnect_secs);
const keepaliveInterval = Number(config.keepalive_interval_secs);
config.keepalive_interval_secs = Number.isFinite(keepaliveInterval) && keepaliveInterval >= 0 ? keepaliveInterval : 30;
}
diff --git a/apps/desktop/src/lib/connection/timeoutLimits.ts b/apps/desktop/src/lib/connection/timeoutLimits.ts
index ad40653bf0..d886676d26 100644
--- a/apps/desktop/src/lib/connection/timeoutLimits.ts
+++ b/apps/desktop/src/lib/connection/timeoutLimits.ts
@@ -10,6 +10,14 @@ export const MAX_IDLE_TIMEOUT_SECS = 3600;
export const DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS = 300;
export const MIN_MANUAL_TRANSACTION_TIMEOUT_SECS = 30;
export const MAX_MANUAL_TRANSACTION_TIMEOUT_SECS = 86400;
+// 空闲自动断开默认不启用(0)。上限取 86400(24 小时):它对正常使用而言已是「几乎永不」
+// 这类连接的时长上限,既避免写入离谱的大数(如把秒误填成毫秒),又足够覆盖长时间挂起的
+// 空闲会话,不再沿用 idle_timeout 的 3600 以免过早关闭用户有意保留的连接池。
+export const DEFAULT_IDLE_DISCONNECT_SECS = 0;
+export const MAX_IDLE_DISCONNECT_SECS = 86400;
+// 用户把「空闲自动断开」开关打开时填入的初值。取 300 秒(5 分钟):既明显大于「保持连接间隔」
+// 的默认 30 秒(否则一开启就落在保活之前、保活等于白开),又不至于长到让人以为没生效。
+export const DEFAULT_IDLE_DISCONNECT_ENABLED_SECS = 300;
export function normalizeConnectTimeoutSecs(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_CONNECT_TIMEOUT_SECS;
@@ -31,6 +39,12 @@ export function normalizeManualTransactionTimeoutSecs(value: unknown): number {
return Math.min(MAX_MANUAL_TRANSACTION_TIMEOUT_SECS, Math.max(MIN_MANUAL_TRANSACTION_TIMEOUT_SECS, Math.round(value)));
}
+// 非法值/NaN/负数一律回落到默认 0(不启用),超出上限则截断;0 是合法值,需与非法值区分。
+export function normalizeIdleDisconnectSecs(value: unknown): number {
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return DEFAULT_IDLE_DISCONNECT_SECS;
+ return Math.min(MAX_IDLE_DISCONNECT_SECS, Math.round(value));
+}
+
export function supportsIdleTimeout(dbType?: DatabaseType): boolean {
return dbType === "mongodb" || dbType === "mysql" || dbType === "doris" || dbType === "starrocks" || dbType === "manticoresearch";
}
diff --git a/apps/desktop/src/lib/plugins/frontendPlugin.ts b/apps/desktop/src/lib/plugins/frontendPlugin.ts
index 6a4fc6e523..1102094e0a 100644
--- a/apps/desktop/src/lib/plugins/frontendPlugin.ts
+++ b/apps/desktop/src/lib/plugins/frontendPlugin.ts
@@ -281,6 +281,8 @@ export function buildPluginConnectionConfig(pluginId: string, contribution: Plug
query_timeout_secs: existing?.query_timeout_secs || 60,
idle_timeout_secs: existing?.idle_timeout_secs || 60,
manual_transaction_timeout_secs: existing?.manual_transaction_timeout_secs || DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS,
+ // 空闲自动断开默认不启用(0);0 是合法值,故用 ?? 而非 ||。
+ idle_disconnect_secs: existing?.idle_disconnect_secs ?? 0,
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
read_only: existing?.read_only || false,
save_password: existing?.save_password !== false,
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.idleClosed.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.idleClosed.spec.ts
new file mode 100644
index 0000000000..36809557d3
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/connectionStore.idleClosed.spec.ts
@@ -0,0 +1,169 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { ConnectionConfig } from "@/types/database";
+
+const toast = vi.hoisted(() => vi.fn());
+const disconnectDb = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const closeConnectionTabs = vi.hoisted(() => vi.fn());
+const releaseConnectionTabs = vi.hoisted(() => vi.fn());
+const rollbackConnectionTransactions = vi.hoisted(() => vi.fn());
+const flushPendingPersist = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function connection(): ConnectionConfig {
+ return {
+ id: "c1",
+ name: "IdleDB",
+ db_type: "postgres",
+ host: "127.0.0.1",
+ port: 5432,
+ username: "postgres",
+ password: "",
+ database: "app",
+ idle_disconnect_secs: 120,
+ } as ConnectionConfig;
+}
+
+/**
+ * 后端「空闲自动断开」事件(issue #12112)。
+ *
+ * 后端在连接池因空闲被关闭时发送 `dbx:connection-idle-closed`。这属于系统触发的断开,前端
+ * 必须把连接标记为未连接、但保留已打开的查询页签与结果(复用 `disconnect` 的
+ * `skipTabHandling` 路径),且不写「用户已关闭」标记(`markClosedByUser: false`),以便用户
+ * 下次操作时按既有 `ensureConnected` 机制自动重连。
+ */
+describe("connectionStore idle auto-disconnect", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.unstubAllGlobals();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ i18n.global.locale.value = "en";
+ toast.mockReset();
+ disconnectDb.mockReset().mockResolvedValue(undefined);
+ closeConnectionTabs.mockReset();
+ releaseConnectionTabs.mockReset();
+ rollbackConnectionTransactions.mockReset();
+ flushPendingPersist.mockReset().mockResolvedValue(undefined);
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ // 页签策略故意设为 close-tabs:若 skipTabHandling 生效,下面的关闭/清理函数都不应被调用。
+ vi.doMock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { disconnectTabHandlingMode: "close-tabs" } }) }));
+ vi.doMock("@/stores/queryStore", () => ({
+ useQueryStore: () => ({ closeConnectionTabs, releaseConnectionTabs, rollbackConnectionTransactions, flushPendingPersist }),
+ }));
+ // 直接替换 toast 实现,避免测试环境(node)缺少 window.setTimeout。
+ vi.doMock("@/composables/useToast", () => ({ useToast: () => ({ toast }) }));
+ vi.doMock("@/lib/backend/api", () => ({
+ disconnectDb,
+ connectionIsOpen: vi.fn().mockResolvedValue(false),
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ listInstalledAgents: vi.fn().mockResolvedValue([]),
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveConnections: vi.fn().mockResolvedValue(undefined),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ }));
+ });
+
+ async function loadStore() {
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const store = useConnectionStore();
+ const config = connection();
+ store.connections = [config];
+ store.markConnectionConnected(config.id);
+ return store;
+ }
+
+ it("marks the connection offline while keeping its query tabs and results", async () => {
+ const store = await loadStore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "c1" });
+
+ expect(store.connectedIds.has("c1")).toBe(false);
+ // skipTabHandling:即使页签策略是 close-tabs,也绝不能关闭/释放该连接的页签。
+ expect(closeConnectionTabs).not.toHaveBeenCalled();
+ expect(releaseConnectionTabs).not.toHaveBeenCalled();
+ expect(rollbackConnectionTransactions).not.toHaveBeenCalled();
+ expect(disconnectDb).toHaveBeenCalledWith("c1", undefined);
+ expect(toast).toHaveBeenCalledTimes(1);
+ });
+
+ it("is idempotent and never re-notifies for an already-offline connection", async () => {
+ const store = await loadStore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "c1" });
+ await store.handleConnectionIdleClosed({ connectionId: "c1" });
+
+ expect(disconnectDb).toHaveBeenCalledTimes(1);
+ expect(toast).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores an event with a missing connectionId without touching the backend", async () => {
+ const store = await loadStore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "" });
+ await store.handleConnectionIdleClosed(undefined as unknown as { connectionId: string });
+
+ expect(disconnectDb).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ expect(store.connectedIds.has("c1")).toBe(true);
+ });
+
+ it("ignores an event for a connection this frontend never showed as connected", async () => {
+ const store = await loadStore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "never-connected" });
+
+ expect(disconnectDb).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it("ignores an event for a connection whose config was already removed", async () => {
+ const store = await loadStore();
+ store.connections = [];
+
+ await store.handleConnectionIdleClosed({ connectionId: "c1" });
+
+ expect(disconnectDb).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ expect(store.connectedIds.has("c1")).toBe(true);
+ });
+
+ // 迟到事件:清扫发生在本次会话之前,事件到达时用户已经重连。丢掉这次通知即可,
+ // 绝不能把刚建立的新会话一起断掉(否则会连带杀掉新池并弹出误导性提示)。
+ it("ignores a late event for a connection that was already reconnected", async () => {
+ const store = await loadStore();
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(2_000_000);
+ store.markConnectionConnected("c1");
+ nowSpy.mockRestore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "c1", closedAtMs: 1_000_000 });
+
+ expect(disconnectDb).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ expect(store.connectedIds.has("c1")).toBe(true);
+ });
+
+ // 反之,事件晚于当前会话时就该正常处理——避免上面的守卫把合法事件也吞掉。
+ it("still disconnects when the event is newer than the current session", async () => {
+ const store = await loadStore();
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(1_000_000);
+ store.markConnectionConnected("c1");
+ nowSpy.mockRestore();
+
+ await store.handleConnectionIdleClosed({ connectionId: "c1", closedAtMs: 1_500_000 });
+
+ expect(disconnectDb).toHaveBeenCalledWith("c1", undefined);
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(store.connectedIds.has("c1")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 720325b37e..0563ca2982 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -13,6 +13,7 @@ import type {
CompletionAssistantObjectKind,
CompletionAssistantRequest,
ConnectionConfig,
+ ConnectionIdleClosedEvent,
ConnectionLivenessMessage,
DatabaseType,
DatabaseConnectionInfo,
@@ -205,6 +206,7 @@ import { buildCustomTypeTreeChildren } from "@/lib/sidebar/customTypeTree";
import { TreeNodeLoadRegistry, type TreeNodeLoadHandle } from "@/lib/metadata/treeNodeLoadHandle";
import { buildXuguTablespaceChildren } from "@/lib/sidebar/xuguTablespaces";
import i18n, { currentLocale } from "@/i18n";
+import { useToast } from "@/composables/useToast";
import type { MqAdminConfig } from "@/types/mq";
import { RABBITMQ_MQ_TENANT, resolveMqSystemKindFromConnection } from "@/lib/mq/mqConsoleDefaults";
import { applySidebarDatabaseStorage, applySidebarTableStorage, sidebarDatabaseNames, supportsSidebarDatabaseStorage, supportsSidebarTableStorage, type SidebarTableStorageScope } from "@/lib/sidebar/sidebarDatabaseStorage";
@@ -717,6 +719,9 @@ export const useConnectionStore = defineStore("connection", () => {
const cancelledLocalConnectionAttempts = new Map<string, Set<number>>();
const successfulLocalConnectionAttempts = new Map<string, number>();
const connectionStateRevisions = new Map<string, number>();
+ // 每个连接最近一次「建立会话」的本地墙钟时间(Unix 毫秒)。用于识别后端空闲自动断开
+ // 事件的迟到:若连接时间晚于事件里的 `closedAtMs`,说明事件描述的是上一个会话。
+ const connectionConnectedAtMs = new Map<string, number>();
const connectionErrorRevisions = new Map<string, number>();
const tableListSourceRevisions = new Map<string, number>();
const treeNodeLoads = new TreeNodeLoadRegistry();
@@ -1819,6 +1824,8 @@ export const useConnectionStore = defineStore("connection", () => {
query_timeout_inherit: queryTimeoutInherit,
idle_timeout_secs: config.idle_timeout_secs ?? 60,
manual_transaction_timeout_secs: normalizeManualTransactionTimeoutSecs(config.manual_transaction_timeout_secs),
+ // 空闲自动断开默认不启用(0),落盘时同样补默认值。
+ idle_disconnect_secs: config.idle_disconnect_secs ?? 0,
keepalive_interval_secs: config.keepalive_interval_secs ?? DEFAULT_KEEPALIVE_INTERVAL_SECS,
redis_database_aliases: normalizeRedisDatabaseAliases(config.redis_database_aliases),
redis_key_filter: dbType === "redis" && typeof config.redis_key_filter === "string" ? config.redis_key_filter.trim() || undefined : undefined,
@@ -4752,7 +4759,7 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
passwordChangeReconnectRequired.delete(config.id);
activeConnectionId.value = id;
- connectedIds.value.add(id);
+ markConnectionConnected(id);
// 显式连接成功即结束"用户已关闭"状态:页签界面随后的被动唤醒可以正常参与。
clearConnectionClosedByUser(config.id);
clearConnectionClosedByUser(id);
@@ -4904,6 +4911,49 @@ export const useConnectionStore = defineStore("connection", () => {
await confirmConnectionLiveness(message.connectionId);
}
+ /**
+ * 把连接标记为已连接,并记录本次会话建立的本地墙钟时间。
+ *
+ * 所有「连上」的路径都必须走这里,否则 `handleConnectionIdleClosed` 无法判断后端事件是否
+ * 早于当前会话(见该函数的「迟到事件」说明)。
+ */
+ function markConnectionConnected(connectionId: string): void {
+ connectedIds.value.add(connectionId);
+ connectionConnectedAtMs.set(connectionId, Date.now());
+ }
+
+ /**
+ * 处理后端「空闲自动断开」事件(issue #12112):某连接的连接池因空闲超过
+ * `idle_disconnect_secs` 被后端关闭。
+ *
+ * 这是系统触发的断开,而非用户主动关闭,因此复用 `disconnect` 时传
+ * `skipTabHandling: true` 跳过页签策略处理——无论用户配置的 `disconnectTabHandlingMode`
+ * 为何,都保留该连接下已打开的查询页签与结果(与「删除连接」流程同一思路);并传
+ * `markClosedByUser: false`,不写「用户已关闭」标记,使页签下次被触发时能通过既有
+ * `ensureConnected` 自动重连。
+ *
+ * 空值与幂等保护:缺少 connectionId、连接配置已删除、或该连接本就不在已连接集合中时
+ * 直接返回,既不抛异常也不重复弹提示(后端可能对同一次断开重复发送事件)。
+ *
+ * 迟到事件保护:事件通道(web 端 SSE 尤其)可能有缓冲,事件可能在连接已经重新建立之后
+ * 才到达;此时它描述的是上一个会话,直接忽略。否则会把刚建好的新会话一并断掉,并弹出
+ * 误导性的「已空闲断开」提示。缺少 `closedAtMs`(旧后端)时退回原行为。
+ */
+ async function handleConnectionIdleClosed(payload: ConnectionIdleClosedEvent): Promise<void> {
+ const connectionId = payload?.connectionId;
+ if (!connectionId) return;
+ // 已不在已连接集合(用户已手动断开,或此前已处理过该事件)时忽略,避免重复 toast。
+ if (!connectedIds.value.has(connectionId)) return;
+ const closedAtMs = Number(payload.closedAtMs);
+ const connectedAtMs = connectionConnectedAtMs.get(connectionId);
+ if (Number.isFinite(closedAtMs) && connectedAtMs !== undefined && connectedAtMs > closedAtMs) return;
+ const config = getConfig(connectionId);
+ if (!config) return;
+ await disconnect(connectionId, { skipTabHandling: true, markClosedByUser: false });
+ const seconds = config.idle_disconnect_secs ?? 0;
+ useToast().toast(i18n.global.t("connection.idleDisconnectToast", { name: config.name || connectionId, seconds }), 5000);
+ }
+
/**
* 断开连接。
*
@@ -5175,7 +5225,7 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
await syncMongoLegacyDriverFallback(connectionId, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
- connectedIds.value.add(connectionId);
+ markConnectionConnected(connectionId);
// 任何路径真的连上之后,"用户已关闭"标记就不能再拦后续的被动唤醒。
clearConnectionClosedByUser(connectionId);
if (config.db_type !== "plugin") {
@@ -10516,7 +10566,7 @@ export const useConnectionStore = defineStore("connection", () => {
if (!connections.value.find((c) => c.id === normalized.id)) {
connections.value.push(normalized);
}
- connectedIds.value.add(normalized.id);
+ markConnectionConnected(normalized.id);
markConnectionHealthChecked(normalized.id);
clearConnectionError(normalized.id);
}
@@ -10625,6 +10675,8 @@ export const useConnectionStore = defineStore("connection", () => {
hasDisconnectInFlight,
markConnectionOffline,
handleConnectionLivenessMessage,
+ handleConnectionIdleClosed,
+ markConnectionConnected,
metadataGenerationFor,
disconnectAndForgetConnectionPassword,
retirePasswordAfterChange,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 80c98e2053..2c710a0323 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -176,6 +176,14 @@ export interface ConnectionConfig {
idle_timeout_secs?: number;
/** Seconds a manual transaction may sit idle before DBX rolls it back. */
manual_transaction_timeout_secs?: number;
+ /**
+ * 空闲自动断开阈值(秒):后端在连接池层面实现,连接在此秒数内无任何查询活动时自动关闭其
+ * 连接池;前端据此把连接标记为未连接并保留已打开的页签与结果,供用户下次操作时自动重连。
+ *
+ * 0(默认)表示不启用。与 `idle_timeout_secs` 语义不同:后者只回收连接池内的空闲物理连接,
+ * 不会关闭整个连接池;本字段关闭的是整个连接池。所有方言均适用(与方言无关)。
+ */
+ idle_disconnect_secs?: number;
keepalive_interval_secs?: number;
ssl?: boolean;
ca_cert_path?: string;
@@ -277,6 +285,15 @@ export type ConnectionLivenessFailureKind = "probe_failed" | "timed_out";
*/
export type ConnectionLivenessMessage = { kind: "lost"; connectionId: string; failureKind: ConnectionLivenessFailureKind } | { kind: "resync" };
+/**
+ * 后端「空闲自动断开」事件(`dbx:connection-idle-closed`)的载荷:某个连接的连接池因空闲
+ * 超过 `idle_disconnect_secs` 被后端自动关闭。前端收到后把该连接标记为未连接并保留页签。
+ *
+ * `closedAtMs` 是后端关闭时的墙钟时间(Unix 毫秒):事件通道可能有缓冲,若本连接在事件
+ * 到达之前已经重新建立,说明这次断开描述的是上一个会话,前端必须忽略,否则会关掉新会话。
+ */
+export type ConnectionIdleClosedEvent = { connectionId: string; closedAtMs?: number };
+
export type TransportLayerConfig = ({ type: "ssh" } & SshTunnelConfig) | ({ type: "proxy" } & ProxyTunnelConfig) | ({ type: "http_tunnel" } & HttpTunnelConfig);
/**
diff --git a/crates/dbx-core/examples/table_import_live_bench.rs b/crates/dbx-core/examples/table_import_live_bench.rs
index 6c082ce364..169dd4d576 100644
--- a/crates/dbx-core/examples/table_import_live_bench.rs
+++ b/crates/dbx-core/examples/table_import_live_bench.rs
@@ -185,6 +185,7 @@ fn connection_config(id: &str, database: BenchDatabase) -> Result<ConnectionConf
query_timeout_secs: 120,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: std::env::var("DBX_BENCH_SSL").is_ok_and(|value| value.eq_ignore_ascii_case("true")),
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/admin/mq/config.rs b/crates/dbx-core/src/admin/mq/config.rs
index f422b9761e..c4a16d7e3f 100644
--- a/crates/dbx-core/src/admin/mq/config.rs
+++ b/crates/dbx-core/src/admin/mq/config.rs
@@ -225,6 +225,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/admin/mq/service.rs b/crates/dbx-core/src/admin/mq/service.rs
index b369a8311b..82d77c767c 100644
--- a/crates/dbx-core/src/admin/mq/service.rs
+++ b/crates/dbx-core/src/admin/mq/service.rs
@@ -952,6 +952,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/admin/nacos/config.rs b/crates/dbx-core/src/admin/nacos/config.rs
index 63c089dce6..ad26337467 100644
--- a/crates/dbx-core/src/admin/nacos/config.rs
+++ b/crates/dbx-core/src/admin/nacos/config.rs
@@ -397,6 +397,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/admin/nacos/service.rs b/crates/dbx-core/src/admin/nacos/service.rs
index f294d206a6..49b7c8fcdd 100644
--- a/crates/dbx-core/src/admin/nacos/service.rs
+++ b/crates/dbx-core/src/admin/nacos/service.rs
@@ -673,6 +673,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
@@ -762,6 +763,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rs
index 5656d70970..a0eb8f6b30 100644
--- a/crates/dbx-core/src/ai/agent_tools.rs
+++ b/crates/dbx-core/src/ai/agent_tools.rs
@@ -2024,6 +2024,7 @@ for line in sys.stdin:
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 30,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/connection/connection_secrets.rs b/crates/dbx-core/src/connection/connection_secrets.rs
index 36f21b8900..39b1120a1d 100644
--- a/crates/dbx-core/src/connection/connection_secrets.rs
+++ b/crates/dbx-core/src/connection/connection_secrets.rs
@@ -1127,6 +1127,7 @@ mod tests {
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
idle_timeout_secs: crate::models::connection::default_idle_timeout_secs(),
manual_transaction_timeout_secs: crate::models::connection::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: crate::models::connection::default_idle_disconnect_secs(),
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index e675138bdb..c35a8f81d4 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -33,8 +33,8 @@ use crate::db::proxy_tunnel::ProxyTunnelManager;
use crate::db::ssh_tunnel::TunnelManager;
use crate::models::connection::{
database_info_from_protocol_value, parse_jdbc_host_port, parse_mongo_first_host, rewrite_jdbc_url_host,
- validate_jdbc_transport_url, ConnectionConfig, ConnectionLivenessFailureKind, ConnectionLivenessMessage,
- ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, TransportLayerConfig,
+ validate_jdbc_transport_url, ConnectionConfig, ConnectionIdleClosedEvent, ConnectionLivenessFailureKind,
+ ConnectionLivenessMessage, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType, TransportLayerConfig,
};
use crate::mongo_oidc::MongoOidcBrowserOpener;
use crate::nacos::config::{NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD};
@@ -447,6 +447,10 @@ pub struct AppState {
/// publishes here once a connection has no pools left; each shell relays it to its own
/// frontend, so DBX core never needs a UI handle of its own.
connection_liveness: tokio::sync::broadcast::Sender<ConnectionLivenessMessage>,
+ /// 连接因空闲被自动断开的通知(#12112)。`sweep_idle_connections` 关闭某个连接的池后
+ /// 在这里发布;两个 shell 各自转发给前端(desktop 用 Tauri 事件、web 用 SSE),
+ /// DBX core 因此不需要任何 UI 句柄。
+ connection_idle_closed: tokio::sync::broadcast::Sender<ConnectionIdleClosedEvent>,
mongo_oidc_browser_opener: std::sync::RwLock<Option<MongoOidcBrowserOpener>>,
salesforce_browser_opener: std::sync::RwLock<Option<SfBrowserOpener>>,
#[cfg(feature = "mq-admin")]
@@ -474,6 +478,14 @@ fn pool_activity_now_ms() -> u64 {
POOL_ACTIVITY_BASE_MS + pool_activity_epoch().elapsed().as_millis() as u64
}
+/// 当前墙钟时间(Unix 毫秒)。
+///
+/// 与 `pool_activity_now_ms` 的单调时钟不同:后者只在进程内可比,而空闲断开事件要跨进程与
+/// 前端比较(web 端是浏览器与服务端两个进程),因此必须用墙钟。
+fn unix_now_ms() -> u64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as u64)
+}
+
#[cfg_attr(not(test), allow(dead_code))]
struct PoolActivity {
last_used_at_ms: std::sync::atomic::AtomicU64,
@@ -1476,6 +1488,14 @@ impl AppState {
self.connection_liveness.subscribe()
}
+ /// 订阅「连接因空闲被自动断开」的通知(#12112)。
+ ///
+ /// 由各 shell 转发给自己的前端;与 liveness 通道同样只在启动时订阅一次并长期持有
+ /// receiver,因为后订阅者收不到订阅之前发布的消息。
+ pub fn subscribe_connection_idle_closed(&self) -> tokio::sync::broadcast::Receiver<ConnectionIdleClosedEvent> {
+ self.connection_idle_closed.subscribe()
+ }
+
/// A locator belongs to its original workload session; never recreate it during lookup.
pub(crate) async fn existing_workload_pool_for_session(
&self,
@@ -1735,6 +1755,9 @@ impl AppState {
// lagged receiver re-syncs from the read-only status check on its next use, so
// dropping events here is safe.
connection_liveness: tokio::sync::broadcast::Sender::new(64),
+ // 同样有界;空闲断开事件量极小(每次只对应一个连接),64 足够覆盖两个 shell
+ // 短时未排空的情况。
+ connection_idle_closed: tokio::sync::broadcast::Sender::new(64),
mongo_oidc_browser_opener: std::sync::RwLock::new(None),
salesforce_browser_opener: std::sync::RwLock::new(None),
#[cfg(feature = "mq-admin")]
@@ -6001,6 +6024,103 @@ impl AppState {
self.pool_routing_control().close_removed_in_background(removed);
}
+ /// 关闭「空闲已超过 `idle_disconnect_secs`」的连接名下全部连接池,返回被关闭的 connection id 列表。
+ ///
+ /// 与 `idle_timeout_secs` 的区别:后者只回收连接池内部空闲的物理连接,池本身仍保留;
+ /// 本方法在连接连续无查询活动超过阈值时,彻底关闭该连接名下全部池(含会话级池),
+ /// 释放长会话长期占用的连接资源。`idle_disconnect_secs == 0`(默认)表示不启用。
+ ///
+ /// 判定保守:只要该连接名下存在「正在执行查询」「手动事务池(或 MySQL 显式保留事务)」
+ /// 「缺少活动记录」中的任一池,就整体跳过,避免误关活跃会话或丢掉未提交事务。
+ /// 并发安全:方法可能被定时任务反复调用;各锁只做快照后立即释放,绝不在持有
+ /// `connections`/`pool_activity` 写锁时 await I/O;被关掉的连接下一拍已不在注册表,天然幂等。
+ pub async fn sweep_idle_connections(&self) -> Vec<String> {
+ // 1. 快照启用了空闲自动断开的连接(只取 id 与阈值),未启用的连接一律不处理。
+ let candidates: Vec<(String, u64)> = self
+ .configs
+ .read()
+ .await
+ .iter()
+ .filter(|(_, config)| config.idle_disconnect_secs > 0)
+ .map(|(connection_id, config)| (connection_id.clone(), config.idle_disconnect_secs))
+ .collect();
+
+ // MySQL 显式保留事务的池键集合(保护未提交事务),一次性快照,避免循环内反复加锁。
+ let preserved_transactions: HashSet<String> =
+ self.mysql_preserved_transactions.read().await.iter().cloned().collect();
+
+ let now_ms = pool_activity_now_ms();
+ let mut closed = Vec::new();
+
+ for (connection_id, idle_disconnect_secs) in candidates {
+ // 2. 收集该连接名下所有池键;没有任何池则直接跳过。
+ let pool_keys: Vec<String> = {
+ let connections = self.connections.read().await;
+ connections.keys().filter(|key| pool_key_belongs_to_connection(key, &connection_id)).cloned().collect()
+ };
+ if pool_keys.is_empty() {
+ continue;
+ }
+
+ // 3a. 取该连接名下所有池「最后使用时间」的最大值;任一池缺少活动记录即保守跳过
+ // (刚建好、尚无真实查询记录的池不做超时判断)。快照后立即释放读锁。
+ let mut latest_used_at_ms = 0u64;
+ let mut has_unrecorded_pool = false;
+ {
+ let activity = self.pool_activity.read().await;
+ for key in &pool_keys {
+ match activity.get(key) {
+ Some(entry) => {
+ let used = entry.last_used_at_ms.load(Ordering::Relaxed);
+ latest_used_at_ms = latest_used_at_ms.max(used);
+ }
+ None => {
+ has_unrecorded_pool = true;
+ break;
+ }
+ }
+ }
+ }
+ if has_unrecorded_pool {
+ continue;
+ }
+
+ // 3b. 有正在执行的查询、或属于手动事务保护的池 → 跳过整个连接,避免打断会话/丢数据。
+ let blocked = pool_keys.iter().any(|key| {
+ self.running_queries.is_pool_active(key)
+ || is_manual_transaction_pool_key(key)
+ || preserved_transactions.contains(key)
+ });
+ if blocked {
+ continue;
+ }
+
+ // 4. 该连接最近一次活动距今是否已超过阈值(毫秒比较,saturating 防止减法下溢)。
+ let idle_ms = idle_disconnect_secs.saturating_mul(1000);
+ if now_ms.saturating_sub(latest_used_at_ms) <= idle_ms {
+ continue;
+ }
+
+ // 5. 复用既有池回收路径:先摘除,再走后台关闭。close_removed_in_background 内部
+ // 经 close_pool_with_timeout,从而继承 Agent 共享 runtime / 手动事务共享 runtime
+ // 的保护逻辑,确保池被真正 close/释放而不只是从 map 移除。
+ let removed = self.drain_connection_pools(&connection_id).await;
+ self.pool_routing_control().close_removed_in_background(removed);
+ log::info!(
+ "[connection][idle_disconnect] connection '{connection_id}' pools closed after {idle_disconnect_secs}s without query activity"
+ );
+ // 发布给各 shell 转发到前端;发送失败(没有任何订阅者)不影响关闭本身。
+ // 带上墙钟时间,供前端识别「迟到事件」:若本连接的建立时间晚于该时刻,说明
+ // 事件描述的是上一个会话,前端应忽略,避免连带关掉刚重连出来的新会话。
+ let _ = self
+ .connection_idle_closed
+ .send(ConnectionIdleClosedEvent { connection_id: connection_id.clone(), closed_at_ms: unix_now_ms() });
+ closed.push(connection_id);
+ }
+
+ closed
+ }
+
#[cfg(feature = "mq-admin")]
async fn persist_removed_mqtt_history(&self, removed: &mut Vec<(String, PoolKind)>) {
let mut remaining = Vec::with_capacity(removed.len());
@@ -7469,6 +7589,7 @@ mod tests {
query_timeout_secs: crate::models::connection::default_query_timeout_secs(),
idle_timeout_secs: crate::models::connection::default_idle_timeout_secs(),
manual_transaction_timeout_secs: crate::models::connection::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: crate::models::connection::default_idle_disconnect_secs(),
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
@@ -10055,6 +10176,7 @@ sleep 30
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: interval_secs,
ssl: false,
ca_cert_path: String::new(),
@@ -10484,6 +10606,171 @@ for line in sys.stdin:
assert_eq!(activity.last_used_at_ms.load(std::sync::atomic::Ordering::Relaxed), newer);
}
+ /// 空闲自动断开(issue #12112):阈值到期且无活跃查询、无手动事务时,关闭该连接名下
+ /// 全部连接池(含会话级池——长会话占用连接资源的来源),并返回被关闭的 connection id。
+ #[tokio::test]
+ async fn sweep_idle_connections_closes_connection_after_threshold() {
+ let (state, dir) = test_app_state().await;
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.idle_disconnect_secs = 60;
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ for key in ["conn", "conn:session:tab-1"] {
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert(key.to_string(), PoolKind::Sqlite(pool));
+ state
+ .pool_activity
+ .write()
+ .await
+ .insert(key.to_string(), super::PoolActivity::idle_for(std::time::Duration::from_secs(600)));
+ }
+
+ let closed = state.sweep_idle_connections().await;
+
+ assert_eq!(closed, vec!["conn".to_string()]);
+ assert!(state.connections.read().await.keys().next().is_none());
+ assert!(state.pool_activity.read().await.is_empty());
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// 清扫命中后必须把事件发布到广播通道:两个 shell 都靠它转发给前端,漏发则前端不会把
+ /// 连接标记为未连接(桌面不弹 toast、web 侧 SSE 也收不到)。这里同时锁定载荷形状——
+ /// 必须序列化成 camelCase 的 `connectionId`,与前端 `ConnectionIdleClosedEvent` 一致。
+ #[tokio::test]
+ async fn sweep_idle_connections_publishes_idle_closed_event() {
+ let (state, dir) = test_app_state().await;
+ let mut events = state.subscribe_connection_idle_closed();
+
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.idle_disconnect_secs = 60;
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert("conn".to_string(), PoolKind::Sqlite(pool));
+ state
+ .pool_activity
+ .write()
+ .await
+ .insert("conn".to_string(), super::PoolActivity::idle_for(std::time::Duration::from_secs(600)));
+
+ assert_eq!(state.sweep_idle_connections().await, vec!["conn".to_string()]);
+
+ let event = events.try_recv().expect("idle-closed event must be published");
+ assert_eq!(event.connection_id, "conn");
+ // 载荷必须与前端类型一致:camelCase 的 `connectionId` / `closedAtMs`,其中墙钟时间
+ // 供前端识别迟到事件(见 `unix_now_ms` 的说明)。
+ assert!(event.closed_at_ms > 0, "the event must carry a wall-clock close time");
+ let payload = serde_json::to_value(&event).unwrap();
+ assert_eq!(payload["connectionId"], "conn");
+ assert!(payload["closedAtMs"].as_u64().is_some_and(|value| value > 0));
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// 默认值 `idle_disconnect_secs == 0` 表示不启用:池再空闲也不能被自动关闭。
+ #[tokio::test]
+ async fn sweep_idle_connections_skips_disabled_connection() {
+ let (state, dir) = test_app_state().await;
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ assert_eq!(config.idle_disconnect_secs, 0);
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert("conn".to_string(), PoolKind::Sqlite(pool));
+ state
+ .pool_activity
+ .write()
+ .await
+ .insert("conn".to_string(), super::PoolActivity::idle_for(std::time::Duration::from_secs(600)));
+
+ assert!(state.sweep_idle_connections().await.is_empty());
+ assert!(state.connections.read().await.contains_key("conn"));
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// 尚未到达阈值(最近仍有查询活动)的连接不能被关闭。
+ #[tokio::test]
+ async fn sweep_idle_connections_keeps_recently_used_connection() {
+ let (state, dir) = test_app_state().await;
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.idle_disconnect_secs = 60;
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert("conn".to_string(), PoolKind::Sqlite(pool));
+ state.pool_activity.write().await.insert("conn".to_string(), super::PoolActivity::now());
+
+ assert!(state.sweep_idle_connections().await.is_empty());
+ assert!(state.connections.read().await.contains_key("conn"));
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// 有正在执行的查询时跳过整个连接,避免打断用户会话。守卫 `_query` 必须在断言之后
+ /// 才释放,否则任务注销会让判定失效。
+ #[tokio::test]
+ async fn sweep_idle_connections_skips_connection_with_running_query() {
+ let (state, dir) = test_app_state().await;
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.idle_disconnect_secs = 60;
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert("conn".to_string(), PoolKind::Sqlite(pool));
+ state
+ .pool_activity
+ .write()
+ .await
+ .insert("conn".to_string(), super::PoolActivity::idle_for(std::time::Duration::from_secs(600)));
+
+ let _query = state.running_queries.register("idle-sweep-active".to_string());
+ state.running_queries.set_pool_key("idle-sweep-active", "conn");
+
+ assert!(state.sweep_idle_connections().await.is_empty());
+ assert!(state.connections.read().await.contains_key("conn"));
+
+ drop(_query);
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
+ /// 手动事务池在保护中时跳过整个连接,避免丢掉未提交事务。MySQL 显式保留事务的池键
+ /// 同样受保护,这里用前者(池键含 `:session:manual-txn-`)覆盖判定分支。
+ #[tokio::test]
+ async fn sweep_idle_connections_skips_connection_with_manual_transaction() {
+ let (state, dir) = test_app_state().await;
+ let mut config = mysql_config(None);
+ config.id = "conn".to_string();
+ config.db_type = DatabaseType::Sqlite;
+ config.idle_disconnect_secs = 60;
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let pool_key = "conn:session:manual-txn-1";
+ let pool = crate::db::sqlite::connect_path(":memory:").await.unwrap();
+ state.connections.write().await.insert(pool_key.to_string(), PoolKind::Sqlite(pool));
+ state
+ .pool_activity
+ .write()
+ .await
+ .insert(pool_key.to_string(), super::PoolActivity::idle_for(std::time::Duration::from_secs(600)));
+
+ assert!(state.sweep_idle_connections().await.is_empty());
+ assert!(state.connections.read().await.contains_key(pool_key));
+
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[tokio::test]
async fn session_scoped_pool_is_not_closed_by_idle_timeout() {
let (state, dir) = test_app_state().await;
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rs
index 80e290d61b..731f692331 100644
--- a/crates/dbx-core/src/data/transfer.rs
+++ b/crates/dbx-core/src/data/transfer.rs
@@ -13693,6 +13693,7 @@ for line in sys.stdin:
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
@@ -20941,6 +20942,7 @@ SELECT 1 FROM dual"#
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rs
index d069ca1613..38b35a5761 100644
--- a/crates/dbx-core/src/persistence/cloud_sync.rs
+++ b/crates/dbx-core/src/persistence/cloud_sync.rs
@@ -3695,6 +3695,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
@@ -3785,6 +3786,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
@@ -4157,6 +4159,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index 5f83afbc01..871c63bba0 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -12039,6 +12039,7 @@ mod tests {
query_timeout_secs: 300,
idle_timeout_secs: 600,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
@@ -12120,6 +12121,7 @@ mod tests {
query_timeout_secs: 300,
idle_timeout_secs: 600,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: crate::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rs
index f11c04d783..786de464fa 100644
--- a/crates/dbx-core/src/query/mod.rs
+++ b/crates/dbx-core/src/query/mod.rs
@@ -8603,6 +8603,7 @@ for line in sys.stdin:
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 30,
ssl: false,
ca_cert_path: String::new(),
@@ -11729,6 +11730,7 @@ for line in sys.stdin:
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/safety/production_safety.rs b/crates/dbx-core/src/safety/production_safety.rs
index d8aea7d87f..7c2b437c14 100644
--- a/crates/dbx-core/src/safety/production_safety.rs
+++ b/crates/dbx-core/src/safety/production_safety.rs
@@ -911,6 +911,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 30,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rs
index 6380db003f..8cd9d357c0 100644
--- a/crates/dbx-core/src/schema/mod.rs
+++ b/crates/dbx-core/src/schema/mod.rs
@@ -3416,6 +3416,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/src/schema/normalization.rs b/crates/dbx-core/src/schema/normalization.rs
index c055a9e272..2291c80004 100644
--- a/crates/dbx-core/src/schema/normalization.rs
+++ b/crates/dbx-core/src/schema/normalization.rs
@@ -174,6 +174,7 @@ mod tests {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/connection_url_compatibility.rs b/crates/dbx-core/tests/connection_url_compatibility.rs
index 7b52b7c1a3..f58f310a5f 100644
--- a/crates/dbx-core/tests/connection_url_compatibility.rs
+++ b/crates/dbx-core/tests/connection_url_compatibility.rs
@@ -1,7 +1,7 @@
use dbx_core::models::connection::{
- default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
- default_manual_transaction_timeout_secs, default_query_timeout_secs, default_redis_key_separator, ConnectionConfig,
- DatabaseType,
+ default_connect_timeout_secs, default_idle_disconnect_secs, default_idle_timeout_secs,
+ default_keepalive_interval_secs, default_manual_transaction_timeout_secs, default_query_timeout_secs,
+ default_redis_key_separator, ConnectionConfig, DatabaseType,
};
use std::str::FromStr;
@@ -38,6 +38,7 @@ fn mysql_config(username: &str, password: &str, database: Option<&str>) -> Conne
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: default_idle_timeout_secs(),
manual_transaction_timeout_secs: default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: default_idle_disconnect_secs(),
keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/dump_docs_fixture.rs b/crates/dbx-core/tests/dump_docs_fixture.rs
index 7d5b3fc633..3ea8a84b67 100644
--- a/crates/dbx-core/tests/dump_docs_fixture.rs
+++ b/crates/dbx-core/tests/dump_docs_fixture.rs
@@ -49,6 +49,7 @@ fn live_postgres_config(
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_docs_annotations.rs b/crates/dbx-core/tests/live_postgres_docs_annotations.rs
index 3db2f25325..eb777f9ef2 100644
--- a/crates/dbx-core/tests/live_postgres_docs_annotations.rs
+++ b/crates/dbx-core/tests/live_postgres_docs_annotations.rs
@@ -45,6 +45,7 @@ fn live_postgres_config(
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
index 11deb78508..61cd46d42b 100644
--- a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
+++ b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs
@@ -40,6 +40,7 @@ fn live_postgres_config(
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_error_position.rs b/crates/dbx-core/tests/live_postgres_error_position.rs
index 23216bfe9e..c626a05877 100644
--- a/crates/dbx-core/tests/live_postgres_error_position.rs
+++ b/crates/dbx-core/tests/live_postgres_error_position.rs
@@ -194,6 +194,7 @@ fn live_connection_config(
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_query_result_export.rs b/crates/dbx-core/tests/live_postgres_query_result_export.rs
index e117578024..09c11eb9d6 100644
--- a/crates/dbx-core/tests/live_postgres_query_result_export.rs
+++ b/crates/dbx-core/tests/live_postgres_query_result_export.rs
@@ -45,6 +45,7 @@ fn live_postgres_config(
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rs
index 8453ed022c..510636aa3b 100644
--- a/crates/dbx-core/tests/live_postgres_transfer.rs
+++ b/crates/dbx-core/tests/live_postgres_transfer.rs
@@ -40,6 +40,7 @@ fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs
index 0321d772aa..04eff79416 100644
--- a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs
+++ b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs
@@ -44,6 +44,7 @@ fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rs
index 0194deec99..98db7a2de5 100644
--- a/crates/dbx-core/tests/live_sqlserver_completion.rs
+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs
@@ -46,6 +46,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connecti
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
index ad1e18f61b..0e170fd9db 100644
--- a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
+++ b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs
@@ -35,6 +35,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connecti
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs
index 3e78a6f47c..9626bdca12 100644
--- a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs
+++ b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs
@@ -50,6 +50,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connecti
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/live_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlserver_transfer.rs
index ac08e3f616..ed32651ef9 100644
--- a/crates/dbx-core/tests/live_sqlserver_transfer.rs
+++ b/crates/dbx-core/tests/live_sqlserver_transfer.rs
@@ -39,6 +39,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> ConnectionConfig {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-core/tests/support/mod.rs b/crates/dbx-core/tests/support/mod.rs
index 2823526ba3..3649610366 100644
--- a/crates/dbx-core/tests/support/mod.rs
+++ b/crates/dbx-core/tests/support/mod.rs
@@ -160,6 +160,7 @@ pub fn postgres_test_config(id: &str, port: u16) -> ConnectionConfig {
query_timeout_secs: 30,
idle_timeout_secs: 60,
manual_transaction_timeout_secs: 300,
+ idle_disconnect_secs: 0,
keepalive_interval_secs: 0,
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-driver-agent/src/agent_connection.rs b/crates/dbx-driver-agent/src/agent_connection.rs
index 6cacc4f4a8..c2984094ab 100644
--- a/crates/dbx-driver-agent/src/agent_connection.rs
+++ b/crates/dbx-driver-agent/src/agent_connection.rs
@@ -779,8 +779,9 @@ fn hive_parameters_use_zookeeper_discovery(source: &str) -> bool {
mod tests {
use super::*;
use crate::models::connection::{
- default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
- default_manual_transaction_timeout_secs, default_query_timeout_secs, default_redis_key_separator,
+ default_connect_timeout_secs, default_idle_disconnect_secs, default_idle_timeout_secs,
+ default_keepalive_interval_secs, default_manual_transaction_timeout_secs, default_query_timeout_secs,
+ default_redis_key_separator,
};
fn config(db_type: DatabaseType, database: Option<&str>) -> ConnectionConfig {
@@ -816,6 +817,7 @@ mod tests {
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: default_idle_timeout_secs(),
manual_transaction_timeout_secs: default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: default_idle_disconnect_secs(),
keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rs
index 84466888ee..7976090df7 100644
--- a/crates/dbx-driver-redis/src/lib.rs
+++ b/crates/dbx-driver-redis/src/lib.rs
@@ -10538,6 +10538,7 @@ mod tests {
query_timeout_secs: dbx_types::models::connection::default_query_timeout_secs(),
idle_timeout_secs: dbx_types::models::connection::default_idle_timeout_secs(),
manual_transaction_timeout_secs: dbx_types::models::connection::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: dbx_types::models::connection::default_idle_disconnect_secs(),
keepalive_interval_secs: dbx_types::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rs
index 44ee6bde08..d11780f66c 100644
--- a/crates/dbx-types/src/models/connection.rs
+++ b/crates/dbx-types/src/models/connection.rs
@@ -41,6 +41,25 @@ pub enum ConnectionLivenessMessage {
Resync,
}
+/// A message on the connection-idle-closed channel (#12112).
+///
+/// Published when a connection's pools were closed because the connection stayed idle
+/// longer than its own `idle_disconnect_secs`. One shape for both shells and both
+/// transports, so the frontend parses the same payload everywhere: the desktop shell
+/// forwards it as the `dbx:connection-idle-closed` event, the web shell streams it over
+/// SSE. `connectionId` is camelCase in JSON to match the frontend type.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectionIdleClosedEvent {
+ pub connection_id: String,
+ /// 关闭发生的墙钟时间(Unix 毫秒)。
+ ///
+ /// 前端用它识别「迟到事件」:SSE / 事件通道都有缓冲,事件可能在本连接已经重新建立
+ /// 之后才到达;此时这次断开描述的已经是上一个会话,前端应忽略,否则会连带关掉刚建好
+ /// 的新会话。用墙钟而非 `Instant` 是因为要跨进程(web 端是浏览器与服务端)比较。
+ pub closed_at_ms: u64,
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct DatabaseConnectionInfo {
@@ -189,6 +208,12 @@ pub struct ConnectionConfig {
pub idle_timeout_secs: u64,
#[serde(default = "default_manual_transaction_timeout_secs")]
pub manual_transaction_timeout_secs: u64,
+ /// 连接空闲自动断开阈值(秒):该连接连续多少秒没有任何查询活动,就关闭其名下
+ /// 全部连接池。0 表示不启用(opt-in),旧配置缺字段时反序列化即为 0,行为不变。
+ /// 注意:与上面的 `idle_timeout_secs`(连接池内空闲物理连接的回收)语义不同,
+ /// 两者并存但互不影响。
+ #[serde(default = "default_idle_disconnect_secs")]
+ pub idle_disconnect_secs: u64,
#[serde(default = "default_keepalive_interval_secs")]
pub keepalive_interval_secs: u64,
#[serde(default)]
@@ -605,6 +630,12 @@ pub fn default_manual_transaction_timeout_secs() -> u64 {
DEFAULT_MANUAL_TRANSACTION_TIMEOUT_SECS
}
+/// 「连接空闲自动断开」阈值的默认值:0 表示默认不启用(opt-in)。
+/// 独立于 `default_idle_timeout_secs`,避免老配置被赋予超时关闭语义。
+pub fn default_idle_disconnect_secs() -> u64 {
+ 0
+}
+
pub fn default_keepalive_interval_secs() -> u64 {
30
}
@@ -688,6 +719,8 @@ struct ConnectionConfigData {
pub idle_timeout_secs: u64,
#[serde(default = "default_manual_transaction_timeout_secs")]
pub manual_transaction_timeout_secs: u64,
+ #[serde(default = "default_idle_disconnect_secs")]
+ pub idle_disconnect_secs: u64,
#[serde(default = "default_keepalive_interval_secs")]
pub keepalive_interval_secs: u64,
#[serde(default)]
@@ -802,6 +835,7 @@ impl From<ConnectionConfigData> for ConnectionConfig {
query_timeout_secs: data.query_timeout_secs,
idle_timeout_secs: data.idle_timeout_secs,
manual_transaction_timeout_secs: data.manual_transaction_timeout_secs,
+ idle_disconnect_secs: data.idle_disconnect_secs,
keepalive_interval_secs: data.keepalive_interval_secs,
ssl: data.ssl,
ca_cert_path: data.ca_cert_path,
@@ -3215,6 +3249,7 @@ mod tests {
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: super::default_idle_timeout_secs(),
manual_transaction_timeout_secs: super::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: super::default_idle_disconnect_secs(),
keepalive_interval_secs: super::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
@@ -3599,6 +3634,31 @@ mod tests {
assert_eq!(config.effective_connect_timeout_secs(), 10);
}
+ #[test]
+ fn missing_idle_disconnect_defaults_to_zero() {
+ // 老配置没有 idle_disconnect_secs 字段时,必须反序列化为 0(不启用),
+ // 保证既有连接不会被赋予空闲超时自动关闭的行为。
+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
+ "id": "id",
+ "name": "name",
+ "db_type": "mysql",
+ "host": "10.1.2.3",
+ "port": 3306,
+ "username": "root",
+ "password": "",
+ "database": null
+ }))
+ .unwrap();
+
+ assert_eq!(config.idle_disconnect_secs, 0);
+ // 显式配置后能正常往返,且不影响并存的 idle_timeout_secs。
+ let mut value = serde_json::to_value(&config).unwrap();
+ value["idle_disconnect_secs"] = serde_json::json!(120);
+ let configured: ConnectionConfig = serde_json::from_value(value).unwrap();
+ assert_eq!(configured.idle_disconnect_secs, 120);
+ assert_eq!(configured.idle_timeout_secs, super::default_idle_timeout_secs());
+ }
+
#[test]
fn legacy_ssh_tunnels_migrate_to_ordered_transport_layers() {
let config: ConnectionConfig = serde_json::from_value(serde_json::json!({
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index 7a711147ee..18ebb79470 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -623,6 +623,7 @@ async fn serve() -> Result<(), String> {
ssh_prompt::install_web_ssh_prompt_bridge(web_state.ssh_prompts.clone());
routes::sql_file::start_sql_file_cleanup(&web_state);
+ routes::connection::start_connection_idle_sweeper(&web_state);
let backup_root = std::env::var_os("DBX_BACKUP_ROOT")
.map(std::path::PathBuf::from)
@@ -665,6 +666,7 @@ async fn serve() -> Result<(), String> {
.route("/connection/check-health", post(routes::connection::check_connection_health))
.route("/connection/is-open", post(routes::connection::connection_is_open))
.route("/connection/liveness-events", get(routes::connection::connection_liveness_events))
+ .route("/connection/idle-closed-events", get(routes::connection::connection_idle_closed_events))
.route("/connection/prewarm", post(routes::connection::prewarm_connection))
.route("/connection/session-credential-status", post(routes::connection::session_credential_status))
.route("/connection/forget-session-credential", post(routes::connection::forget_session_credential))
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index f068458ed8..5d1bb86ea6 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -11,7 +11,8 @@ use dbx_core::connection::{
connection_configs_pool_equivalent, connection_configs_session_credentials_compatible, AppState, PoolKind,
};
use dbx_core::models::connection::{
- ConnectionConfig, ConnectionLivenessMessage, ConnectionTestResult, DatabaseConnectionInfo, DatabaseType,
+ ConnectionConfig, ConnectionIdleClosedEvent, ConnectionLivenessMessage, ConnectionTestResult,
+ DatabaseConnectionInfo, DatabaseType,
};
use dbx_core::nacos::config::{
take_transient_passwords, NACOS_CONSOLE_SESSION_PASSWORD, NACOS_PRIMARY_SESSION_PASSWORD,
@@ -735,6 +736,67 @@ pub async fn connection_liveness_events(
Sse::new(stream).keep_alive(KeepAlive::default())
}
+/// Serialise one idle-closed message for the SSE stream, or `None` when serialisation fails.
+fn idle_closed_sse_event(event: &ConnectionIdleClosedEvent) -> Option<Event> {
+ match serde_json::to_string(event) {
+ Ok(payload) => Some(Event::default().data(payload)),
+ // The payload is a struct of plain fields, so this is unreachable in practice.
+ Err(error) => {
+ log::warn!("Connection idle-closed event could not be serialised: {error}");
+ None
+ }
+ }
+}
+
+/// Stream backend idle-closed notifications to the browser (#12112).
+///
+/// The payload is byte-identical to what the desktop shell emits as
+/// `dbx:connection-idle-closed`, so the frontend parses one shape on both transports.
+pub async fn connection_idle_closed_events(
+ State(state): State<Arc<WebState>>,
+) -> Sse<impl futures::Stream<Item = Result<Event, Infallible>>> {
+ let mut events = state.app.subscribe_connection_idle_closed();
+ let stream = stream! {
+ loop {
+ match events.recv().await {
+ Ok(event) => {
+ if let Some(event) = idle_closed_sse_event(&event) {
+ yield Ok(event);
+ }
+ }
+ // 丢弃事件不影响正确性:前端下次触发查询时会经 `ensureConnected` 自动重连,
+ // 侧边栏状态也会在下一次刷新时对齐,因此这里只记日志、不做 resync 补偿。
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Web connection idle-closed stream skipped {skipped} messages");
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ };
+ Sse::new(stream).keep_alive(KeepAlive::default())
+}
+
+/// 启动「空闲自动断开」定时清扫(issue #12112)。
+///
+/// web shell 与 desktop shell 一样只负责传输:这里周期调用 core 的
+/// `sweep_idle_connections` 触发清扫,关闭结果由 core 发布到广播通道,再由
+/// [`connection_idle_closed_events`] 以 SSE 下发给浏览器。
+///
+/// 用 `Weak` 持有状态:前端 WebState 被销毁后任务在下一轮自行退出。间隔取 30 秒的理由
+/// 与 desktop 侧的 `install_connection_idle_closed_bridge` 相同(面向分钟级空闲,
+/// 未启用阈值的连接会被 core 直接过滤)。
+pub fn start_connection_idle_sweeper(state: &Arc<WebState>) {
+ let state = Arc::downgrade(state);
+ tokio::spawn(async move {
+ loop {
+ let Some(state) = state.upgrade() else { break };
+ state.app.sweep_idle_connections().await;
+ drop(state);
+ tokio::time::sleep(std::time::Duration::from_secs(30)).await;
+ }
+ });
+}
+
pub async fn prewarm_connection(
State(state): State<Arc<WebState>>,
Json(body): Json<PrewarmConnectionRequest>,
@@ -1157,6 +1219,7 @@ mod tests {
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
idle_timeout_secs: dbx_core::models::connection::default_idle_timeout_secs(),
manual_transaction_timeout_secs: dbx_core::models::connection::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: dbx_core::models::connection::default_idle_disconnect_secs(),
keepalive_interval_secs: dbx_core::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-web/src/routes/docs.rs b/crates/dbx-web/src/routes/docs.rs
index 566596c3bf..80b13bede7 100644
--- a/crates/dbx-web/src/routes/docs.rs
+++ b/crates/dbx-web/src/routes/docs.rs
@@ -194,8 +194,9 @@ pub async fn export_html(Json(request): Json<DocsExportRequest>) -> Result<Json<
mod tests {
use super::*;
use dbx_core::models::connection::{
- default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
- default_manual_transaction_timeout_secs, default_query_timeout_secs, DatabaseType,
+ default_connect_timeout_secs, default_idle_disconnect_secs, default_idle_timeout_secs,
+ default_keepalive_interval_secs, default_manual_transaction_timeout_secs, default_query_timeout_secs,
+ DatabaseType,
};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
@@ -234,6 +235,7 @@ mod tests {
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: default_idle_timeout_secs(),
manual_transaction_timeout_secs: default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: default_idle_disconnect_secs(),
keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rs
index 5a1bbd2f59..66ecd89d06 100644
--- a/crates/dbx-web/src/routes/transfer.rs
+++ b/crates/dbx-web/src/routes/transfer.rs
@@ -314,8 +314,9 @@ mod tests {
use axum::response::IntoResponse;
use dbx_core::connection::AppState;
use dbx_core::models::connection::{
- default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
- default_manual_transaction_timeout_secs, default_query_timeout_secs, ConnectionConfig, DatabaseType,
+ default_connect_timeout_secs, default_idle_disconnect_secs, default_idle_timeout_secs,
+ default_keepalive_interval_secs, default_manual_transaction_timeout_secs, default_query_timeout_secs,
+ ConnectionConfig, DatabaseType,
};
use dbx_core::persistence::task_history::{TaskRunItemsQuery, TaskRunStatus, TransferObjectSelectionMode};
use dbx_core::transfer::{
@@ -355,6 +356,7 @@ mod tests {
query_timeout_secs: default_query_timeout_secs(),
idle_timeout_secs: default_idle_timeout_secs(),
manual_transaction_timeout_secs: default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: default_idle_disconnect_secs(),
keepalive_interval_secs: default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 65efbc79c0..b87aba9ebf 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -371,6 +371,7 @@ mod tests {
query_timeout_secs: dbx_core::models::connection::default_query_timeout_secs(),
idle_timeout_secs: dbx_core::models::connection::default_idle_timeout_secs(),
manual_transaction_timeout_secs: dbx_core::models::connection::default_manual_transaction_timeout_secs(),
+ idle_disconnect_secs: dbx_core::models::connection::default_idle_disconnect_secs(),
keepalive_interval_secs: dbx_core::models::connection::default_keepalive_interval_secs(),
ssl: false,
ca_cert_path: String::new(),
@@ -2700,9 +2701,54 @@ pub fn install_connection_liveness_bridge(app: &tauri::AppHandle, state: Arc<App
});
}
+/// 「空闲自动断开」定时清扫与事件转发(issue #12112)。
+///
+/// 分两步,与 `install_connection_liveness_bridge` 同一分工(core 负责发布事件,各 shell
+/// 只负责自己的传输):
+/// 1. 定时任务周期调用 `sweep_idle_connections` 触发清扫;
+/// 2. 订阅转发任务把 core 发布的 `ConnectionIdleClosedEvent` 以 `dbx:connection-idle-closed`
+/// 事件发给前端;前端据此把该连接标记为未连接(保留已打开的查询页签与结果,且不写
+/// 「用户已关闭」标记,便于自动重连)。
+///
+/// 间隔取 30 秒:该功能面向「分钟级」的长时间空闲,这个检测粒度足够;成本也很低——
+/// 未启用 `idle_disconnect_secs` 的连接在 core 的第一步就被过滤掉,不会有额外开销。
+pub fn install_connection_idle_closed_bridge(app: &tauri::AppHandle, state: Arc<AppState>) {
+ const SWEEP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
+ let sweep_state = state.clone();
+ tauri::async_runtime::spawn(async move {
+ let mut ticker = tokio::time::interval(SWEEP_INTERVAL);
+ // 间隔型任务不需要「追赶」错过的 tick:若上一轮因为系统休眠等原因被推迟,
+ // 只需在下一轮正常执行,避免休眠唤醒后连续补跑多次清扫。
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ // 首次 tick 会立即就绪,此时通常还没有任何连接池,属于正常空跑。
+ ticker.tick().await;
+ sweep_state.sweep_idle_connections().await;
+ }
+ });
+
+ let app_handle = app.clone();
+ let mut events = state.subscribe_connection_idle_closed();
+ tauri::async_runtime::spawn(async move {
+ loop {
+ match events.recv().await {
+ Ok(event) => {
+ let _ = app_handle.emit("dbx:connection-idle-closed", event);
+ }
+ // 丢弃事件不影响正确性:前端下次触发查询时会经 `ensureConnected` 自动重连,
+ // 侧边栏状态也会在下一次刷新时对齐,因此这里只记日志、不做补偿。
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
+ log::warn!("Desktop idle-closed bridge skipped {skipped} messages");
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
+ }
+ }
+ });
+}
+
/// Warm the driver and connection pool for a connection a tab is opening, so the
-/// first Run does not pay pool creation, tunnel setup, or external-driver (JDBC
-/// agent) startup while the user waits. Never removes an existing pool.
+/// first Run does not pay pool creation, tunnel setup, or external-driver (JDBC)
+/// agent startup while the user waits. Never removes an existing pool.
#[tauri::command]
pub async fn prewarm_connection(
state: State<'_, Arc<AppState>>,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index ae98ae2d69..67b1b80dd9 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1922,6 +1922,7 @@ pub fn run() {
app.manage(state.clone());
commands::plugins::install_plugin_event_bridge(app.handle(), state.clone());
commands::connection::install_connection_liveness_bridge(app.handle(), state.clone());
+ commands::connection::install_connection_idle_closed_bridge(app.handle(), state.clone());
let app_identifier = app.config().identifier.clone();
let backups = tauri::async_runtime::block_on(async {
background_backup::BackgroundBackup::new(state.clone(), data_dir.clone(), app_identifier)