-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataSource.ts
More file actions
315 lines (279 loc) · 9.17 KB
/
Copy pathDataSource.ts
File metadata and controls
315 lines (279 loc) · 9.17 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import PouchDB from 'pouchdb';
import pouchdbFind from 'pouchdb-find';
import { ContextRepository } from '@/data/ContextRepository';
import { DocumentTypes } from '@/data/documentTypes';
import { LocalSettings } from '@/data/documentTypes/LocalSettings';
import { PreferencesRepository } from '@/data/PreferencesRepository';
import { TaskRepository } from '@/data/TaskRepository';
import { Logger } from '@/helpers/Logger';
import { MigrationManager } from './migrations/MigrationManager';
export enum SyncStatus {
NOT_CONFIGURED = 'not_configured',
INACTIVE = 'inactive',
ACTIVE = 'active',
PAUSED = 'paused',
ERROR = 'error',
}
export class DataSource {
protected db: PouchDB.Database<DocumentTypes>;
private migrationManager: MigrationManager;
private syncHandler: PouchDB.Replication.Sync<{}> | null = null;
private taskRepository: TaskRepository | null = null;
private contextRepository: ContextRepository | null = null;
private preferencesRepository: PreferencesRepository | null = null;
public onMigrationStatusChange?: (isMigrating: boolean) => void;
public onSyncStatusChange?: (status: SyncStatus) => void;
public syncStatus: SyncStatus = SyncStatus.NOT_CONFIGURED;
/**
* Creates a new LocalDataSource instance.
* If a database is provided, it will use that database; otherwise, it will create a new
* PouchDB instance.
*
* @param database Optional PouchDB database instance to use.
* @param migrationManager Optional MigrationManager instance to use for migrations.
*/
constructor(database: PouchDB.Database<DocumentTypes>, migrationManager?: MigrationManager) {
this.db = database;
PouchDB.plugin(pouchdbFind);
if (migrationManager) {
this.migrationManager = migrationManager;
} else {
this.migrationManager = new MigrationManager(this.db);
}
}
/**
* Get the PouchDB database instance.
*/
getDatabase(): PouchDB.Database<DocumentTypes> {
return this.db;
}
/**
* Cleanup all active subscriptions and resources.
* This should be called when the DataSource instance is no longer needed
* to prevent memory leaks and ensure proper cleanup of PouchDB change feeds.
*/
async cleanup(): Promise<void> {
Logger.info('Cleaning up DataSource');
await this.getTaskRepository().cleanup();
await this.getContextRepository().cleanup();
Logger.info('DataSource cleanup completed');
}
/**
* Create/return the TaskRepository singleton
*/
getTaskRepository(): TaskRepository {
if (!this.taskRepository) {
this.taskRepository = new TaskRepository(this.db);
}
return this.taskRepository;
}
/**
* Create/return the ContextRepository singleton
*/
getContextRepository(): ContextRepository {
if (!this.contextRepository) {
this.contextRepository = new ContextRepository(this.db);
}
return this.contextRepository;
}
/**
* Create/return the PreferencesRepository singleton
*/
getPreferencesRepository(): PreferencesRepository {
if (!this.preferencesRepository) {
this.preferencesRepository = new PreferencesRepository(this.db);
}
return this.preferencesRepository;
}
/**
* Initialize the sync process with the remote server.
*/
async initializeSync() {
Logger.info('Initializing sync');
const settings = await this.getLocalSettings();
if (!settings.syncServerUrl || !settings.syncServerAccessToken) {
Logger.info('No sync server settings found, skipping sync setup');
this.setSyncStatus(SyncStatus.NOT_CONFIGURED);
return;
}
const syncDb = this.createSyncDb(settings);
await this.verifySyncConnection(syncDb);
try {
this.syncHandler = this.db
.sync(syncDb, {
live: true,
retry: true,
})
.on('change', (info) => {
Logger.info('Sync change:', info);
this.setSyncStatus(SyncStatus.ACTIVE);
})
.on('paused', () => {
Logger.info('Sync paused (up to date)');
this.setSyncStatus(SyncStatus.PAUSED);
})
.on('active', () => {
Logger.info('Sync resumed');
this.setSyncStatus(SyncStatus.ACTIVE);
})
.on('denied', (err) => {
Logger.error('Sync denied:', err);
this.setSyncStatus(SyncStatus.ERROR);
})
.on('complete', (info) => {
Logger.info('Sync complete:', info);
this.setSyncStatus(SyncStatus.INACTIVE);
})
.on('error', (err) => {
Logger.error('Error replicating to remote database:', err);
this.setSyncStatus(SyncStatus.ERROR);
});
} catch (error) {
Logger.error('Error initializing sync:', error);
this.cancelSync();
this.setSyncStatus(SyncStatus.ERROR);
throw error; // Re-throw to handle it in the calling code
}
}
/**
* Create a new PouchDB database for syncing with a couchdb server.
*
* @param settings
*/
createSyncDb(settings: LocalSettings): PouchDB.Database {
Logger.info('Creating sync database');
return new PouchDB(settings.syncServerUrl, {
headers: {
Authorization: `Bearer ${settings.syncServerAccessToken}`,
},
} as PouchDB.Configuration.DatabaseConfiguration & { headers?: Record<string, string> });
}
/**
* Cancels the current sync operation if it is active.
*/
cancelSync() {
Logger.info('Cancelling sync');
if (this.syncHandler) {
this.syncHandler.cancel();
this.syncHandler = null;
if (this.syncStatus !== SyncStatus.ERROR) {
this.setSyncStatus(SyncStatus.INACTIVE);
}
} else {
Logger.info('No active sync to cancel');
}
}
/**
* Run any pending migrations.
*/
async runMigrations(): Promise<void> {
if (!(await this.migrationManager.needsMigration())) {
return;
}
try {
this.onMigrationStatusChange?.(true);
await this.migrationManager.runMigrations();
} finally {
this.onMigrationStatusChange?.(false);
}
}
/**
* Get the local settings from the database. These settings are not synced to the server
*
*/
async getLocalSettings(): Promise<LocalSettings> {
try {
Logger.info('Getting local settings');
return await this.db.get<LocalSettings>('_local/settings');
} catch (error) {
if (this.isPouchNotFoundError(error)) {
// If the document does not exist, return default settings
Logger.info('Local settings not found, returning default settings');
return {
_id: '_local/settings',
};
}
Logger.error('Error getting local settings:', error);
throw error;
}
}
/**
* Set the local settings in the database. These will never be synced to the server.
*
* @param settings
*/
async setLocalSettings(settings: LocalSettings): Promise<void> {
try {
Logger.info('Setting local settings');
await this.db.put<LocalSettings>(settings);
} catch (error) {
Logger.error('Error setting local settings:', error);
throw error; // Re-throw to handle it in the calling code
}
}
/**
* Export all data from the database, excluding _local documents.
*/
async exportAllData(): Promise<DocumentTypes[]> {
Logger.info('Exporting all data from the database');
try {
const result = await this.db.allDocs<DocumentTypes>({
include_docs: true,
});
return result.rows.map((row) => row.doc!);
} catch (error) {
Logger.error('Error exporting data:', error);
throw error;
}
}
/**
* Import data into the database.
* @param docs
*/
async importData(docs: DocumentTypes[]): Promise<void> {
Logger.info('Importing data into the database');
try {
// We probably don't want to allow _local documents to be imported, as it
// can activate sync
const filteredDocs = docs.filter((doc) => !doc._id.startsWith('_local/'));
const cleanedDocs = filteredDocs.map((doc) => {
const { _rev, ...cleanDoc } = doc as any;
return cleanDoc;
});
await this.db.bulkDocs(cleanedDocs);
Logger.info('Data imported successfully:');
} catch (error) {
Logger.error('Error importing data:', error);
throw error; // Re-throw to handle it in the calling code
}
}
private async verifySyncConnection(syncDb: PouchDB.Database): Promise<void> {
try {
await syncDb.info();
} catch (error) {
this.setSyncStatus(SyncStatus.ERROR);
Logger.error('Error connecting to sync database:', error);
throw new Error(
'Failed to connect to sync database. Please check your sync server URL and access token.'
);
}
}
// Is the error a PouchDB not found error?
/**
* Check if sync is configured.
*/
async isSyncConfigured(): Promise<boolean> {
const settings = await this.getLocalSettings();
return !!settings.syncServerUrl;
}
private setSyncStatus(status: SyncStatus) {
if (this.syncStatus !== status) {
this.syncStatus = status;
this.onSyncStatusChange?.(this.syncStatus);
}
}
// Is the error a PouchDB not found error?
private isPouchNotFoundError(err: any): err is PouchDB.Core.Error {
return err && (err.status === 404 || err.name === 'not_found');
}
}