Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Revert ensu chat storage migration

Prateek Sunal1345e21f75b0
diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.ts
index c8865aea2d..490020373b 100644
--- a/web/apps/ensu/src/services/chat/store.ts
+++ b/web/apps/ensu/src/services/chat/store.ts
@@ -1,5 +1,5 @@
import log from "ente-base/log";
-import { openDB, type DBSchema, type IDBPDatabase } from "idb";
+import { base64ToBytes, bytesToBase64 } from "services/base64";
import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";
import { cachedLocalChatKey } from "./chatKey";
import {
@@ -9,8 +9,7 @@ import {
encryptChatPayload,
} from "./crypto";
-const DB_NAME = "ensu.chat.db";
-const DB_VERSION = 3;
+const STORAGE_KEY = "ensu.chat.store.v1";
export type AttachmentKind = "image" | "document";
@@ -62,10 +61,53 @@ interface StoredAttachmentBytes {
data: Uint8Array;
}
-interface ChatDbSchema extends DBSchema {
- sessions: { key: string; value: StoredSession };
- messages: { key: string; value: StoredMessage };
- attachmentBytes: { key: string; value: StoredAttachmentBytes };
+interface ChatDbSchema {
+ sessions: StoredSession;
+ messages: StoredMessage;
+ attachmentBytes: StoredAttachmentBytes;
+}
+
+type ChatStoreName = keyof ChatDbSchema;
+
+type PersistedAttachmentBytes = {
+ id: string;
+ data: string;
+};
+
+type PersistedChatStore = {
+ sessions: StoredSession[];
+ messages: StoredMessage[];
+ attachmentBytes: PersistedAttachmentBytes[];
+};
+
+type ChatStoreState = {
+ sessions: StoredSession[];
+ messages: StoredMessage[];
+ attachmentBytes: StoredAttachmentBytes[];
+};
+
+interface ChatObjectStore<K extends ChatStoreName> {
+ get: (key: string) => Promise<ChatDbSchema[K] | undefined>;
+ getAll: () => Promise<ChatDbSchema[K][]>;
+ put: (value: ChatDbSchema[K]) => Promise<void>;
+ delete: (key: string) => Promise<void>;
+}
+
+interface ChatTransaction {
+ objectStore: <K extends ChatStoreName>(name: K) => ChatObjectStore<K>;
+ done: Promise<void>;
+}
+
+interface ChatDbLike {
+ get: <K extends ChatStoreName>(
+ name: K,
+ key: string,
+ ) => Promise<ChatDbSchema[K] | undefined>;
+ getAll: <K extends ChatStoreName>(name: K) => Promise<ChatDbSchema[K][]>;
+ put: <K extends ChatStoreName>(name: K, value: ChatDbSchema[K]) => Promise<void>;
+ delete: <K extends ChatStoreName>(name: K, key: string) => Promise<void>;
+ transaction: (names: ChatStoreName[], mode: "readwrite") => ChatTransaction;
+ close: () => void;
}
export interface ChatSession {
@@ -235,76 +277,187 @@ const withNativeDbRecovery = async <T>(
}
};
-let _chatDb: Promise<IDBPDatabase<ChatDbSchema>> | undefined;
+const cloneStoreState = (state: ChatStoreState): ChatStoreState => ({
+ sessions: state.sessions.map((session) => ({ ...session })),
+ messages: state.messages.map((message) => ({
+ ...message,
+ attachments: message.attachments?.map((attachment) => ({
+ ...attachment,
+ })),
+ })),
+ attachmentBytes: state.attachmentBytes.map((attachment) => ({
+ id: attachment.id,
+ data: new Uint8Array(attachment.data),
+ })),
+});
+
+const loadChatStoreState = (): ChatStoreState => {
+ if (typeof localStorage === "undefined") {
+ return { sessions: [], messages: [], attachmentBytes: [] };
+ }
-const openChatDb = async () => {
- const db = await openDB<ChatDbSchema>(DB_NAME, DB_VERSION, {
- upgrade: async (db, oldVersion, _newVersion, transaction) => {
- if (!db.objectStoreNames.contains("sessions")) {
- db.createObjectStore("sessions", { keyPath: "sessionUuid" });
- }
- if (!db.objectStoreNames.contains("messages")) {
- db.createObjectStore("messages", { keyPath: "messageUuid" });
- }
- if (!db.objectStoreNames.contains("attachmentBytes")) {
- db.createObjectStore("attachmentBytes", { keyPath: "id" });
- }
+ const json = localStorage.getItem(STORAGE_KEY);
+ if (!json) {
+ return { sessions: [], messages: [], attachmentBytes: [] };
+ }
- if (oldVersion < 2 && transaction) {
- const now = Date.now() * 1000;
- const sessionStore = transaction.objectStore("sessions");
- const sessions = await sessionStore.getAll();
- for (const session of sessions) {
- session.needsSync = session.needsSync ?? true;
- session.remoteId = session.remoteId ?? session.sessionUuid;
- session.deletedAt =
- session.deletedAt ?? (session.isDeleted ? now : null);
- await sessionStore.put(session);
- }
+ try {
+ const parsed = JSON.parse(json) as Partial<PersistedChatStore>;
+ return {
+ sessions: (parsed.sessions ?? []).map((session) => ({
+ ...session,
+ remoteId: session.remoteId ?? null,
+ needsSync: session.needsSync ?? true,
+ deletedAt:
+ session.deletedAt ??
+ (session.isDeleted ? session.updatedAt : null),
+ })),
+ messages: (parsed.messages ?? []).map((message) => ({
+ ...message,
+ attachments: message.attachments ?? [],
+ remoteId: message.remoteId ?? null,
+ deletedAt:
+ message.deletedAt ??
+ (message.isDeleted ? message.createdAt : null),
+ })),
+ attachmentBytes: (parsed.attachmentBytes ?? []).map((attachment) => ({
+ id: attachment.id,
+ data: base64ToBytes(attachment.data),
+ })),
+ };
+ } catch (error) {
+ log.error("Failed to parse chat store", error);
+ return { sessions: [], messages: [], attachmentBytes: [] };
+ }
+};
- const messageStore = transaction.objectStore("messages");
- const messages = await messageStore.getAll();
- for (const message of messages) {
- message.attachments = message.attachments ?? [];
- message.deletedAt =
- message.deletedAt ?? (message.isDeleted ? now : null);
- await messageStore.put(message);
- }
- }
+const saveChatStoreState = (state: ChatStoreState) => {
+ if (typeof localStorage === "undefined") return;
- if (oldVersion < 3 && transaction) {
- const sessionStore = transaction.objectStore("sessions");
- const sessions = await sessionStore.getAll();
- for (const session of sessions) {
- session.remoteId = session.remoteId ?? session.sessionUuid;
- await sessionStore.put(session);
- }
+ const persisted: PersistedChatStore = {
+ sessions: state.sessions,
+ messages: state.messages,
+ attachmentBytes: state.attachmentBytes.map((attachment) => ({
+ id: attachment.id,
+ data: bytesToBase64(attachment.data),
+ })),
+ };
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(persisted));
+};
- const messageStore = transaction.objectStore("messages");
- const messages = await messageStore.getAll();
- for (const message of messages) {
- message.remoteId = message.remoteId ?? message.messageUuid;
- await messageStore.put(message);
- }
- }
- },
- blocking() {
- log.info("Another client is trying to open a newer chat DB schema");
- db.close();
- _chatDb = undefined;
- },
- blocked() {
- log.warn("Waiting for an existing client to release the chat DB");
- },
- terminated() {
- log.warn("Chat DB connection was terminated");
- _chatDb = undefined;
- },
- });
+const getStoreKey = (name: ChatStoreName, value: ChatDbSchema[ChatStoreName]) => {
+ if (name === "sessions") {
+ return (value as StoredSession).sessionUuid;
+ }
+ if (name === "messages") {
+ return (value as StoredMessage).messageUuid;
+ }
+ return (value as StoredAttachmentBytes).id;
+};
- return db;
+const getStoreCollection = <K extends ChatStoreName>(
+ state: ChatStoreState,
+ name: K,
+): ChatDbSchema[K][] => state[name] as ChatDbSchema[K][];
+
+const cloneStoreEntry = <K extends ChatStoreName>(
+ name: K,
+ value: ChatDbSchema[K],
+): ChatDbSchema[K] => {
+ if (name === "attachmentBytes") {
+ const attachment = value as StoredAttachmentBytes;
+ return {
+ ...attachment,
+ data: new Uint8Array(attachment.data),
+ } as ChatDbSchema[K];
+ }
+
+ const cloned = { ...value } as ChatDbSchema[K];
+ if (name === "messages") {
+ const message = cloned as StoredMessage;
+ message.attachments = message.attachments?.map((attachment) => ({
+ ...attachment,
+ }));
+ }
+ return cloned;
};
+const createObjectStore = <K extends ChatStoreName>(
+ state: ChatStoreState,
+ name: K,
+): ChatObjectStore<K> => ({
+ get: async (key) =>
+ (() => {
+ const entry = getStoreCollection(state, name).find(
+ (candidate) => getStoreKey(name, candidate) === key,
+ );
+ return entry ? cloneStoreEntry(name, entry) : undefined;
+ })(),
+ getAll: async () =>
+ getStoreCollection(state, name).map((entry) =>
+ cloneStoreEntry(name, entry),
+ ),
+ put: async (value) => {
+ const collection = getStoreCollection(state, name);
+ const key = getStoreKey(name, value);
+ const index = collection.findIndex((entry) => getStoreKey(name, entry) === key);
+ const nextValue = cloneStoreEntry(name, value);
+ if (index >= 0) {
+ collection[index] = nextValue;
+ } else {
+ collection.push(nextValue);
+ }
+ },
+ delete: async (key) => {
+ const collection = getStoreCollection(state, name);
+ const index = collection.findIndex((entry) => getStoreKey(name, entry) === key);
+ if (index >= 0) {
+ collection.splice(index, 1);
+ }
+ },
+});
+
+const createLocalStorageChatDb = (): ChatDbLike => ({
+ get: async (name, key) => createObjectStore(loadChatStoreState(), name).get(key),
+ getAll: async (name) => createObjectStore(loadChatStoreState(), name).getAll(),
+ put: async (name, value) => {
+ const state = loadChatStoreState();
+ await createObjectStore(state, name).put(value);
+ saveChatStoreState(state);
+ },
+ delete: async (name, key) => {
+ const state = loadChatStoreState();
+ await createObjectStore(state, name).delete(key);
+ saveChatStoreState(state);
+ },
+ transaction: () => {
+ const state = cloneStoreState(loadChatStoreState());
+ return {
+ objectStore: <K extends ChatStoreName>(name: K): ChatObjectStore<K> => {
+ const base = createObjectStore(state, name);
+ return {
+ get: base.get,
+ getAll: base.getAll,
+ put: async (value: ChatDbSchema[K]) => {
+ await base.put(value);
+ saveChatStoreState(state);
+ },
+ delete: async (key: string) => {
+ await base.delete(key);
+ saveChatStoreState(state);
+ },
+ };
+ },
+ done: Promise.resolve(),
+ };
+ },
+ close: () => {},
+});
+
+let _chatDb: Promise<ChatDbLike> | undefined;
+
+const openChatDb = async () => createLocalStorageChatDb();
+
const chatDb = () => (_chatDb ??= openChatDb());
const normalizeTitleText = (value: string) => value.replace(/\s+/g, " ").trim();
@@ -898,32 +1051,14 @@ export const getBranchSelections = (rootSessionUuid: string) => {
export const resetChatStore = async () => {
if (typeof window === "undefined") return;
+ localStorage.removeItem(STORAGE_KEY);
localStorage.removeItem(BRANCH_SELECTIONS_KEY);
if (isTauriRuntime()) {
await invokeChat("chat_db_reset");
return;
}
-
- if (typeof indexedDB === "undefined") return;
-
- try {
- if (_chatDb) {
- const db = await _chatDb;
- db.close();
- }
- } catch (error) {
- log.error("Failed to close chat DB", error);
- }
-
_chatDb = undefined;
-
- await new Promise<void>((resolve, reject) => {
- const request = indexedDB.deleteDatabase(DB_NAME);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error);
- request.onblocked = () => resolve();
- });
};
export const setBranchSelection = (