-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection-context.tsx
More file actions
297 lines (263 loc) · 9.69 KB
/
Copy pathconnection-context.tsx
File metadata and controls
297 lines (263 loc) · 9.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import React, { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
import { DBConfig, SavedConnection } from '@/types';
import { db } from '@/lib/db';
import { getIdleTimeoutMin } from '@/lib/app-settings';
import { track, toDbKind } from '@/lib/telemetry';
import { useToast } from './toast-context';
const ACTIVITY_THROTTLE_MS = 5_000;
const ACTIVITY_CHANNEL = 'justdb-activity';
const ACTIVITY_EVENTS: Array<keyof DocumentEventMap> = [
'mousedown',
'keydown',
'scroll',
'touchstart',
'visibilitychange',
];
interface ConnectionContextType {
isConnected: boolean;
isConnecting: boolean;
databaseName?: string;
databaseType: "postgresql" | "mysql" | "sqlite";
currentConnectionId?: string;
savedConnections: SavedConnection[];
connect: (config: DBConfig, name?: string) => Promise<void>;
connectToSaved: (connectionId: string) => Promise<void>;
cancelConnect: () => void;
disconnect: () => Promise<void>;
saveConnection: (name: string, config: DBConfig) => void;
deleteConnection: (connectionId: string) => void;
error: string | null;
}
const ConnectionContext = createContext<ConnectionContextType | undefined>(undefined);
const CURRENT_CONNECTION_KEY = 'db-current-connection';
export function ConnectionProvider({ children }: { children: React.ReactNode }) {
const [isConnected, setIsConnected] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [databaseName, setDatabaseName] = useState<string | undefined>();
const [currentConnectionId, setCurrentConnectionId] = useState<string | undefined>();
const [savedConnections, setSavedConnections] = useState<SavedConnection[]>([]);
const [databaseType, setDatabaseType] = useState<"postgresql" | "mysql" | "sqlite">("postgresql");
const [error, setError] = useState<string | null>(null);
const { addToast } = useToast();
const idleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastActivityRef = useRef<number>(0);
// Token bumped per connect attempt; cancelConnect bumps it too so the
// resolving await sees a mismatch and discards its result. Tauri's
// invoke() can't actually be aborted — we just make the UI behave as
// if it were, and clean up the orphan session that does come back.
const connectTokenRef = useRef(0);
const loadSavedConnections = useCallback(async () => {
try {
const connections = await db.savedList();
setSavedConnections(connections);
} catch (e) {
console.error('Failed to load saved connections:', e);
}
}, []);
useEffect(() => {
loadSavedConnections();
}, [loadSavedConnections]);
useEffect(() => {
if (savedConnections.length > 0 && !isConnected) {
const currentId = typeof window !== 'undefined'
? localStorage.getItem(CURRENT_CONNECTION_KEY)
: null;
if (currentId) {
const connection = savedConnections.find(c => c.id === currentId);
if (connection) {
connectToSaved(currentId).catch(() => {});
}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [savedConnections.length]);
const connect = async (config: DBConfig, name?: string) => {
const token = ++connectTokenRef.current;
setIsConnecting(true);
setError(null);
try {
const connectionId = name
? `conn_${Date.now()}_${Math.random().toString(36).substring(7)}`
: undefined;
// Single call: opens the session + optionally writes to the OS keychain.
const data = await db.connect(
config,
name && connectionId ? { name, id: connectionId } : undefined,
);
if (connectTokenRef.current !== token) {
// Cancelled or superseded. Discard this session in the background.
void db.disconnectId(data.sessionId);
return;
}
setIsConnected(true);
setDatabaseName(data.database || config.database);
setDatabaseType((data.type || config.type || 'postgresql') as 'postgresql' | 'mysql' | 'sqlite');
void track({ name: 'connection_opened', db_type: toDbKind(data.type || config.type), success: true });
if (name && data.savedConnection) {
setSavedConnections(prev => [...prev, data.savedConnection!]);
setCurrentConnectionId(connectionId);
localStorage.setItem(CURRENT_CONNECTION_KEY, connectionId!);
}
} catch (err: any) {
if (connectTokenRef.current !== token) return;
setError(err.message || 'Connection failed');
setIsConnected(false);
setDatabaseName(undefined);
void track({ name: 'connection_opened', db_type: toDbKind(config.type), success: false });
throw err;
} finally {
if (connectTokenRef.current === token) setIsConnecting(false);
}
};
const connectToSaved = async (connectionId: string) => {
const connection = savedConnections.find(c => c.id === connectionId);
if (!connection) {
throw new Error('Connection not found');
}
const token = ++connectTokenRef.current;
setIsConnecting(true);
setError(null);
try {
// Rust pulls the credentials from the OS keychain and opens a fresh session.
const data = await db.connectSaved(connectionId);
if (connectTokenRef.current !== token) {
void db.disconnectId(data.sessionId);
return;
}
setIsConnected(true);
setDatabaseName(data.database || connection.config.database);
setDatabaseType((data.type || connection.config.type || 'postgresql') as 'postgresql' | 'mysql' | 'sqlite');
void track({ name: 'connection_opened', db_type: toDbKind(data.type || connection.config.type), success: true });
setCurrentConnectionId(connectionId);
localStorage.setItem(CURRENT_CONNECTION_KEY, connectionId);
setSavedConnections(prev =>
prev.map(c =>
c.id === connectionId ? { ...c, lastUsed: Date.now() } : c
)
);
} catch (err: any) {
if (connectTokenRef.current !== token) return;
setError(err.message || 'Connection failed');
setIsConnected(false);
setDatabaseName(undefined);
throw err;
} finally {
if (connectTokenRef.current === token) setIsConnecting(false);
}
};
const cancelConnect = useCallback(() => {
connectTokenRef.current += 1;
setIsConnecting(false);
setError(null);
}, []);
const disconnect = useCallback(async () => {
try {
await db.disconnect();
setIsConnected(false);
setDatabaseName(undefined);
setDatabaseType("postgresql");
setCurrentConnectionId(undefined);
if (typeof window !== 'undefined') {
localStorage.removeItem(CURRENT_CONNECTION_KEY);
}
setError(null);
} catch (err: any) {
setError(err.message || 'Disconnect failed');
}
}, []);
useEffect(() => {
if (!isConnected) {
if (idleTimerRef.current) {
clearTimeout(idleTimerRef.current);
idleTimerRef.current = null;
}
return;
}
const channel =
typeof BroadcastChannel !== 'undefined'
? new BroadcastChannel(ACTIVITY_CHANNEL)
: null;
const idleMin = getIdleTimeoutMin();
const arm = () => {
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
idleTimerRef.current = setTimeout(() => {
void disconnect();
addToast(`Disconnected after ${idleMin} minutes of inactivity`, 'info');
}, idleMin * 60 * 1000);
};
const noteActivity = (broadcast: boolean) => {
const now = Date.now();
if (now - lastActivityRef.current < ACTIVITY_THROTTLE_MS) return;
lastActivityRef.current = now;
arm();
if (broadcast && channel) channel.postMessage({ t: now });
};
lastActivityRef.current = Date.now();
arm();
const onLocalActivity = () => noteActivity(true);
const onRemoteActivity = () => noteActivity(false);
ACTIVITY_EVENTS.forEach((ev) =>
document.addEventListener(ev, onLocalActivity, { passive: true })
);
if (channel) channel.addEventListener('message', onRemoteActivity);
return () => {
ACTIVITY_EVENTS.forEach((ev) => document.removeEventListener(ev, onLocalActivity));
if (channel) {
channel.removeEventListener('message', onRemoteActivity);
channel.close();
}
if (idleTimerRef.current) {
clearTimeout(idleTimerRef.current);
idleTimerRef.current = null;
}
};
}, [isConnected, disconnect, addToast]);
const saveConnection = async (name: string, config: DBConfig) => {
const connectionId = `conn_${Date.now()}_${Math.random().toString(36).substring(7)}`;
try {
const connection = await db.savedCreate(connectionId, name, config);
setSavedConnections(prev => [...prev, connection]);
} catch (e) {
console.error('Failed to save connection:', e);
}
};
const deleteConnection = async (connectionId: string) => {
try {
await db.savedDelete(connectionId);
setSavedConnections(prev => prev.filter(c => c.id !== connectionId));
if (currentConnectionId === connectionId) {
disconnect();
}
} catch (e) {
console.error('Failed to delete connection:', e);
}
};
return (
<ConnectionContext.Provider
value={{
isConnected,
isConnecting,
databaseName,
databaseType,
currentConnectionId,
savedConnections,
connect,
connectToSaved,
cancelConnect,
disconnect,
saveConnection,
deleteConnection,
error,
}}
>
{children}
</ConnectionContext.Provider>
);
}
export function useConnection() {
const context = useContext(ConnectionContext);
if (context === undefined) {
throw new Error('useConnection must be used within a ConnectionProvider');
}
return context;
}