import { AbstractStreamingSyncImplementation, DiagnosticsEvent, LockOptions, LockType } from '@powersync/shared-internals'; import { Mutex } from '@powersync/shared-internals'; type MutexMap = { /** * Used to track the consumers of this Mutex. * It should be safe to dispose the Mutex if this is empty. */ tracking: Set; locks: { [Type in LockType]: Mutex; }; }; const GLOBAL_MUTEX_STORE: Map = new Map(); /** * Used to identify multiple instances of CapacitorStreamingSyncImplementation */ let _CAPACITOR_STREAMING_SYNC_SEQUENCE = 0; export class CapacitorStreamingSyncImplementation extends AbstractStreamingSyncImplementation { // A unique ID for tacking this specific instance of CapacitorStreamingSyncImplementation protected instanceId = _CAPACITOR_STREAMING_SYNC_SEQUENCE++; private diagnosticsChannel?: BroadcastChannel; /** * Broadcasts a core diagnostics event on a same-origin channel for diagnostics tooling in the * WebView to consume. */ protected override emitDiagnostics(event: DiagnosticsEvent): void { this.diagnosticsChannel ??= new BroadcastChannel('powersync-diagnostics-events'); this.diagnosticsChannel.postMessage(event); } async dispose(): Promise { await super.dispose(); this.diagnosticsChannel?.close(); this.diagnosticsChannel = undefined; // Clear up any global mutexes which aren't used anymore for (const mutexEntry of GLOBAL_MUTEX_STORE.entries()) { const [identifier, mutex] = mutexEntry; if (!mutex.tracking.has(this.instanceId)) { continue; } mutex.tracking.delete(this.instanceId); if (mutex.tracking.size == 0) { GLOBAL_MUTEX_STORE.delete(identifier); } } } async obtainLock(lockOptions: LockOptions): Promise { // If we don't have an identifier for some reason (should not happen), we use a shared Mutex const { identifier: baseIdentifier = 'DEFAULT' } = this.options; if (!GLOBAL_MUTEX_STORE.has(baseIdentifier)) { GLOBAL_MUTEX_STORE.set(baseIdentifier, { tracking: new Set([this.instanceId]), locks: { [LockType.CRUD]: new Mutex(), [LockType.SYNC]: new Mutex() } }); } const mutexRecord = GLOBAL_MUTEX_STORE.get(baseIdentifier)!; mutexRecord.tracking.add(this.instanceId); const mutex = mutexRecord.locks[lockOptions.type]; return mutex.runExclusive(async () => { return await lockOptions.callback(); }, lockOptions.signal); } }