All files / logging/providers indexed-db-log.provider.ts

39.06% Statements 25/64
52.5% Branches 21/40
57.14% Functions 8/14
39.06% Lines 25/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1961x   1x     1x     1x     1x     1x                     1x 12x     12x             12x 12x   12x           9x               2x 2x                                     1x 1x                                                                                   2x 2x                       1x 1x                               1x 1x                       1x                                                                 1x      
import { LogDatabase } from '../log-database';
import { LogEntry, LogStorageProvider, GetLogsOptions } from '../log-provider.interface';
import { assertIsDefined } from '@drevo-web/shared';
 
/** Default max storage size in bytes (10MB) */
const DEFAULT_MAX_SIZE = 10 * 1024 * 1024;
 
/** Batch size - number of entries to buffer before writing */
const BATCH_SIZE = 10;
 
/** Batch timeout - max time to wait before flushing buffer (ms) */
const BATCH_TIMEOUT_MS = 1000;
 
/** Percentage of logs to delete when pruning (20%) */
const PRUNE_PERCENTAGE = 0.2;
 
/**
 * IndexedDB log provider
 * Persists logs to browser's IndexedDB using Dexie.js
 *
 * Features:
 * - Batched writes for better performance
 * - Automatic pruning when storage limit is reached
 * - SSR-safe (disabled on server)
 */
export class IndexedDBLogProvider implements LogStorageProvider {
    readonly name = 'indexeddb';
 
    private database: LogDatabase | undefined;
    private buffer: LogEntry[] = [];
    private flushTimer: ReturnType<typeof setTimeout> | undefined;
    private flushPromise: Promise<void> | undefined;
    private readonly maxSize: number;
    private readonly isBrowser: boolean;
 
    constructor(options?: { maxSize?: number }) {
        this.maxSize = options?.maxSize ?? DEFAULT_MAX_SIZE;
        this.isBrowser = typeof window !== 'undefined' && typeof indexedDB !== 'undefined';
 
        Iif (this.isBrowser) {
            this.database = new LogDatabase();
        }
    }
 
    get isAvailable(): boolean {
        return this.isBrowser && this.database !== undefined;
    }
 
    /**
     * Add log entry to buffer
     * Will be flushed to IndexedDB when buffer is full or timeout expires
     */
    log(entry: LogEntry): void {
        Eif (!this.isAvailable) {
            return;
        }
 
        this.buffer.push(entry);
 
        // Flush if buffer is full
        if (this.buffer.length >= BATCH_SIZE) {
            void this.flush();
        } else {
            // Start timer if not already running
            this.startFlushTimer();
        }
    }
 
    /**
     * Flush buffered logs to IndexedDB
     * Serializes concurrent flush calls to prevent ordering issues on failure
     */
    async flush(): Promise<void> {
        Eif (!this.isAvailable || this.buffer.length === 0) {
            return;
        }
 
        // If flush is already in progress, wait for it
        if (this.flushPromise) {
            return this.flushPromise;
        }
 
        this.flushPromise = this.doFlush();
        try {
            await this.flushPromise;
        } finally {
            this.flushPromise = undefined;
        }
    }
 
    private async doFlush(): Promise<void> {
        // Clear timer
        this.clearFlushTimer();
 
        // Take current buffer and reset
        const entries = [...this.buffer];
        this.buffer = [];
 
        assertIsDefined(this.database, 'IndexedDBLogProvider flush: database is undefined');
 
        try {
            await this.database.addLogs(entries);
 
            // Check if pruning is needed
            await this.pruneIfNeeded();
        } catch (error) {
            // Re-add entries to buffer on failure
            this.buffer.unshift(...entries);
            console.error('IndexedDBLogProvider: Failed to flush logs', error);
        }
    }
 
    /**
     * Get logs from IndexedDB
     */
    async getLogs(options?: GetLogsOptions): Promise<LogEntry[]> {
        Eif (!this.isAvailable) {
            return [];
        }
 
        assertIsDefined(this.database, 'IndexedDBLogProvider getLogs: database is undefined');
 
        return this.database.getLogs(options);
    }
 
    /**
     * Clear all logs from IndexedDB
     */
    async clearLogs(): Promise<void> {
        Eif (!this.isAvailable) {
            return;
        }
 
        // Also clear buffer
        this.buffer = [];
        this.clearFlushTimer();
 
        assertIsDefined(this.database, 'IndexedDBLogProvider clearLogs: database is undefined');
 
        await this.database.clearLogs();
    }
 
    /**
     * Get approximate storage size in bytes
     */
    async getStorageSize(): Promise<number> {
        Eif (!this.isAvailable) {
            return 0;
        }
 
        assertIsDefined(this.database, 'IndexedDBLogProvider getStorageSize: database is undefined');
 
        return this.database.getStorageSize();
    }
 
    /**
     * Get the captured user agent string
     */
    getUserAgent(): string | undefined {
        return this.database?.getUserAgent();
    }
 
    private startFlushTimer(): void {
        if (this.flushTimer === undefined) {
            this.flushTimer = setTimeout(() => {
                void this.flush();
            }, BATCH_TIMEOUT_MS);
        }
    }
 
    private clearFlushTimer(): void {
        if (this.flushTimer !== undefined) {
            clearTimeout(this.flushTimer);
            this.flushTimer = undefined;
        }
    }
 
    private async pruneIfNeeded(): Promise<void> {
        const size = await this.getStorageSize();
 
        assertIsDefined(this.database, 'IndexedDBLogProvider pruneIfNeeded: database is undefined');
 
        if (size > this.maxSize) {
            await this.database.deleteOldestLogs(PRUNE_PERCENTAGE);
        }
    }
}
 
/**
 * Factory function to create IndexedDB provider
 * Use this in provideLogProviders()
 */
export function createIndexedDBLogProvider(options?: { maxSize?: number }): IndexedDBLogProvider {
    return new IndexedDBLogProvider(options);
}