Spaces:
Sleeping

File size: 5,888 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
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
export interface ServiceTypeConfig {
    messageType: string;   // Tên service (phải unique)
    min: number;           // Số lượng tối thiểu instance có thể chạy đồng thời
    max: number;           // Số lượng tối đa instance có thể chạy đồng thời  
    priority: number;      // Mức ưu tiên (1 = cao nhất, 2, 3, ...)
    description?: string;  // Mô tả service làm gì (dùng cho documentation)
}

/**

 * 📊 CẤU HÌNH TOÀN BỘ SERVICES

 * 

 * Thay đổi ở đây sẽ ảnh hưởng đến:

 * - Worker registration với Noah API (typeConfig)

 * - Resource allocation priorities và capacity

 * - Message processing workflow

 * 

/**

 * 📊 CẤU HÌNH TOÀN BỘ SERVICES (LEGACY / DEFAULT)

 *

 * 🔹 Từ phiên bản dùng worker profiles (worker/*.json), cấu hình **thật** cho

 * từng worker (min/max/priority) được lấy từ JSON, và được apply qua

 * `ServiceConfigManager.setRuntimeOverrides()`.

 *

 * 🔹 `SERVICE_CONFIGS` giờ chỉ giữ vai trò:

 *    - Ví dụ mặc định / tài liệu hoá (có thể để trống hoàn toàn).

 *    - Fallback nếu KHÔNG load worker profile.

 *

 * 👉 Bình thường bạn **không cần chỉnh file này** nữa. Hãy cấu hình services

 *    trong các file JSON ở thư mục `worker/`.

 */
export const SERVICE_CONFIGS: Record<string, ServiceTypeConfig> = {
    // Ví dụ (có thể xoá hết hoặc giữ lại làm reference):
    // Template: {
    //     messageType: "Template",
    //     min: 1,
    //     max: 1,
    //     priority: 0,
    //     description: "template service"
    // },
};
export class ServiceConfigManager {
    /**

     * Runtime overrides được load từ worker profile (worker/*.json).

     * Nếu có override cho một messageType, config đó sẽ được dùng thay vì SERVICE_CONFIGS.

     */
    private static runtimeOverrides: Record<string, ServiceTypeConfig> = {};
    
    /**

     * Lấy config của một service theo messageType

     */
    static getServiceConfig(messageType: string): ServiceTypeConfig | undefined {
        // Ưu tiên config runtime từ worker profile nếu có
        if (this.runtimeOverrides[messageType]) {
            return this.runtimeOverrides[messageType];
        }
        // Fallback về catalog toàn cục
        return SERVICE_CONFIGS[messageType];
    }

    /**

     * Lấy tất cả service configs dưới dạng array (dùng cho worker registration)

     */
    static getAllTypeConfigs(): ServiceTypeConfig[] {
        // Nếu đã có overrides từ worker profile thì ưu tiên dùng các config này
        const overrideKeys = Object.keys(this.runtimeOverrides);
        if (overrideKeys.length > 0) {
            return Object.values(this.runtimeOverrides);
        }
        return Object.values(SERVICE_CONFIGS);
    }

    /**

     * Lấy danh sách services được sắp xếp theo priority (ưu tiên cao → thấp)

     */
    static getServicesByPriority(): ServiceTypeConfig[] {
        const sourceConfigs = this.getAllTypeConfigs();
        return sourceConfigs.sort((a, b) => a.priority - b.priority);
    }

    /**

     * Validate service config có hợp lệ không

     */
    static validateServiceConfig(config: ServiceTypeConfig): boolean {
        return !!(
            config.messageType &&
            config.min >= 1 &&
            config.max >= config.min &&
            config.priority >= 0
        );
    }

    /**

     * Validate all SERVICE_CONFIGS and return an object with validity + errors

     */
    static validateAllConfigs(): { valid: boolean; errors: string[] } {
        const errors: string[] = [];

        Object.entries(SERVICE_CONFIGS).forEach(([key, cfg]) => {
            if (!cfg) {
                errors.push(`Missing config for key=${key}`);
                return;
            }

            if (key !== cfg.messageType) {
                // Allow differences where multiple projects share the same messageType by checking for suffixes used above
                if (key !== `${cfg.messageType}`) {
                    errors.push(`Key mismatch: map key='${key}' but config.messageType='${cfg.messageType}'`);
                }
            }

            if (typeof cfg.min !== 'number' || typeof cfg.max !== 'number' || typeof cfg.priority !== 'number') {
                errors.push(`Invalid numeric values for ${key}`);
            } else if (cfg.min < 1) {
                errors.push(`${key}: min must be >= 1`);
            } else if (cfg.max < cfg.min) {
                errors.push(`${key}: max must be >= min`);
            }
        });

        return { valid: errors.length === 0, errors };
    }

    /**

     * In ra summary của tất cả services (dùng cho debugging & monitoring)

     */
    static printServicesSummary(): void {
        console.log("📋 SNAKE SERVICE CONFIGURATION SUMMARY:");
        console.log("=".repeat(60));
        
        const sortedServices = ServiceConfigManager.getServicesByPriority();
        
        sortedServices.forEach((config, index) => {
            console.log(`${index + 1}. ${config.messageType}`);
            console.log(`   Priority: ${config.priority} | Capacity: ${config.min}-${config.max} instances`);
            console.log(`   Description: ${config.description || 'No description'}`);
            console.log();
        });
    }

    /**

     * Áp dụng toàn bộ runtime overrides cho worker hiện tại.

     * Thường được gọi sau khi load worker profile từ thư mục `worker/`.

     */
    static setRuntimeOverrides(overrides: Record<string, ServiceTypeConfig>): void {
        this.runtimeOverrides = { ...overrides };
    }
}