All files / app/services/app-update app-update.service.ts

100% Statements 52/52
91.3% Branches 21/23
100% Functions 13/13
100% Lines 51/51

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 1143x 3x 3x 3x 3x 3x   3x   3x     3x 16x 16x 16x 16x 16x 16x   16x 16x   16x 16x                 16x     2x     2x 1x       16x     7x 7x         1x             7x 1x   6x 6x       2x 2x       3x 1x   2x 2x       8x 1x 1x     7x   7x     1x   2x 2x           3x   3x 3x   3x     1x 1x        
import { isChunkLoadError } from './is-chunk-load-error';
import { VersionCheckService } from './version-check.service';
import { DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NavigationError, Router } from '@angular/router';
import { LoggerService, NotificationService, WINDOW } from '@drevo-web/core';
import { VersionInfo } from '@drevo-web/shared';
import { filter, Subscription, timer } from 'rxjs';
 
const REMIND_AFTER_MS = 60 * 60 * 1000;
 
@Injectable({ providedIn: 'root' })
export class AppUpdateService {
    private readonly window = inject(WINDOW);
    private readonly router = inject(Router);
    private readonly logger = inject(LoggerService).withContext('AppUpdateService');
    private readonly versionCheck = inject(VersionCheckService);
    private readonly notification = inject(NotificationService);
    private readonly destroyRef = inject(DestroyRef);
 
    private readonly _chunkLoadFailed = signal(false);
    readonly chunkLoadFailed = this._chunkLoadFailed.asReadonly();
 
    private readonly _newVersionAvailable = signal<VersionInfo | undefined>(undefined);
    readonly newVersionAvailable = this._newVersionAvailable.asReadonly();
 
    private lastDismissedAt: number | undefined;
    private reminderTimer?: Subscription;
 
    constructor() {
        // Covers router navigations: in zoneless mode imperative router.navigate()
        // rejections may bypass the global ErrorHandler, so we listen to NavigationError
        // directly. ChunkErrorHandler complements this for non-router dynamic imports.
        this.router.events
            .pipe(
                takeUntilDestroyed(),
                filter((e): e is NavigationError => e instanceof NavigationError),
            )
            .subscribe(event => {
                if (isChunkLoadError(event.error)) {
                    this.notifyChunkLoadFailure(event.error, { url: event.url, source: 'router' });
                }
            });
 
        this.versionCheck.newVersionAvailable$
            .pipe(takeUntilDestroyed())
            .subscribe(info => {
                this._newVersionAvailable.set(info);
                this.showUpdateSnackbar(info);
            });
    }
 
    startVersionCheck(): void {
        this.versionCheck.startPolling();
    }
 
    notifyChunkLoadFailure(
        error: unknown,
        context: { readonly url: string; readonly source: 'router' | 'error-handler' },
    ): void {
        if (this._chunkLoadFailed()) {
            return;
        }
        this._chunkLoadFailed.set(true);
        this.logger.error('Chunk load failure — reload prompt shown', { error, ...context });
    }
 
    reload(reason: 'chunk-load-failure' | 'version-update' = 'chunk-load-failure'): void {
        this.logger.info('User clicked reload', { reason });
        this.window?.location.reload();
    }
 
    dismiss(): void {
        if (!this._chunkLoadFailed()) {
            return;
        }
        this._chunkLoadFailed.set(false);
        this.logger.info('User dismissed reload prompt; will reappear on next chunk load failure');
    }
 
    private showUpdateSnackbar(info: VersionInfo): void {
        if (this.lastDismissedAt && Date.now() - this.lastDismissedAt < REMIND_AFTER_MS) {
            this.scheduleReminder(info);
            return;
        }
 
        this.logger.info('Showing update notification', { version: info.version });
 
        this.notification.showPersistent({
            message: `Доступна новая версия ${info.version}`,
            actionLabel: 'Обновить',
            onAction: () => this.reload('version-update'),
            onDismiss: () => {
                this.lastDismissedAt = Date.now();
                this.scheduleReminder(info);
            },
        });
    }
 
    private scheduleReminder(info: VersionInfo): void {
        this.reminderTimer?.unsubscribe();
 
        const elapsed = Date.now() - (this.lastDismissedAt ?? 0);
        const remaining = Math.max(0, REMIND_AFTER_MS - elapsed);
 
        this.reminderTimer = timer(remaining)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe(() => {
                this.lastDismissedAt = undefined;
                this.showUpdateSnackbar(info);
            });
    }
}