refactor(service): standardize import statements, improve code organization, and enhance clarity in Services class methods

This commit is contained in:
NicolasCantu 2025-12-03 10:06:15 +01:00
parent d78dc14a2b
commit 6dd8ce730f

View File

@ -1,9 +1,19 @@
import * as Comlink from 'comlink';
import { ApiReturn, Device, Member, MerkleProofResult, Process, ProcessState, SecretsStore, UserDiff } from '../../pkg/sdk_client';
import { BackUp } from '../types/index';
import { APP_CONFIG } from '../config/constants';
import { NetworkService } from './core/network.service';
import type { CoreBackend } from '../workers/core.worker';
import * as Comlink from "comlink";
import {
ApiReturn,
Device,
Member,
MerkleProofResult,
Process,
ProcessState,
SecretsStore,
UserDiff,
} from "../../pkg/sdk_client";
import { BackUp } from "../types/index";
import { APP_CONFIG } from "../config/constants";
import { NetworkService } from "./core/network.service";
import type { CoreBackend } from "../workers/core.worker";
import Database from "./database.service";
export default class Services {
private static instance: Services;
@ -21,8 +31,8 @@ export default class Services {
// Initialisation du Core Worker
this.workerInstance = new Worker(
new URL('../workers/core.worker.ts', import.meta.url),
{ type: 'module' }
new URL("../workers/core.worker.ts", import.meta.url),
{ type: "module" }
);
this.coreWorker = Comlink.wrap<CoreBackend>(this.workerInstance);
}
@ -41,23 +51,26 @@ export default class Services {
}
public async init(): Promise<void> {
console.log('[Services] 🚀 Démarrage Proxy...');
console.log("[Services] 🚀 Démarrage Proxy...");
// 1. Initialiser le Core Worker
await this.coreWorker.init();
// 2. Configurer les Callbacks (Le worker pilote le main thread pour le réseau)
// 2. Initialiser la Database ici (Main Thread) pour lancer le SW
await Database.getInstance();
// 3. Configurer les Callbacks (Le worker pilote le main thread pour le réseau)
await this.coreWorker.setCallbacks(
Comlink.proxy(this.handleWorkerNotification.bind(this)), // notifier
Comlink.proxy(this.handleWorkerNetworkSend.bind(this)), // networkSender
Comlink.proxy(this.handleWorkerRelayUpdate.bind(this)), // relayUpdater
Comlink.proxy(this.handleWorkerRelayRequest.bind(this)) // relayGetter
Comlink.proxy(this.handleWorkerNetworkSend.bind(this)), // networkSender
Comlink.proxy(this.handleWorkerRelayUpdate.bind(this)), // relayUpdater
Comlink.proxy(this.handleWorkerRelayRequest.bind(this)) // relayGetter
);
// 3. Initialiser le Réseau (Network Worker via Proxy)
await this.networkService.initRelays();
console.log('[Services] ✅ Proxy connecté au CoreWorker et NetworkService.');
console.log(
"[Services] ✅ Proxy connecté au CoreWorker et NetworkService."
);
}
// ==========================================
@ -85,155 +98,345 @@ export default class Services {
// ==========================================
public async dispatchToWorker(flag: string, content: string, url: string) {
switch (flag) {
case 'Handshake': await this.coreWorker.handleHandshakeMsg(url, content); break;
case 'NewTx': await this.coreWorker.parseNewTx(content); break;
case 'Cipher': await this.coreWorker.parseCipher(content); break;
case 'Commit': await this.coreWorker.handleCommitError(content); break;
case "Handshake":
await this.coreWorker.handleHandshakeMsg(url, content);
break;
case "NewTx":
await this.coreWorker.parseNewTx(content);
break;
case "Cipher":
await this.coreWorker.parseCipher(content);
break;
case "Commit":
await this.coreWorker.handleCommitError(content);
break;
}
}
// ==========================================
// PROXY - PROPERTIES PUBLIC
// ==========================================
public async getDevice1() { return await this.coreWorker.getDevice1(); }
public async getDevice2Ready() { return await this.coreWorker.getDevice2Ready(); }
public async getDevice1() {
return await this.coreWorker.getDevice1();
}
public async getDevice2Ready() {
return await this.coreWorker.getDevice2Ready();
}
// NOTE: getSdkClient renvoie null car l'objet WASM n'est pas transférable hors du worker.
// Toute la logique utilisant le client doit être dans le worker.
public get sdkClient() { return null; }
public get sdkClient() {
return null;
}
public async setProcessId(id: string | null) { return await this.coreWorker.setProcessId(id); }
public async setStateId(id: string | null) { return await this.coreWorker.setStateId(id); }
public async getProcessId() { return await this.coreWorker.getProcessId(); }
public async getStateId() { return await this.coreWorker.getStateId(); }
public async resetState() { return await this.coreWorker.resetState(); }
public async setProcessId(id: string | null) {
return await this.coreWorker.setProcessId(id);
}
public async setStateId(id: string | null) {
return await this.coreWorker.setStateId(id);
}
public async getProcessId() {
return await this.coreWorker.getProcessId();
}
public async getStateId() {
return await this.coreWorker.getStateId();
}
public async resetState() {
return await this.coreWorker.resetState();
}
// ==========================================
// PROXY - NETWORK PROXY
// ==========================================
public async connectAllRelays() { await this.networkService.connectAllRelays(); }
public async addWebsocketConnection(url: string) { await this.networkService.addWebsocketConnection(url); }
public getAllRelays() { return this.networkService.getAllRelays(); }
public updateRelay(url: string, sp: string) { this.networkService.updateRelay(url, sp); }
public getSpAddress(url: string) { return this.networkService.getAllRelays()[url]; }
public async connectAllRelays() {
await this.networkService.connectAllRelays();
}
public async addWebsocketConnection(url: string) {
await this.networkService.addWebsocketConnection(url);
}
public getAllRelays() {
return this.networkService.getAllRelays();
}
public updateRelay(url: string, sp: string) {
this.networkService.updateRelay(url, sp);
}
public getSpAddress(url: string) {
return this.networkService.getAllRelays()[url];
}
// Délégation directe au NetworkService
public printAllRelays() {
// Si NetworkService ne l'expose pas directement dans sa version proxy, on l'ajoute ou on log ici
console.log('Relays:', this.networkService.getAllRelays());
console.log("Relays:", this.networkService.getAllRelays());
}
// ==========================================
// PROXY - WALLET
// ==========================================
public async isPaired() { return await this.coreWorker.isPaired(); }
public async getAmount() { return await this.coreWorker.getAmount(); }
public async getDeviceAddress() { return await this.coreWorker.getDeviceAddress(); }
public async dumpDeviceFromMemory() { return await this.coreWorker.dumpDeviceFromMemory(); }
public async dumpNeuteredDevice() { return await this.coreWorker.dumpNeuteredDevice(); }
public async getPairingProcessId() { return await this.coreWorker.getPairingProcessId(); }
public async getDeviceFromDatabase() { return await this.coreWorker.getDeviceFromDatabase(); }
public async restoreDevice(d: Device) { await this.coreWorker.restoreDevice(d); }
public async pairDevice(pid: string, list: string[]) { await this.coreWorker.pairDevice(pid, list); }
public async unpairDevice() { await this.coreWorker.unpairDevice(); }
public async saveDeviceInDatabase(d: Device) { await this.coreWorker.saveDeviceInDatabase(d); }
public async createNewDevice() { return await this.coreWorker.createNewDevice(); }
public async dumpWallet() { return await this.coreWorker.dumpWallet(); }
public async getMemberFromDevice() { return await this.coreWorker.getMemberFromDevice(); }
public async isPaired() {
return await this.coreWorker.isPaired();
}
public async getAmount() {
return await this.coreWorker.getAmount();
}
public async getDeviceAddress() {
return await this.coreWorker.getDeviceAddress();
}
public async dumpDeviceFromMemory() {
return await this.coreWorker.dumpDeviceFromMemory();
}
public async dumpNeuteredDevice() {
return await this.coreWorker.dumpNeuteredDevice();
}
public async getPairingProcessId() {
return await this.coreWorker.getPairingProcessId();
}
public async getDeviceFromDatabase() {
return await this.coreWorker.getDeviceFromDatabase();
}
public async restoreDevice(d: Device) {
await this.coreWorker.restoreDevice(d);
}
public async pairDevice(pid: string, list: string[]) {
await this.coreWorker.pairDevice(pid, list);
}
public async unpairDevice() {
await this.coreWorker.unpairDevice();
}
public async saveDeviceInDatabase(d: Device) {
await this.coreWorker.saveDeviceInDatabase(d);
}
public async createNewDevice() {
return await this.coreWorker.createNewDevice();
}
public async dumpWallet() {
return await this.coreWorker.dumpWallet();
}
public async getMemberFromDevice() {
return await this.coreWorker.getMemberFromDevice();
}
// ==========================================
// PROXY - PROCESS
// ==========================================
public async getProcess(id: string) { return await this.coreWorker.getProcess(id); }
public async getProcesses() { return await this.coreWorker.getProcesses(); }
public async restoreProcessesFromDB() { await this.coreWorker.restoreProcessesFromDB(); }
public async getLastCommitedState(p: Process) { return await this.coreWorker.getLastCommitedState(p); }
public async getUncommitedStates(p: Process) { return await this.coreWorker.getUncommitedStates(p); }
public async getStateFromId(p: Process, id: string) { return await this.coreWorker.getStateFromId(p, id); }
public async getRoles(p: Process) { return await this.coreWorker.getRoles(p); }
public async getLastCommitedStateIndex(p: Process) { return await this.coreWorker.getLastCommitedStateIndex(p); }
public async batchSaveProcessesToDb(p: Record<string, Process>) { return await this.coreWorker.batchSaveProcessesToDb(p); }
public async getProcess(id: string) {
return await this.coreWorker.getProcess(id);
}
public async getProcesses() {
return await this.coreWorker.getProcesses();
}
public async restoreProcessesFromDB() {
await this.coreWorker.restoreProcessesFromDB();
}
public async getLastCommitedState(p: Process) {
return await this.coreWorker.getLastCommitedState(p);
}
public async getUncommitedStates(p: Process) {
return await this.coreWorker.getUncommitedStates(p);
}
public async getStateFromId(p: Process, id: string) {
return await this.coreWorker.getStateFromId(p, id);
}
public async getRoles(p: Process) {
return await this.coreWorker.getRoles(p);
}
public async getLastCommitedStateIndex(p: Process) {
return await this.coreWorker.getLastCommitedStateIndex(p);
}
public async batchSaveProcessesToDb(p: Record<string, Process>) {
return await this.coreWorker.batchSaveProcessesToDb(p);
}
// ==========================================
// PROXY - CRYPTO
// ==========================================
public async decodeValue(val: number[]) { return await this.coreWorker.decodeValue(val); }
public async hexToBlob(hex: string) { return await this.coreWorker.hexToBlob(hex); }
public async hexToUInt8Array(hex: string) { return await this.coreWorker.hexToUInt8Array(hex); }
public async blobToHex(blob: Blob) { return await this.coreWorker.blobToHex(blob); }
public async getHashForFile(c: string, l: string, f: any) { return await this.coreWorker.getHashForFile(c, l, f); }
public async getMerkleProofForFile(s: ProcessState, a: string) { return await this.coreWorker.getMerkleProofForFile(s, a); }
public async validateMerkleProof(p: MerkleProofResult, h: string) { return await this.coreWorker.validateMerkleProof(p, h); }
public async decodeValue(val: number[]) {
return await this.coreWorker.decodeValue(val);
}
public async hexToBlob(hex: string) {
return await this.coreWorker.hexToBlob(hex);
}
public async hexToUInt8Array(hex: string) {
return await this.coreWorker.hexToUInt8Array(hex);
}
public async blobToHex(blob: Blob) {
return await this.coreWorker.blobToHex(blob);
}
public async getHashForFile(c: string, l: string, f: any) {
return await this.coreWorker.getHashForFile(c, l, f);
}
public async getMerkleProofForFile(s: ProcessState, a: string) {
return await this.coreWorker.getMerkleProofForFile(s, a);
}
public async validateMerkleProof(p: MerkleProofResult, h: string) {
return await this.coreWorker.validateMerkleProof(p, h);
}
// ==========================================
// PROXY - MEMBERS
// ==========================================
public async getAllMembers() { return await this.coreWorker.getAllMembers(); }
public async getAllMembersSorted() { return await this.coreWorker.getAllMembersSorted(); }
public async ensureMembersAvailable() { await this.coreWorker.ensureMembersAvailable(); }
public async getAddressesForMemberId(memberId: string) { return await this.coreWorker.getAddressesForMemberId(memberId); }
public async compareMembers(mA: string[], mB: string[]) { return await this.coreWorker.compareMembers(mA, mB); }
public async getAllMembers() {
return await this.coreWorker.getAllMembers();
}
public async getAllMembersSorted() {
return await this.coreWorker.getAllMembersSorted();
}
public async ensureMembersAvailable() {
await this.coreWorker.ensureMembersAvailable();
}
public async getAddressesForMemberId(memberId: string) {
return await this.coreWorker.getAddressesForMemberId(memberId);
}
public async compareMembers(mA: string[], mB: string[]) {
return await this.coreWorker.compareMembers(mA, mB);
}
// ==========================================
// PROXY - UTILS
// ==========================================
public async createFaucetMessage() { return await this.coreWorker.createFaucetMessage(); }
public async isChildRole(parent: any, child: any) { return await this.coreWorker.isChildRole(parent, child); }
public async createFaucetMessage() {
return await this.coreWorker.createFaucetMessage();
}
public async isChildRole(parent: any, child: any) {
return await this.coreWorker.isChildRole(parent, child);
}
// ==========================================
// PROXY - LOGIQUE METIER & API
// ==========================================
public async getMyProcesses() { return await this.coreWorker.getMyProcesses(); }
public async ensureConnections(p: Process, sId?: string) { await this.coreWorker.ensureConnections(p, sId || null); }
public async connectAddresses(addr: string[]) { return await this.coreWorker.connectAddresses(addr); }
public async getMyProcesses() {
return await this.coreWorker.getMyProcesses();
}
public async ensureConnections(p: Process, sId?: string) {
await this.coreWorker.ensureConnections(p, sId || null);
}
public async connectAddresses(addr: string[]) {
return await this.coreWorker.connectAddresses(addr);
}
public async createPairingProcess(name: string, pairWith: string[]) { return await this.coreWorker.createPairingProcess(name, pairWith); }
public async createProcess(priv: any, pub: any, roles: any) { return await this.coreWorker.createProcess(priv, pub, roles); }
public async updateProcess(pid: string, newData: any, priv: string[], roles: any) { return await this.coreWorker.updateProcess(pid, newData, priv, roles); }
public async createPairingProcess(name: string, pairWith: string[]) {
return await this.coreWorker.createPairingProcess(name, pairWith);
}
public async createProcess(priv: any, pub: any, roles: any) {
return await this.coreWorker.createProcess(priv, pub, roles);
}
public async updateProcess(
pid: string,
newData: any,
priv: string[],
roles: any
) {
return await this.coreWorker.updateProcess(pid, newData, priv, roles);
}
public async createPrdUpdate(pid: string, sid: string) { return await this.coreWorker.createPrdUpdate(pid, sid); }
public async createPrdResponse(pid: string, sid: string) { return await this.coreWorker.createPrdResponse(pid, sid); }
public async approveChange(pid: string, sid: string) { return await this.coreWorker.approveChange(pid, sid); }
public async rejectChange(pid: string, sid: string) { return await this.coreWorker.rejectChange(pid, sid); }
public async requestDataFromPeers(pid: string, sids: string[], roles: any) { await this.coreWorker.requestDataFromPeers(pid, sids, roles); }
public async createPrdUpdate(pid: string, sid: string) {
return await this.coreWorker.createPrdUpdate(pid, sid);
}
public async createPrdResponse(pid: string, sid: string) {
return await this.coreWorker.createPrdResponse(pid, sid);
}
public async approveChange(pid: string, sid: string) {
return await this.coreWorker.approveChange(pid, sid);
}
public async rejectChange(pid: string, sid: string) {
return await this.coreWorker.rejectChange(pid, sid);
}
public async requestDataFromPeers(pid: string, sids: string[], roles: any) {
await this.coreWorker.requestDataFromPeers(pid, sids, roles);
}
public async resetDevice() { await this.coreWorker.resetDevice(); }
public async handleApiReturn(res: ApiReturn) { await this.coreWorker.handleApiReturn(res); }
public async saveDiffsToDb(diffs: UserDiff[]) { await this.coreWorker.saveDiffsToDb(diffs); }
public async handleCommitError(res: string) { await this.coreWorker.handleCommitError(res); }
public async resetDevice() {
await this.coreWorker.resetDevice();
}
public async handleApiReturn(res: ApiReturn) {
await this.coreWorker.handleApiReturn(res);
}
public async saveDiffsToDb(diffs: UserDiff[]) {
await this.coreWorker.saveDiffsToDb(diffs);
}
public async handleCommitError(res: string) {
await this.coreWorker.handleCommitError(res);
}
public async rolesContainsUs(roles: any) { return await this.coreWorker.rolesContainsUs(roles); }
public async getSecretForAddress(addr: string) { return await this.coreWorker.getSecretForAddress(addr); }
public async getAllDiffs() { return await this.coreWorker.getAllDiffs(); }
public async getDiffByValue(val: string) { return await this.coreWorker.getDiffByValue(val); }
public async getAllSecrets() { return await this.coreWorker.getAllSecrets(); }
public async rolesContainsUs(roles: any) {
return await this.coreWorker.rolesContainsUs(roles);
}
public async getSecretForAddress(addr: string) {
return await this.coreWorker.getSecretForAddress(addr);
}
public async getAllDiffs() {
return await this.coreWorker.getAllDiffs();
}
public async getDiffByValue(val: string) {
return await this.coreWorker.getDiffByValue(val);
}
public async getAllSecrets() {
return await this.coreWorker.getAllSecrets();
}
// ==========================================
// PROXY - STORAGE & DB
// ==========================================
public async saveBlobToDb(h: string, d: Blob) { await this.coreWorker.saveBlobToDb(h, d); }
public async getBlobFromDb(h: string) { return await this.coreWorker.getBlobFromDb(h); }
public async fetchValueFromStorage(h: string) { return await this.coreWorker.fetchValueFromStorage(h); }
public async saveDataToStorage(s: string[], h: string, d: Blob, ttl: number | null) { return await this.coreWorker.saveDataToStorage(s, h, d, ttl); }
public async saveBlobToDb(h: string, d: Blob) {
await this.coreWorker.saveBlobToDb(h, d);
}
public async getBlobFromDb(h: string) {
return await this.coreWorker.getBlobFromDb(h);
}
public async fetchValueFromStorage(h: string) {
return await this.coreWorker.fetchValueFromStorage(h);
}
public async saveDataToStorage(
s: string[],
h: string,
d: Blob,
ttl: number | null
) {
return await this.coreWorker.saveDataToStorage(s, h, d, ttl);
}
// ==========================================
// PROXY - HELPERS UI & DATA
// ==========================================
public async getProcessName(p: Process) { return await this.coreWorker.getProcessName(p); }
public async getPublicData(p: Process) { return await this.coreWorker.getPublicData(p); }
public async getNotifications() { return await this.coreWorker.getNotifications(); }
public async setNotifications(n: any[]) { await this.coreWorker.setNotifications(n); }
public async getProcessName(p: Process) {
return await this.coreWorker.getProcessName(p);
}
public async getPublicData(p: Process) {
return await this.coreWorker.getPublicData(p);
}
public async getNotifications() {
return await this.coreWorker.getNotifications();
}
public async setNotifications(n: any[]) {
await this.coreWorker.setNotifications(n);
}
public async parseCipher(msg: string) { await this.coreWorker.parseCipher(msg); }
public async parseNewTx(msg: string) { await this.coreWorker.parseNewTx(msg); }
public async updateMemberPublicName(pid: string, name: string) { return await this.coreWorker.updateMemberPublicName(pid, name); }
public async parseCipher(msg: string) {
await this.coreWorker.parseCipher(msg);
}
public async parseNewTx(msg: string) {
await this.coreWorker.parseNewTx(msg);
}
public async updateMemberPublicName(pid: string, name: string) {
return await this.coreWorker.updateMemberPublicName(pid, name);
}
// ==========================================
// PROXY - BACKUP & DECRYPT
// ==========================================
public async importJSON(b: BackUp) { await this.coreWorker.importJSON(b); }
public async restoreSecretsFromBackUp(s: SecretsStore) { await this.coreWorker.restoreSecretsFromBackUp(s); }
public async restoreSecretsFromDB() { await this.coreWorker.restoreSecretsFromDB(); }
public async createBackUp() { return await this.coreWorker.createBackUp(); }
public async importJSON(b: BackUp) {
await this.coreWorker.importJSON(b);
}
public async restoreSecretsFromBackUp(s: SecretsStore) {
await this.coreWorker.restoreSecretsFromBackUp(s);
}
public async restoreSecretsFromDB() {
await this.coreWorker.restoreSecretsFromDB();
}
public async createBackUp() {
return await this.coreWorker.createBackUp();
}
public async decryptAttribute(pid: string, s: ProcessState, attr: string) { return await this.coreWorker.decryptAttribute(pid, s, attr); }
public async decryptAttribute(pid: string, s: ProcessState, attr: string) {
return await this.coreWorker.decryptAttribute(pid, s, attr);
}
}