All files / src/platform/integrations/services integration-registry.service.ts

0% Statements 0/48
0% Branches 0/30
0% Functions 0/11
0% Lines 0/46

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                                                                                                                                                                                                                                                                                                                                                                                       
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  IntegrationDefinition,
  TenantIntegration,
  IntegrationLog,
  IntegrationHealthCheck,
} from '../schemas/integration.schema';
 
type ProviderInstance = { testConnection(): Promise<boolean> };
 
@Injectable()
export class IntegrationRegistryService {
  private readonly logger = new Logger(IntegrationRegistryService.name);
  private readonly providers = new Map<string, ProviderInstance>();
  private readonly definitions = new Map<
    string,
    { category: string; name: string; description?: string }
  >();
 
  constructor(
    @InjectModel(IntegrationDefinition.name)
    private readonly definitionModel: Model<IntegrationDefinition>,
    @InjectModel(TenantIntegration.name)
    private readonly tenantIntegrationModel: Model<TenantIntegration>,
    @InjectModel(IntegrationLog.name)
    private readonly logModel: Model<IntegrationLog>,
    @InjectModel(IntegrationHealthCheck.name)
    private readonly healthCheckModel: Model<IntegrationHealthCheck>,
  ) {}
 
  /**
   * Register a system-level provider instance.
   */
  registerProvider(
    key: string,
    instance: ProviderInstance,
    meta?: { category?: string; name?: string },
  ): void {
    this.providers.set(key, instance);
    if (meta) {
      this.definitions.set(key, {
        category: meta.category ?? 'custom',
        name: meta.name ?? key,
      });
    }
    this.logger.log(`Integration provider registered: ${key}`);
  }
 
  getProvider<T extends ProviderInstance>(key: string): T {
    const provider = this.providers.get(key);
    if (!provider)
      throw new NotFoundException(
        `Integration provider '${key}' is not registered`,
      );
    return provider as T;
  }
 
  listProviders(): string[] {
    return Array.from(this.providers.keys());
  }
 
  async getActiveTenantIntegrations(
    tenantId: string,
  ): Promise<TenantIntegration[]> {
    return this.tenantIntegrationModel
      .find({ tenantId, status: 'connected' })
      .exec();
  }
 
  async getTenantIntegration(
    tenantId: string,
    key: string,
  ): Promise<TenantIntegration | null> {
    return this.tenantIntegrationModel
      .findOne({ tenantId, integrationKey: key })
      .exec();
  }
 
  async connect(
    tenantId: string,
    key: string,
    settings: any,
    connectedBy?: string,
  ): Promise<TenantIntegration> {
    const existing = await this.tenantIntegrationModel
      .findOne({ tenantId, integrationKey: key })
      .exec();
    const doc =
      existing ??
      new this.tenantIntegrationModel({ tenantId, integrationKey: key });
    doc.status = 'connected';
    doc.settings = settings;
    doc.connectedAt = new Date();
    doc.connectedBy = connectedBy as any;
    await doc.save();
 
    await this.writeLog(
      tenantId,
      key,
      'connect',
      'success',
      'Integration connected',
    );
    return doc;
  }
 
  async disconnect(tenantId: string, key: string): Promise<void> {
    await this.tenantIntegrationModel
      .findOneAndUpdate(
        { tenantId, integrationKey: key },
        { status: 'disconnected', disconnectedAt: new Date() },
      )
      .exec();
    await this.writeLog(
      tenantId,
      key,
      'disconnect',
      'success',
      'Integration disconnected',
    );
  }
 
  async testConnection(
    tenantId: string,
    key: string,
  ): Promise<{ ok: boolean; latencyMs: number }> {
    const start = Date.now();
    let ok = false;
 
    try {
      const provider = this.getProvider(key);
      ok = await provider.testConnection();
    } catch (err) {
      this.logger.warn(`Integration test failed for ${key}: ${err.message}`);
    }
 
    const latencyMs = Date.now() - start;
    await this.healthCheckModel.create({
      tenantId,
      integrationKey: key,
      status: ok ? 'ok' : 'failed',
      latencyMs,
      checkedAt: new Date(),
    });
 
    await this.tenantIntegrationModel
      .findOneAndUpdate(
        { tenantId, integrationKey: key },
        {
          lastHealthCheckAt: new Date(),
          lastHealthCheckResult: ok ? 'ok' : 'failed',
        },
      )
      .exec();
 
    return { ok, latencyMs };
  }
 
  async getHealthLogs(
    tenantId: string,
    key: string,
  ): Promise<IntegrationLog[]> {
    return this.logModel
      .find({ tenantId, integrationKey: key })
      .sort({ createdAt: -1 })
      .limit(50)
      .exec();
  }
 
  private async writeLog(
    tenantId: string,
    key: string,
    action: string,
    level: 'success' | 'failure' | 'warning',
    message: string,
  ): Promise<void> {
    await this.logModel.create({
      tenantId,
      integrationKey: key,
      action,
      level,
      message,
    });
  }
}