Spaces:
Sleeping
Sleeping
File size: 5,329 Bytes
1305386 | 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 | /**
* 🏭 SERVICE LOADER
*
* Responsible for auto-discovering và loading tất cả services vào ServiceRegistry.
* Hỗ trợ comprehensive validation để đảm bảo services được implement đầy đủ.
*
* � PROJECT-BASED STRUCTURE:
* Từ version mới, services được tổ chức theo projectId:
* services/{projectId}/{messageType}/
*
* Ví dụ: services/testService/WebsiteContentIdeaRequest/
*
* �💡 Để thêm service mới:
* 1. Tạo service theo hướng dẫn trong docs/CREATE_NEW_SERVICE.md
* 2. Đặt trong thư mục services/{projectId}/{messageType}/
* 3. Import ServiceFactory của service đó
* 4. Thêm factory vào serviceFactories array
*
* @see docs/CREATE_NEW_SERVICE.md
*/
import { IServiceRegistry } from '../../interfaces/core/IServiceRegistry';
import { ServiceConfigManager } from '../../config/ServiceConfig';
import { ServiceValidator } from './ServiceValidator';
import { ServiceFactoryType } from '../../interfaces/core/IServiceFactory';
import { AggregationCounterAPI } from './AggregationCounterAPI';
import { IWorkerRegistry } from '../../interfaces/core/IWorkerRegistry';
// Default
import { ServiceFactory as DefaultServiceFactory } from '../services/Default/DefaultService/ServiceFactory';
// 📋 DANH SÁCH TẤT CẢ SERVICE FACTORIES
// Cấu trúc: services/{projectId}/{messageType}/ServiceFactory
// Thêm service factory mới vào đây khi tạo service mới
const candidateFactories: Array<{ messageType: string; factory: ServiceFactoryType }> = [
{ messageType: "DefaultService", factory: DefaultServiceFactory as ServiceFactoryType },
];
export class ServiceLoader {
/**
* 🚀 Load tất cả services với validation
*
* Process:
* 1. Print service configuration summary
* 2. Load services từ factories
* 3. Register vào ServiceRegistry
* 4. Comprehensive validation
* 5. Exit nếu có lỗi (strict mode)
*/
static loadAllServices(
serviceRegistry: IServiceRegistry,
aggregationCounterAPI: AggregationCounterAPI,
workerRegistry: IWorkerRegistry,
options?: { enabledMessageTypes?: string[] }
): void {
console.log("🔄 Loading all services...");
// Validate centralized service configs first (fail-fast)
const cfgValidation = ServiceConfigManager.validateAllConfigs();
if (!cfgValidation.valid) {
console.error("🛑 SERVICE CONFIG VALIDATION ERRORS:");
cfgValidation.errors.forEach(err => console.error(` - ${err}`));
console.error("Fix SERVICE_CONFIGS in src/config/ServiceConfig.ts and restart.");
process.exit(1);
}
// Print service configs để dev review
ServiceConfigManager.printServicesSummary();
const enabledMessageTypes = options?.enabledMessageTypes && options.enabledMessageTypes.length > 0
? new Set(options.enabledMessageTypes)
: new Set(candidateFactories.map(c => c.messageType));
if (options?.enabledMessageTypes && options.enabledMessageTypes.length > 0) {
console.log("🔧 ServiceLoader: enabled messageTypes from worker profile:", options.enabledMessageTypes.join(', '));
}
const serviceFactories: ServiceFactoryType[] = candidateFactories
.filter(c => enabledMessageTypes.has(c.messageType))
.map(c => c.factory)
.filter(f => f && typeof (f as any).createServiceConfig === 'function');
const loadedConfigs: any[] = [];
// Load từng service factory
serviceFactories.forEach(factory => {
try {
// Tất cả service factories đều nhận dependencies object
const config = factory.createServiceConfig({
aggregationCounterAPI,
workerRegistry
});
serviceRegistry.registerService(config);
loadedConfigs.push(config);
} catch (error) {
console.error(`❌ Failed to load service from factory:`, error);
}
});
console.log(`✅ Loaded ${serviceRegistry.getAllServices().length} services`);
// 🔍 COMPREHENSIVE VALIDATION
// Kiểm tra tất cả services đã được implement đầy đủ chưa
console.log("\n🔍 Starting service validation...");
const validator = new ServiceValidator();
const validationReport = validator.validateAllServices(loadedConfigs);
// Strict mode: Exit nếu có service invalid
if (validationReport.invalidServices > 0) {
const shouldContinue = process.env.IGNORE_SERVICE_VALIDATION === 'true';
if (!shouldContinue) {
console.error("🛑 STARTUP ABORTED: Invalid services detected!");
console.error("Fix the errors above or set IGNORE_SERVICE_VALIDATION=true to bypass (not recommended)");
process.exit(1);
} else {
console.warn("⚠️ WARNING: Continuing despite invalid services (IGNORE_SERVICE_VALIDATION=true)");
}
}
}
} |