Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore(sql-editor): WebSocket auto reconnect and error notification (#12768)

Liu Ji2c67ecedbbbf
diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
index 840e4ea60f..c1aa45f161 100644
--- a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
@@ -18,10 +18,30 @@
>
{{ placeholder }}
</div>
+
+ <NPopover v-if="ready" placement="left">
+ <template #trigger>
+ <div
+ class="absolute top-[3px] right-[18px] w-4 h-4 flex items-center justify-center cursor-pointer z-50 opacity-50 hover:opacity-100 transition-all"
+ >
+ <div
+ class="w-3 h-3 rounded-full"
+ :class="connectionStateIndicatorClass"
+ />
+ </div>
+ </template>
+ <template #default>
+ <div class="inline-flex gap-1">
+ <span>Language server</span>
+ <span>{{ connectionStateText }}</span>
+ </div>
+ </template>
+ </NPopover>
</div>
</template>
<script lang="ts" setup>
+import { NPopover } from "naive-ui";
import {
onMounted,
ref,
@@ -31,8 +51,8 @@ import {
onBeforeUnmount,
watch,
watchEffect,
+ computed,
} from "vue";
-import { useLegacyAutoComplete } from "@/plugins/sql-lsp/client";
import type { SQLDialect } from "@/types";
import {
type AutoCompleteContext,
@@ -48,8 +68,8 @@ import {
useSelectedContent,
useSuggestOptionByLanguage,
useLineHighlights,
+ useLSPConnectionState,
} from "./composables";
-import { shouldUseNewLSP } from "./dev";
import monaco, { createMonacoEditor } from "./editor";
import type {
AdviceOption,
@@ -98,6 +118,27 @@ const containerRef = ref<HTMLDivElement>();
const editorRef = shallowRef<IStandaloneCodeEditor>();
const ready = ref(false);
const contentRef = ref("");
+const { connectionState } = useLSPConnectionState();
+const connectionStateIndicatorClass = computed(() => {
+ const state = connectionState.value;
+ if (state === "ready") {
+ return "bg-green-500";
+ }
+ if (state === "initial" || state === "reconnecting") {
+ return "bg-yellow-500";
+ }
+ return "bg-gray-500";
+});
+const connectionStateText = computed(() => {
+ const state = connectionState.value;
+ if (state === "ready") {
+ return "connected";
+ }
+ if (state === "initial" || state === "reconnecting") {
+ return "connecting";
+ }
+ return "disconnected";
+});
onMounted(async () => {
const container = containerRef.value;
@@ -131,15 +172,7 @@ onMounted(async () => {
useAdvices(monaco, editor, toRef(props, "advices"));
useLineHighlights(monaco, editor, toRef(props, "lineHighlights"));
useAutoHeight(monaco, editor, containerRef, toRef(props, "autoHeight"));
- if (shouldUseNewLSP()) {
- useAutoComplete(monaco, editor, toRef(props, "autoCompleteContext"));
- } else {
- useLegacyAutoComplete(
- monaco,
- editor,
- toRef(props, "autoCompleteContext")
- );
- }
+ useAutoComplete(monaco, editor, toRef(props, "autoCompleteContext"));
ready.value = true;
diff --git a/frontend/src/components/MonacoEditor/composables/index.ts b/frontend/src/components/MonacoEditor/composables/index.ts
index f8df53d64b..7f9ccf11dd 100644
--- a/frontend/src/components/MonacoEditor/composables/index.ts
+++ b/frontend/src/components/MonacoEditor/composables/index.ts
@@ -8,3 +8,4 @@ export * from "./useAdvices";
export * from "./useLineHighlights";
export * from "./useAutoHeight";
export * from "./useAutoComplete";
+export * from "./useLSPConnectionState";
diff --git a/frontend/src/components/MonacoEditor/composables/useLSPConnectionState.ts b/frontend/src/components/MonacoEditor/composables/useLSPConnectionState.ts
new file mode 100644
index 0000000000..cff51ca47c
--- /dev/null
+++ b/frontend/src/components/MonacoEditor/composables/useLSPConnectionState.ts
@@ -0,0 +1,14 @@
+import { ref, watchEffect } from "vue";
+import type { ConnectionState } from "../lsp-client";
+
+export const useLSPConnectionState = () => {
+ const connectionState = ref<ConnectionState["state"]>();
+
+ import("../lsp-client").then(({ connectionState: state }) => {
+ watchEffect(() => {
+ connectionState.value = state.value;
+ });
+ });
+
+ return { connectionState };
+};
diff --git a/frontend/src/components/MonacoEditor/dev.ts b/frontend/src/components/MonacoEditor/dev.ts
deleted file mode 100644
index e52234d30b..0000000000
--- a/frontend/src/components/MonacoEditor/dev.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { useActuatorV1Store } from "@/store";
-
-export const shouldUseNewLSP = () => {
- return useActuatorV1Store().serverInfo?.lsp;
-};
diff --git a/frontend/src/components/MonacoEditor/editor.ts b/frontend/src/components/MonacoEditor/editor.ts
index a3d4b1bd45..72eedb4d4a 100644
--- a/frontend/src/components/MonacoEditor/editor.ts
+++ b/frontend/src/components/MonacoEditor/editor.ts
@@ -8,7 +8,6 @@ import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
import "monaco-editor/esm/vs/editor/standalone/browser/standaloneCodeEditorService";
import "monaco-editor/esm/vs/language/typescript/monaco.contribution.js";
import { defer } from "@/utils";
-import { shouldUseNewLSP } from "./dev";
import { initializeMonacoServices } from "./services";
import { getBBTheme } from "./themes/bb";
import { getBBDarkTheme } from "./themes/bb-dark";
@@ -39,32 +38,15 @@ const initializeTheme = () => {
state.themeInitialized = true;
};
-const initializeNewLSP = async () => {
- const { initializeLSPClient } = await import("./lsp-client");
- await initializeLSPClient();
-};
-
-const initializeLegacyLSP = async () => {
- const { useLanguageClient } = await import("@/plugins/sql-lsp/client");
- const { start } = useLanguageClient();
- start();
-};
-
const initialize = async () => {
await initializeMonacoServices();
- if (shouldUseNewLSP()) {
- try {
- await initializeNewLSP();
- } catch (err) {
- console.error("[MonacoEditor] initialize", err);
-
- await initializeLegacyLSP();
- }
- } else {
- await initializeLegacyLSP();
+ try {
+ const { initializeLSPClient } = await import("./lsp-client");
+ await initializeLSPClient();
+ } catch (err) {
+ console.error("[MonacoEditor] initialize", err);
}
-
initializeTheme();
};
diff --git a/frontend/src/components/MonacoEditor/lsp-client.ts b/frontend/src/components/MonacoEditor/lsp-client.ts
index cb70485fa9..9ab6ccb482 100644
--- a/frontend/src/components/MonacoEditor/lsp-client.ts
+++ b/frontend/src/components/MonacoEditor/lsp-client.ts
@@ -1,20 +1,120 @@
-import { MonacoLanguageClient } from "monaco-languageclient";
-import type {
- ExecuteCommandParams,
- MessageTransports,
-} from "vscode-languageclient";
-import { CloseAction, ErrorAction } from "vscode-languageclient";
import {
+ MonacoLanguageClient,
+ type IConnectionProvider,
+} from "monaco-languageclient";
+import type { ExecuteCommandParams } from "vscode-languageclient";
+import { CloseAction, ErrorAction, State } from "vscode-languageclient";
+import {
+ toSocket,
WebSocketMessageReader,
WebSocketMessageWriter,
- toSocket,
} from "vscode-ws-jsonrpc";
-import { h } from "vue";
-import { pushNotification } from "@/store";
-import LearnMoreLink from "../LearnMoreLink.vue";
+import { shallowReactive, toRef } from "vue";
+import { sleep } from "@/utils";
+import {
+ createUrl,
+ errorNotification,
+ MAX_RETRIES,
+ messages,
+ progressiveDelay,
+ WEBSOCKET_TIMEOUT,
+} from "./utils";
+
+export type ConnectionState = {
+ url: string;
+ state: "initial" | "ready" | "closed" | "reconnecting";
+ ws: Promise<WebSocket> | undefined;
+ lastCommand: ExecuteCommandParams | undefined;
+ retries: number;
+};
+
+const conn = shallowReactive<ConnectionState>({
+ url: createUrl(location.host, "/lsp").toString(),
+ state: "initial",
+ ws: undefined,
+ lastCommand: undefined,
+ retries: 0,
+});
+
+const connectWebSocket = () => {
+ if (conn.ws) {
+ return conn.ws;
+ }
+
+ const connect = (
+ resolve: (value: WebSocket | PromiseLike<WebSocket>) => void,
+ reject: (reason?: any) => void
+ ) => {
+ const ws = new WebSocket(conn.url);
+ const retries = conn.retries++;
+
+ switch (conn.state) {
+ case "closed":
+ return reject(`Connection is closed`);
+ case "initial":
+ break;
+ case "ready":
+ case "reconnecting":
+ conn.state = "reconnecting";
+ break;
+ }
+
+ const delay = progressiveDelay(retries);
+ console.debug(
+ `[LSP-Client] try connecting: state=${conn.state} retries=${retries} delay=${delay}`
+ );
+
+ sleep(delay).then(() => {
+ const handleError = (code: number, reason: string) => {
+ if (conn.state === "closed" || conn.state === "ready") {
+ return;
+ }
+
+ if (conn.retries >= MAX_RETRIES) {
+ conn.state = "closed";
+ return reject(
+ `${messages.disconnected()}: maxRetires exceeded (${MAX_RETRIES}). code=${code} reason="${reason}"`
+ );
+ }
+ return connect(resolve, reject);
+ };
+
+ const timer = setTimeout(() => {
+ handleError(-1, "timeout");
+ }, WEBSOCKET_TIMEOUT);
+
+ ws.addEventListener("open", () => {
+ clearTimeout(timer);
+ console.debug(`[LSP-Client] WebSocket open`);
+ if (conn.state === "ready" || conn.state === "closed") {
+ return;
+ }
+ conn.state = "ready";
+ conn.retries = 0; // reset retry counter
+ resolve(ws);
+ });
+ ws.addEventListener("close", (e) => {
+ clearTimeout(timer);
+ console.debug(
+ `[LSP-Client] WebSocket close state=${conn.state} code=${e.code} reason=${e.reason}`
+ );
+ handleError(e.code, e.reason);
+ });
+ });
+ };
+
+ const promise = new Promise<WebSocket>(connect);
+ conn.ws = promise;
+ return promise;
+};
+
+const state = {
+ client: undefined as MonacoLanguageClient | undefined,
+ clientInitialized: undefined as Promise<MonacoLanguageClient> | undefined,
+};
export const createLanguageClient = (
- transports: MessageTransports
+ connectionProvider: IConnectionProvider
): MonacoLanguageClient => {
return new MonacoLanguageClient({
name: "Bytebase Language Client",
@@ -23,95 +123,81 @@ export const createLanguageClient = (
documentSelector: ["sql"],
// disable the default error handler
errorHandler: {
- error: () => ({ action: ErrorAction.Continue }),
- closed: () => ({ action: CloseAction.Restart }),
+ error: (error, message, count) => {
+ console.debug("[MonacoLanguageClient] error", error, message, count);
+ return {
+ action: ErrorAction.Continue,
+ };
+ },
+ closed: async () => {
+ console.debug("[MonacoLanguageClient] closed");
+ conn.ws = undefined;
+ try {
+ await connectWebSocket();
+ return {
+ action: CloseAction.Restart,
+ };
+ } catch (err) {
+ errorNotification(err);
+ return {
+ action: CloseAction.DoNotRestart,
+ };
+ }
+ },
},
},
// create a language client connection from the JSON RPC connection on demand
- connectionProvider: {
- get: () => {
- return Promise.resolve(transports);
- },
- },
+ connectionProvider,
});
};
-export const createUrl = (
- host: string,
- path: string,
- searchParams: Record<string, any> = {},
- secure: boolean = location.protocol === "https:"
-): string => {
- const protocol = secure ? "wss" : "ws";
- const url = new URL(`${protocol}://${host}${path}`);
-
- for (const [key, value] of Object.entries(searchParams)) {
- const v = value instanceof Array ? value.join(",") : value;
- if (v) {
- url.searchParams.set(key, v);
- }
- }
-
- return url.toString();
-};
-
-export const createWebSocketAndStartClient = (
- url: string
-): {
- webSocket: WebSocket;
+export const createWebSocketAndStartClient = (): {
languageClient: Promise<MonacoLanguageClient>;
} => {
- const webSocket = new WebSocket(url);
const languageClient = new Promise<MonacoLanguageClient>(
(resolve, reject) => {
- webSocket.onopen = () => {
- const socket = toSocket(webSocket);
- const reader = new WebSocketMessageReader(socket);
- const writer = new WebSocketMessageWriter(socket);
- const languageClient = createLanguageClient({
- reader,
- writer,
- });
- languageClient.start();
- reader.onClose(() => languageClient.stop());
- resolve(languageClient);
- };
- webSocket.onerror = (e: any) => {
- console.error("[MonacoLanguageClient] WebSocket error", e);
- const message = typeof e.message === "string" ? e.message : "";
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Error",
- description: () => {
- return [
- h("p", {}, `Error occurred when initializing WebSocket`),
- message ? h("p", {}, message) : null,
- h(LearnMoreLink, {
- url: "https://www.bytebase.com/docs/administration/production-setup/#enable-https-and-websocket",
- }),
- ];
- },
- });
- reject(e);
- };
+ const languageClient = createLanguageClient({
+ async get() {
+ const ws = await connectWebSocket();
+ const socket = toSocket(ws);
+ const reader = new WebSocketMessageReader(socket);
+ const writer = new WebSocketMessageWriter(socket);
+ return { reader, writer };
+ },
+ });
+ languageClient.onDidChangeState((e) => {
+ if (e.newState === State.Running) {
+ const { lastCommand } = conn;
+ if (lastCommand) {
+ // When LSP Client is reconnected, the LSP context (e.g. setMetadata)
+ // will be cleared.
+ // So we need to catch the last command, and re-send it to recover
+ // the context
+ executeCommand(
+ languageClient,
+ lastCommand.command,
+ lastCommand.arguments
+ );
+ }
+ }
+ });
+
+ languageClient.start().catch((err) => {
+ // LSP Client startup failed.
+ errorNotification(err);
+ });
+
+ resolve(languageClient);
}
);
return {
- webSocket,
languageClient,
};
};
-const state = {
- client: undefined as MonacoLanguageClient | undefined,
- clientInitialized: undefined as Promise<MonacoLanguageClient> | undefined,
-};
-
const initializeRunner = async () => {
- const url = createUrl(location.host, "/lsp");
- const client = await createWebSocketAndStartClient(url).languageClient;
+ const client = await createWebSocketAndStartClient().languageClient;
state.client = client;
return client;
};
@@ -145,9 +231,12 @@ export const executeCommand = async (
command,
arguments: args,
};
+ conn.lastCommand = executeCommandParams;
const result = await client.sendRequest(
"workspace/executeCommand",
executeCommandParams
);
return result;
};
+
+export const connectionState = toRef(conn, "state");
diff --git a/frontend/src/components/MonacoEditor/utils.ts b/frontend/src/components/MonacoEditor/utils.ts
index f0b3377df7..06bb656219 100644
--- a/frontend/src/components/MonacoEditor/utils.ts
+++ b/frontend/src/components/MonacoEditor/utils.ts
@@ -1,9 +1,31 @@
import { Range } from "monaco-editor";
import { isRef, unref, watch } from "vue";
+import { h } from "vue";
+import { t } from "@/plugins/i18n";
+import { pushNotification } from "@/store";
import type { Language, MaybeRef, SQLDialect } from "@/types";
+import { minmax } from "@/utils";
+import LearnMoreLink from "../LearnMoreLink.vue";
import sqlFormatter from "./sqlFormatter";
import type { IStandaloneCodeEditor } from "./types";
+// Max retires in a retry serial. Will be reset after a success connection
+export const MAX_RETRIES = 5;
+// Progressive delay in a retry serial. Avoiding to flood the server.
+export const RECONNECTION_DELAY = {
+ max: 1000,
+ min: 100,
+ growth: 1.5,
+};
+// Timeout to setup connection in EACH attempt
+export const WEBSOCKET_TIMEOUT = 5000;
+
+export const messages = {
+ title: () => t("sql-editor.web-socket.errors.title"),
+ description: () => t("sql-editor.web-socket.errors.description"),
+ disconnected: () => t("sql-editor.web-socket.errors.disconnected"),
+};
+
export const extensionNameOfLanguage = (lang: Language) => {
switch (lang) {
case "sql":
@@ -71,3 +93,60 @@ export const formatEditorContent = async (
editor.setPosition(pos);
}
};
+
+export const createUrl = (
+ host: string,
+ path: string,
+ searchParams: Record<string, any> = {},
+ secure: boolean = location.protocol === "https:"
+) => {
+ const protocol = secure ? "wss" : "ws";
+ const url = new URL(`${protocol}://${host}${path}`);
+
+ for (const [key, value] of Object.entries(searchParams)) {
+ const v = value instanceof Array ? value.join(",") : value;
+ if (v) {
+ url.searchParams.set(key, v);
+ }
+ }
+ return url;
+};
+
+const extractErrorMessage = (err: any) => {
+ if (typeof err === "string") {
+ return err;
+ }
+ if (typeof err.message === "string") {
+ return err.message;
+ }
+ return String(err);
+};
+
+export const errorNotification = (err: unknown) => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: messages.title(),
+ description: () => {
+ const message = extractErrorMessage(err);
+ return [
+ h("p", {}, messages.description()),
+ message ? h("p", {}, message) : null,
+ h(LearnMoreLink, {
+ url: "https://www.bytebase.com/docs/administration/production-setup/#enable-https-and-websocket",
+ }),
+ ];
+ },
+ });
+};
+
+export const progressiveDelay = (serial: number) => {
+ if (serial === 0) {
+ return 0;
+ }
+ return minmax(
+ RECONNECTION_DELAY.min * Math.pow(RECONNECTION_DELAY.growth, serial - 1),
+ RECONNECTION_DELAY.min,
+ RECONNECTION_DELAY.max
+ );
+};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index d475b8224f..90afcaa219 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2391,7 +2391,14 @@
"self": "Standard mode"
},
"to-enable-standard-mode": "to enable the standard mode",
- "add-a-new-instance": "Add a new instance"
+ "add-a-new-instance": "Add a new instance",
+ "web-socket": {
+ "errors": {
+ "title": "WebSocket connection failed",
+ "description": "Auto Completion might be limited or disabled.",
+ "disconnected": "WebSocket disconnected"
+ }
+ }
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index cdb28277bb..8b43f5ff0c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2391,7 +2391,14 @@
"self": "Modo estandar"
},
"to-enable-standard-mode": "para habilitar el modo estándar",
- "add-a-new-instance": "Agregar una nueva instancia"
+ "add-a-new-instance": "Agregar una nueva instancia",
+ "web-socket": {
+ "errors": {
+ "title": "La conexión WebSocket falló",
+ "description": "La finalización automática puede estar limitada o deshabilitada.",
+ "disconnected": "WebSocket desconectado"
+ }
+ }
},
"schema-editor": {
"self": "Editor de esquema",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 6b6efd7cfd..2c0350170c 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2391,7 +2391,14 @@
"self": "標準モード"
},
"to-enable-standard-mode": "標準モードを有効にするには",
- "add-a-new-instance": "新しいインスタンスを追加する"
+ "add-a-new-instance": "新しいインスタンスを追加する",
+ "web-socket": {
+ "errors": {
+ "title": "WebSocket接続に失敗しました",
+ "description": "オートコンプリートが制限されているか、無効になっている可能性があります。",
+ "disconnected": "WebSocketが切断されました"
+ }
+ }
},
"schema-editor": {
"self": "スキーマエディタ",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index c45d72c36c..de246c8c9d 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2391,7 +2391,14 @@
"self": "标准模式"
},
"to-enable-standard-mode": "来开启标准模式",
- "add-a-new-instance": "添加实例"
+ "add-a-new-instance": "添加实例",
+ "web-socket": {
+ "errors": {
+ "title": "WebSocket 连接失败",
+ "description": "自动补全功能可能会受到限制或无效。",
+ "disconnected": "WebSocket 已断开连接"
+ }
+ }
},
"schema-editor": {
"self": "Schema 编辑器",
@@ -3620,4 +3627,4 @@
"self": "最后更新"
}
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index e401424a7d..cfb2f2a661 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -217,6 +217,10 @@ export function defer<T = any>() {
return d;
}
+export const sleep = (ms: number) => {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+};
+
/**
* Wrap a Ref as a Promise, will be resolved when the Ref turns to expectedValue
* first time