diff --git a/src/services/database.service.ts b/src/services/database.service.ts index a9df19b..924f8c4 100755 --- a/src/services/database.service.ts +++ b/src/services/database.service.ts @@ -1,7 +1,6 @@ -import Services from "./service"; - /** - * Database service managing IndexedDB operations via Web Worker and Service Worker + * Database service managing IndexedDB operations via Web Worker + * Pure Data Store Layer */ export class Database { // ============================================ @@ -9,8 +8,6 @@ export class Database { // ============================================ private static instance: Database; - private serviceWorkerRegistration: ServiceWorkerRegistration | null = null; - private serviceWorkerCheckIntervalId: number | null = null; private indexedDBWorker: Worker | null = null; private messageIdCounter: number = 0; private pendingMessages: Map< @@ -24,7 +21,6 @@ export class Database { private constructor() { this.initIndexedDBWorker(); - this.initServiceWorker(); } public static async getInstance(): Promise { @@ -81,7 +77,6 @@ export class Database { this.indexedDBWorker.postMessage({ type, payload, id }); - // Timeout de sécurité (30 secondes) setTimeout(() => { if (this.pendingMessages.has(id)) { this.pendingMessages.delete(id); @@ -91,186 +86,6 @@ export class Database { }); } - // ============================================ - // SERVICE WORKER - // ============================================ - - private initServiceWorker(): void { - this.registerServiceWorker("/data.worker.js"); - } - - private async registerServiceWorker(path: string): Promise { - if (!("serviceWorker" in navigator)) return; - console.log("[Database] Initializing Service Worker:", path); - - try { - const registrations = await navigator.serviceWorker.getRegistrations(); - - for (const registration of registrations) { - const scriptURL = - registration.active?.scriptURL || - registration.installing?.scriptURL || - registration.waiting?.scriptURL; - const scope = registration.scope; - - if ( - scope.includes("/src/service-workers/") || - (scriptURL && scriptURL.includes("/src/service-workers/")) - ) { - console.warn(`[Database] Removing old Service Worker (${scope})`); - await registration.unregister(); - } - } - - const existingValidWorker = registrations.find((r) => { - const url = - r.active?.scriptURL || - r.installing?.scriptURL || - r.waiting?.scriptURL; - return url && url.endsWith(path.replace(/^\//, "")); - }); - - if (!existingValidWorker) { - console.log("[Database] Registering new Service Worker"); - this.serviceWorkerRegistration = await navigator.serviceWorker.register( - path, - { type: "module", scope: "/" } - ); - } else { - console.log("[Database] Service Worker already active"); - this.serviceWorkerRegistration = existingValidWorker; - await this.serviceWorkerRegistration.update(); - } - - navigator.serviceWorker.addEventListener("message", async (event) => { - await this.handleServiceWorkerMessage(event.data); - }); - - if (this.serviceWorkerCheckIntervalId) - clearInterval(this.serviceWorkerCheckIntervalId); - this.serviceWorkerCheckIntervalId = window.setInterval(async () => { - const activeWorker = - this.serviceWorkerRegistration?.active || - (await this.waitForServiceWorkerActivation( - this.serviceWorkerRegistration! - )); - const service = await Services.getInstance(); - const payload = await service.getMyProcesses(); - if (payload && payload.length != 0) { - activeWorker?.postMessage({ type: "SCAN", payload }); - } - }, 5000); - } catch (error) { - console.error("[Database] Service Worker error:", error); - } - } - - private async waitForServiceWorkerActivation( - registration: ServiceWorkerRegistration - ): Promise { - return new Promise((resolve) => { - if (registration.active) { - resolve(registration.active); - } else { - const listener = () => { - if (registration.active) { - navigator.serviceWorker.removeEventListener( - "controllerchange", - listener - ); - resolve(registration.active); - } - }; - navigator.serviceWorker.addEventListener("controllerchange", listener); - } - }); - } - - private async checkForUpdates(): Promise { - if (this.serviceWorkerRegistration) { - try { - await this.serviceWorkerRegistration.update(); - - if (this.serviceWorkerRegistration.waiting) { - this.serviceWorkerRegistration.waiting.postMessage({ - type: "SKIP_WAITING", - }); - } - } catch (error) { - console.error("Error checking for service worker updates:", error); - } - } - } - - // ============================================ - // SERVICE WORKER MESSAGE HANDLERS - // ============================================ - - private async handleServiceWorkerMessage(message: any) { - switch (message.type) { - case "TO_DOWNLOAD": - await this.handleDownloadList(message.data); - break; - case "DIFFS_TO_CREATE": - await this.handleDiffsToCreate(message.data); - break; - default: - console.warn( - "Unknown message type received from service worker:", - message - ); - } - } - - private async handleDiffsToCreate(diffs: any[]): Promise { - console.log( - `[Database] Creating ${diffs.length} diffs from Service Worker scan` - ); - try { - await this.saveDiffs(diffs); - console.log("[Database] Diffs created successfully"); - } catch (error) { - console.error("[Database] Error creating diffs:", error); - } - } - - private async handleDownloadList(downloadList: string[]): Promise { - let requestedStateId: string[] = []; - const service = await Services.getInstance(); - for (const hash of downloadList) { - const diff = await service.getDiffByValue(hash); - if (!diff) { - console.warn(`Missing a diff for hash ${hash}`); - continue; - } - const processId = diff.process_id; - const stateId = diff.state_id; - const roles = diff.roles; - try { - const valueBytes = await service.fetchValueFromStorage(hash); - if (valueBytes) { - const blob = new Blob([valueBytes], { - type: "application/octet-stream", - }); - await service.saveBlobToDb(hash, blob); - document.dispatchEvent( - new CustomEvent("newDataReceived", { - detail: { processId, stateId, hash }, - }) - ); - } else { - console.log("Request data from managers of the process"); - if (!requestedStateId.includes(stateId)) { - await service.requestDataFromPeers(processId, [stateId], [roles]); - requestedStateId.push(stateId); - } - } - } catch (e) { - console.error(e); - } - } - } - // ============================================ // GENERIC INDEXEDDB OPERATIONS // ============================================