Skip to content

Commit

Permalink
fix: improve database initialization and error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
vgcman16 committed Oct 30, 2024
1 parent 02030cb commit fb156fa
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 37 deletions.
21 changes: 18 additions & 3 deletions app/lib/persistence/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { ChatHistoryItem } from './useChatHistory';
const logger = createScopedLogger('ChatHistory');

let dbInitAttempted = false;
let dbInitializing = false;

function isBrowserEnvironment(): boolean {
try {
Expand All @@ -19,17 +20,19 @@ function isBrowserEnvironment(): boolean {
}

export async function openDatabase(): Promise<IDBDatabase | undefined> {
if (dbInitAttempted) {
logger.debug('Database initialization already attempted');
if (dbInitAttempted || dbInitializing) {
logger.debug('Database initialization already attempted or in progress');
return undefined;
}

dbInitAttempted = true;
dbInitializing = true;

return new Promise((resolve) => {
try {
if (!isBrowserEnvironment()) {
logger.debug('Not in browser environment or IndexedDB not available');
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
return;
}
Expand Down Expand Up @@ -57,31 +60,43 @@ export async function openDatabase(): Promise<IDBDatabase | undefined> {
const transaction = db.transaction(['chats'], 'readonly');
transaction.oncomplete = () => {
logger.debug('Database test successful');
dbInitAttempted = true;
dbInitializing = false;
resolve(db);
};
transaction.onerror = () => {
logger.error('Database test failed');
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
};
} catch (error) {
logger.error('Error testing database:', error);
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
}
};

request.onerror = (event: Event) => {
const error = (event.target as IDBOpenDBRequest).error;
logger.error('Failed to open database:', error?.message || 'Unknown error');
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
};

request.onblocked = () => {
logger.error('Database blocked');
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
};

} catch (error) {
logger.error('Error initializing database:', error);
dbInitAttempted = true;
dbInitializing = false;
resolve(undefined);
}
});
Expand Down
66 changes: 32 additions & 34 deletions app/lib/persistence/useChatHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,29 @@ export interface ChatHistoryItem {
// Initialize database lazily when needed
let db: IDBDatabase | undefined;
let dbInitialized = false;
let dbInitializing = false;

export const chatId = atom<string | undefined>(undefined);
export const description = atom<string | undefined>(undefined);

async function initializeDb() {
if (dbInitialized || dbInitializing) {
return db;
}

dbInitializing = true;
try {
db = await openDatabase();
dbInitialized = true;
logger.debug('Database initialized successfully');
} catch (error) {
logger.error('Failed to initialize database:', error);
} finally {
dbInitializing = false;
}
return db;
}

export function useChatHistory() {
const navigate = useNavigate();
const { id: mixedId } = useLoaderData<{ id?: string }>();
Expand All @@ -33,49 +52,28 @@ export function useChatHistory() {

// Initialize database when component mounts
useEffect(() => {
const initDb = async () => {
const init = async () => {
try {
// Only attempt to initialize once
if (!dbInitialized) {
logger.debug('Initializing database');
db = await openDatabase();
dbInitialized = true;
}

// If we have a mixedId but no database, navigate home
if (mixedId && !db) {
logger.debug('No database available, navigating home');
navigate('/', { replace: true });
setReady(true);
return;
}

// If we have both mixedId and database, try to load messages
if (mixedId && db) {
try {
const storedMessages = await getMessages(db, mixedId);
if (storedMessages && storedMessages.messages.length > 0) {
setInitialMessages(storedMessages.messages);
setUrlId(storedMessages.urlId);
description.set(storedMessages.description);
chatId.set(storedMessages.id);
} else {
navigate('/', { replace: true });
}
} catch (error) {
logger.error('Failed to load messages:', error);
const database = await initializeDb();

if (mixedId && database) {
const storedMessages = await getMessages(database, mixedId);
if (storedMessages && storedMessages.messages.length > 0) {
setInitialMessages(storedMessages.messages);
setUrlId(storedMessages.urlId);
description.set(storedMessages.description);
chatId.set(storedMessages.id);
} else {
navigate('/', { replace: true });
}
}

setReady(true);
} catch (error) {
logger.error('Failed to initialize:', error);
setReady(true);
}
setReady(true);
};

initDb();
init();
}, [mixedId, navigate]);

return {
Expand Down

0 comments on commit fb156fa

Please sign in to comment.