Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: local storage key namespace by user uid (#12348)
Liu Ji259237654437
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex 35a5d39727..e6c47e1ca4 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -1,5 +1,5 @@import type { MaybeRef } from "@vueuse/core";-import { useLocalStorage, watchThrottled } from "@vueuse/core";+import { watchThrottled } from "@vueuse/core";import { head, pick, uniqBy } from "lodash-es";import { defineStore, storeToRefs } from "pinia";import { computed, reactive, unref } from "vue";@@ -14,19 +14,17 @@ import {WebStorageHelper,defaultSQLEditorTab,emptySQLEditorConnection,+ extractUserUID,isDisconnectedSQLEditorTab,isSimilarSQLEditorTab,+ useDynamicLocalStorage,} from "@/utils";+import { useCurrentUserV1 } from "../auth";import { useDatabaseV1Store, useInstanceV1Store } from "../v1";import { useSQLEditorStore } from "./editor";import { useWebTerminalStore } from "./webTerminal";const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";-const KEYS = {- tabIdList: "tab-id-list",- currentTabId: "current-tab-id",- tab: (id: string) => `tab.${id}`,-};// Only store the core fields of a tab.// Don't store anything which might be too large.@@ -50,11 +48,21 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {const { project } = storeToRefs(useSQLEditorStore());// states- const storage = new WebStorageHelper(LOCAL_STORAGE_KEY_PREFIX);+ const me = useCurrentUserV1();+ const userUID = computed(() => extractUserUID(me.value.name));+ const keyNamespace = computed(+ () => `${LOCAL_STORAGE_KEY_PREFIX}.${userUID.value}`+ );+ const getStorage = () => {+ return new WebStorageHelper(keyNamespace.value);+ };+ const keyForTab = (id: string) => {+ return `tab.${id}`;+ };const loadStoredTab = (id: string) => {- const stored = storage.load<PersistentTab | undefined>(- KEYS.tab(id),+ const stored = getStorage().load<PersistentTab | undefined>(+ keyForTab(id),undefined);if (!stored) {@@ -70,13 +78,16 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {return tab;};- const tabIdListMapByProject = useLocalStorage<Record<string, string[]>>(- `${LOCAL_STORAGE_KEY_PREFIX}.${KEYS.tabIdList}`,- {}- );- const currentTabIdMapByProject = useLocalStorage<+ const tabIdListKey = computed(() => `${keyNamespace.value}.tab-id-list`);+ const tabIdListMapByProject = useDynamicLocalStorage<+ Record<string, string[]>+ >(tabIdListKey, {});++ const currentTabIdKey = computed(() => `${keyNamespace.value}.current-tab-id`);+ const currentTabIdMapByProject = useDynamicLocalStorage<Record<string, string | undefined>- >(`${LOCAL_STORAGE_KEY_PREFIX}.${KEYS.currentTabId}`, {});+ >(currentTabIdKey, {});+const initializedProjects = new Set<string>();const maybeInitProject = (project: string) => {if (initializedProjects.has(project)) {@@ -178,7 +189,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {if (position < 0) return;tabIdList.value.splice(position, 1);tabsById.delete(id);- storage.remove(KEYS.tab(id));+ getStorage().remove(keyForTab(id));if (tab.mode === "ADMIN") {useWebTerminalStore().clearQueryStateByTab(id);@@ -235,7 +246,9 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {// clean persistent tabs that are not in the `tabIdList` anymoreconst _cleanup = () => {const prefix = `${LOCAL_STORAGE_KEY_PREFIX}.tab.`;- const keys = storage.keys().filter((key) => key.startsWith(prefix));+ const keys = getStorage()+ .keys()+ .filter((key) => key.startsWith(prefix));const flattenTabIdSet = new Set(Object.keys(tabIdListMapByProject.value).flatMap((project) => tabIdListMapByProject.value[project]@@ -244,7 +257,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {keys.forEach((key) => {const id = key.substring(prefix.length);if (!flattenTabIdSet.has(id)) {- storage.remove(KEYS.tab(id));+ getStorage().remove(keyForTab(id));}});};@@ -255,7 +268,10 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {watchThrottled(() => pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab,(persistentTab) => {- storage.save<PersistentTab>(KEYS.tab(persistentTab.id), persistentTab);+ getStorage().save<PersistentTab>(+ keyForTab(persistentTab.id),+ persistentTab+ );},{ deep: true, immediate, throttle: 100, trailing: true });@@ -276,7 +292,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {initAll();const reset = () => {- storage.clear();tabIdListMapByProject.value = {};currentTabIdMapByProject.value = {};initAll();diff --git a/frontend/src/utils/web-storage.ts b/frontend/src/utils/web-storage.tsindex b79d823190..4e43f54358 100644--- a/frontend/src/utils/web-storage.ts+++ b/frontend/src/utils/web-storage.ts@@ -1,3 +1,20 @@+import {+ StorageSerializers,+ customStorageEventName,+ defaultWindow,+ getSSRHandler,+ pausableWatch,+ toValue,+ tryOnMounted,+ useEventListener,+ type MaybeRefOrGetter,+ type RemovableRef,+ type StorageEventLike,+ type StorageLike,+ type UseStorageOptions,+} from "@vueuse/core";+import { nextTick, ref, shallowRef, watch, type Ref } from "vue";+export class WebStorageHelper {storage: Storage;keyPrefix: string;@@ -55,3 +72,183 @@ export class WebStorageHelper {});}}++/**+ * see: https://github.com/vueuse/vueuse/blob/main/packages/core/useStorage/index.ts+ */+export const useDynamicLocalStorage = <+ T extends string | number | boolean | object | null,+>(+ key: Ref<string>,+ defaults: MaybeRefOrGetter<T>,+ storage: StorageLike | undefined = window.localStorage,+ options: UseStorageOptions<T> = {}+) => {+ const {+ flush = "pre",+ deep = true,+ listenToStorageChanges = true,+ writeDefaults = true,+ mergeDefaults = false,+ shallow,+ window = defaultWindow,+ eventFilter,+ onError = (e) => {+ console.error(e);+ },+ initOnMounted,+ } = options;++ const data = (shallow ? shallowRef : ref)(+ typeof defaults === "function" ? defaults() : defaults+ ) as RemovableRef<T>;++ if (!storage) {+ try {+ storage = getSSRHandler(+ "getDefaultStorage",+ () => defaultWindow?.localStorage+ )();+ } catch (e) {+ onError(e);+ }+ }++ if (!storage) return data;++ const rawInit: T = toValue(defaults);+ const type = guessSerializerType<T>(rawInit);+ const serializer = options.serializer ?? StorageSerializers[type];++ const { pause: pauseWatch, resume: resumeWatch } = pausableWatch(+ data,+ () => write(data.value),+ { flush, deep, eventFilter }+ );++ if (window && listenToStorageChanges) {+ tryOnMounted(() => {+ // this should be fine since we are in a mounted hook+ useEventListener(window, "storage", update);+ useEventListener(window, customStorageEventName, updateFromCustomEvent);+ if (initOnMounted) update();+ });+ }++ // avoid reading immediately to avoid hydration mismatch when doing SSR+ if (!initOnMounted) update();++ function dispatchWriteEvent(+ oldValue: string | null,+ newValue: string | null+ ) {+ // send custom event to communicate within same page+ // importantly this should _not_ be a StorageEvent since those cannot+ // be constructed with a non-built-in storage area+ if (window) {+ window.dispatchEvent(+ new CustomEvent<StorageEventLike>(customStorageEventName, {+ detail: {+ key: key.value,+ oldValue,+ newValue,+ storageArea: storage!,+ },+ })+ );+ }+ }++ function write(v: unknown) {+ try {+ const oldValue = storage!.getItem(key.value);++ if (v == null) {+ dispatchWriteEvent(oldValue, null);+ storage!.removeItem(key.value);+ } else {+ const serialized = serializer.write(v as any);+ if (oldValue !== serialized) {+ storage!.setItem(key.value, serialized);+ dispatchWriteEvent(oldValue, serialized);+ }+ }+ } catch (e) {+ onError(e);+ }+ }++ function read(event?: StorageEventLike) {+ const rawValue = event ? event.newValue : storage!.getItem(key.value);++ if (rawValue == null) {+ if (writeDefaults && rawInit != null)+ storage!.setItem(key.value, serializer.write(rawInit));+ return rawInit;+ } else if (!event && mergeDefaults) {+ const value = serializer.read(rawValue);+ if (typeof mergeDefaults === "function")+ return mergeDefaults(value, rawInit);+ else if (type === "object" && !Array.isArray(value))+ return { ...(rawInit as any), ...value };+ return value;+ } else if (typeof rawValue !== "string") {+ return rawValue;+ } else {+ return serializer.read(rawValue);+ }+ }++ function update(event?: StorageEventLike) {+ if (event && event.storageArea !== storage) return;++ if (event && event.key == null) {+ data.value = rawInit;+ return;+ }++ if (event && event.key !== key.value) return;++ pauseWatch();+ try {+ if (event?.newValue !== serializer.write(data.value))+ data.value = read(event);+ } catch (e) {+ onError(e);+ } finally {+ // use nextTick to avoid infinite loop+ if (event) nextTick(resumeWatch);+ else resumeWatch();+ }+ }++ function updateFromCustomEvent(event: CustomEvent<StorageEventLike>) {+ update(event.detail);+ }++ watch(key, () => update());++ return data;+};++export function guessSerializerType<+ T extends string | number | boolean | object | null,+>(rawInit: T) {+ return rawInit == null+ ? "any"+ : rawInit instanceof Set+ ? "set"+ : rawInit instanceof Map+ ? "map"+ : rawInit instanceof Date+ ? "date"+ : typeof rawInit === "boolean"+ ? "boolean"+ : typeof rawInit === "string"+ ? "string"+ : typeof rawInit === "object"+ ? "object"+ : !Number.isNaN(rawInit)+ ? "number"+ : "any";+}