All files / src/infrastructure/database database-integrity.service.ts

0% Statements 0/67
0% Branches 0/37
0% Functions 0/6
0% Lines 0/63

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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { Injectable, Logger } from '@nestjs/common';
import { Connection } from 'mongoose';
import { InjectConnection } from '@nestjs/mongoose';
 
interface CollectionAuditResult {
  collection: string;
  documentCount: number;
  indexCount: number;
  avgDocSize: number;
  hasTenantId: boolean;
  hasTimestamps: boolean;
  indexes: string[];
  warnings: string[];
}
 
interface IntegrityReport {
  status: 'pass' | 'fail';
  totalCollections: number;
  totalDocuments: number;
  totalIndexes: number;
  duplicateCollectionWarnings: string[];
  orphanReferenceWarnings: string[];
  missingIndexWarnings: string[];
  collectionResults: CollectionAuditResult[];
  seedConsistency: { success: boolean; warnings: string[] };
  executedAt: string;
}
 
@Injectable()
export class DatabaseIntegrityService {
  private readonly logger = new Logger(DatabaseIntegrityService.name);
 
  constructor(@InjectConnection() private readonly connection: Connection) {}
 
  async runFullIntegrityCheck(): Promise<IntegrityReport> {
    this.logger.log('Starting full database integrity validation...');
 
    const collectionResults: CollectionAuditResult[] = [];
    const duplicateCollectionWarnings: string[] = [];
    const orphanReferenceWarnings: string[] = [];
    const missingIndexWarnings: string[] = [];
 
    let totalDocuments = 0;
    let totalIndexes = 0;
 
    // Get all collection names from MongoDB
    const db = this.connection.db;
    if (!db) {
      return {
        status: 'fail',
        totalCollections: 0,
        totalDocuments: 0,
        totalIndexes: 0,
        duplicateCollectionWarnings: ['Database connection not available'],
        orphanReferenceWarnings: [],
        missingIndexWarnings: [],
        collectionResults: [],
        seedConsistency: {
          success: false,
          warnings: ['Cannot verify - no DB connection'],
        },
        executedAt: new Date().toISOString(),
      };
    }
 
    const collections = await db.listCollections().toArray();
 
    for (const collInfo of collections) {
      const collName = collInfo.name;
      if (collName.startsWith('system.')) continue;
 
      try {
        const coll = db.collection(collName);
        const docCount = await coll.countDocuments();
        const indexes = await coll.indexes();
        const warnings: string[] = [];
 
        totalDocuments += docCount;
        totalIndexes += indexes.length;
 
        // Check for tenantId index (multi-tenant isolation)
        const hasTenantIdIndex = indexes.some(
          (idx) => idx.key && 'tenantId' in idx.key,
        );
 
        // Check for timestamps
        let hasTimestamps = false;
        if (docCount > 0) {
          const sample = await coll.findOne();
          hasTimestamps = !!(
            sample &&
            ('createdAt' in sample || 'updatedAt' in sample)
          );
        }
 
        // Validate index effectiveness
        const indexNames = indexes.map((i) => i.name || 'unnamed');
 
        // Check for missing tenantId index on tenant-scoped collections
        if (docCount > 0 && !hasTenantIdIndex) {
          const sample = await coll.findOne();
          if (sample && 'tenantId' in sample) {
            missingIndexWarnings.push(
              `Collection '${collName}' has tenantId field but no index on it`,
            );
            warnings.push('Missing tenantId index');
          }
        }
 
        // Estimate average document size
        let avgDocSize = 0;
        if (docCount > 0) {
          const stats = await db
            .command({ collStats: collName })
            .catch(() => null);
          if (stats) {
            avgDocSize = Math.round((stats.size || 0) / Math.max(docCount, 1));
          }
        }
 
        collectionResults.push({
          collection: collName,
          documentCount: docCount,
          indexCount: indexes.length,
          avgDocSize,
          hasTenantId: hasTenantIdIndex,
          hasTimestamps,
          indexes: indexNames,
          warnings,
        });
      } catch (err: any) {
        this.logger.warn(
          `Error auditing collection ${collName}: ${err.message}`,
        );
      }
    }
 
    // Known duplicate collection mappings from static analysis
    const KNOWN_DUPLICATES = [
      {
        collection: 'employees',
        sources: [
          'domains/hr/employee',
          'infrastructure/database/business-stubs',
        ],
      },
      {
        collection: 'contacts',
        sources: ['domains/crm', 'infrastructure/database/business-stubs'],
      },
      {
        collection: 'projects',
        sources: ['domains/projects', 'infrastructure/database/business-stubs'],
      },
      {
        collection: 'subscriptions',
        sources: ['platform/auth', 'platform/subscriptions'],
      },
      {
        collection: 'onboarding_checklist_items',
        sources: ['domains/crm', 'platform/onboarding'],
      },
    ];
 
    for (const dup of KNOWN_DUPLICATES) {
      duplicateCollectionWarnings.push(
        `Collection '${dup.collection}' is mapped by multiple schemas: ${dup.sources.join(', ')}`,
      );
    }
 
    // Seed consistency check
    const seedConsistency = await this.validateSeedConsistency(db);
 
    const status =
      missingIndexWarnings.length === 0 &&
      duplicateCollectionWarnings.length <= 5
        ? 'pass'
        : 'fail';
 
    this.logger.log(`Database integrity check completed: ${status}`);
 
    return {
      status,
      totalCollections: collections.length,
      totalDocuments,
      totalIndexes,
      duplicateCollectionWarnings,
      orphanReferenceWarnings,
      missingIndexWarnings,
      collectionResults,
      seedConsistency,
      executedAt: new Date().toISOString(),
    };
  }
 
  private async validateSeedConsistency(
    db: any,
  ): Promise<{ success: boolean; warnings: string[] }> {
    const warnings: string[] = [];
 
    const seedCollections = [
      { name: 'mdm_countries', minCount: 5 },
      { name: 'mdm_currencies', minCount: 5 },
      { name: 'mdm_states', minCount: 1 },
      { name: 'mdm_cities', minCount: 1 },
      { name: 'mdm_languages', minCount: 1 },
      { name: 'mdm_timezones', minCount: 1 },
      { name: 'mdm_industries', minCount: 1 },
      { name: 'mdm_tax_masters', minCount: 1 },
      { name: 'mdm_document_types', minCount: 1 },
      { name: 'mdm_number_series', minCount: 1 },
    ];
 
    for (const seed of seedCollections) {
      try {
        const count = await db.collection(seed.name).countDocuments();
        if (count < seed.minCount) {
          warnings.push(
            `Seed collection '${seed.name}' has ${count} documents (expected >= ${seed.minCount})`,
          );
        }
      } catch {
        warnings.push(`Seed collection '${seed.name}' does not exist`);
      }
    }
 
    return { success: warnings.length === 0, warnings };
  }
}