All files / src/lib/services project-health-service.ts

95.65% Statements 44/46
100% Branches 8/8
88.24% Functions 15/17
95.35% Lines 41/43

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                            61x     61x                                                     148x 148x 148x 148x 148x 148x       148x               12x 10x     10x       10x 10x                             5x 4x                         24x 24x 4x 4x 20x           24x 52x 52x     52x               13x       13x       20x         51x 20x 20x     20x                       20x 20x   20x 20x     20x       4x   4x   17x 17x                        
import { IUnleashStores } from '../types/stores';
import { IUnleashConfig } from '../types/option';
import { Logger } from '../logger';
import {
    FeatureToggle,
    IFeatureOverview,
    IProject,
    IProjectHealthReport,
    IProjectOverview,
} from '../types/model';
import { IFeatureToggleStore } from '../types/stores/feature-toggle-store';
import { IFeatureTypeStore } from '../types/stores/feature-type-store';
import { IProjectStore } from '../types/stores/project-store';
import FeatureToggleService from './feature-toggle-service';
import { hoursToMilliseconds } from 'date-fns';
import Timer = NodeJS.Timer;
 
export default class ProjectHealthService {
    private logger: Logger;
 
    private projectStore: IProjectStore;
 
    private featureTypeStore: IFeatureTypeStore;
 
    private featureToggleStore: IFeatureToggleStore;
 
    private featureTypes: Map<string, number>;
 
    private healthRatingTimer: Timer;
 
    private featureToggleService: FeatureToggleService;
 
    constructor(
        {
            projectStore,
            featureTypeStore,
            featureToggleStore,
        }: Pick<
            IUnleashStores,
            'projectStore' | 'featureTypeStore' | 'featureToggleStore'
        >,
        { getLogger }: Pick<IUnleashConfig, 'getLogger'>,
        featureToggleService: FeatureToggleService,
    ) {
        this.logger = getLogger('services/project-health-service.ts');
        this.projectStore = projectStore;
        this.featureTypeStore = featureTypeStore;
        this.featureToggleStore = featureToggleStore;
        this.featureTypes = new Map();
        this.healthRatingTimer = setInterval(
            () => this.setHealthRating(),
            hoursToMilliseconds(1),
        ).unref();
        this.featureToggleService = featureToggleService;
    }
 
    // TODO: duplicate from project-service.
    async getProjectOverview(
        projectId: string,
        archived: boolean = false,
    ): Promise<IProjectOverview> {
        const project = await this.projectStore.get(projectId);
        const environments = await this.projectStore.getEnvironmentsForProject(
            projectId,
        );
        const features = await this.featureToggleService.getFeatureOverview(
            projectId,
            archived,
        );
        const members = await this.projectStore.getMembers(projectId);
        return {
            name: project.name,
            description: project.description,
            health: project.health,
            updatedAt: project.updatedAt,
            environments,
            features,
            members,
            version: 1,
        };
    }
 
    async getProjectHealthReport(
        projectId: string,
    ): Promise<IProjectHealthReport> {
        const overview = await this.getProjectOverview(projectId, false);
        return {
            ...overview,
            potentiallyStaleCount: await this.potentiallyStaleCount(
                overview.features,
            ),
            activeCount: this.activeCount(overview.features),
            staleCount: this.staleCount(overview.features),
        };
    }
 
    private async potentiallyStaleCount(
        features: Pick<FeatureToggle, 'createdAt' | 'stale' | 'type'>[],
    ): Promise<number> {
        const today = new Date().valueOf();
        if (this.featureTypes.size === 0) {
            const types = await this.featureTypeStore.getAll();
            types.forEach((type) => {
                this.featureTypes.set(
                    type.name.toLowerCase(),
                    type.lifetimeDays,
                );
            });
        }
        return features.filter((feature) => {
            const diff = today - feature.createdAt.valueOf();
            const featureTypeExpectedLifetime = this.featureTypes.get(
                feature.type,
            );
            return (
                !feature.stale &&
                diff >= featureTypeExpectedLifetime * hoursToMilliseconds(24)
            );
        }).length;
    }
 
    private activeCount(features: IFeatureOverview[]): number {
        return features.filter((f) => !f.stale).length;
    }
 
    private staleCount(features: IFeatureOverview[]): number {
        return features.filter((f) => f.stale).length;
    }
 
    async calculateHealthRating(project: IProject): Promise<number> {
        const toggles = await this.featureToggleStore.getAll({
            project: project.id,
            archived: false,
        });
 
        const activeToggles = toggles.filter((feature) => !feature.stale);
        const staleToggles = toggles.length - activeToggles.length;
        const potentiallyStaleToggles = await this.potentiallyStaleCount(
            activeToggles,
        );
        return this.getHealthRating(
            toggles.length,
            staleToggles,
            potentiallyStaleToggles,
        );
    }
 
    private getHealthRating(
        toggleCount: number,
        staleToggleCount: number,
        potentiallyStaleCount: number,
    ): number {
        const startPercentage = 100;
        const stalePercentage = (staleToggleCount / toggleCount) * 100 || 0;
        const potentiallyStalePercentage =
            (potentiallyStaleCount / toggleCount) * 100 || 0;
        const rating = Math.round(
            startPercentage - stalePercentage - potentiallyStalePercentage,
        );
        return rating;
    }
 
    async setHealthRating(): Promise<void> {
        const projects = await this.projectStore.getAll();
 
        await Promise.all(
            projects.map(async (project) => {
                const newHealth = await this.calculateHealthRating(project);
                await this.projectStore.updateHealth({
                    id: project.id,
                    health: newHealth,
                });
            }),
        );
    }
 
    destroy(): void {
        clearInterval(this.healthRatingTimer);
    }
}