# All files / common provider-registry.ts

97.67% Statements 126/129
93.33% Branches 56/60
100% Functions 19/19
97.67% Lines 126/129

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
    2201x

    1x
    28x

    28x
    57x
    57x

    57x
    57x
    57x
    57x
    57x
    57x
    57x
    57x
    57x
    57x
    57x

    57x
    1x
    57x
    56x
    56x
    57x

    28x
    2x
    2x
    1x
    1x
    1x
    1x
    2x

    28x
    26x
    26x

    28x
    1x
    1x

    28x
    2x
    2x

    28x
    8x
    8x

    28x
    1x
    1x

    28x
    2x
    2x

    28x
    2x
    2x

    28x
    6x
    6x
    6x
    6x
    6x
    6x

    6x
    1x
    1x
    6x

    28x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    28x
    4x
    4x

    3x
    4x
    1x
    1x
    2x
    4x

    28x
    1x
    1x

    28x
    2x
    2x
    4x

    4x
    4x
    3x
    4x
    1x
    1x
    4x
    1x
    1x
    4x
    2x
    2x

    28x
    2x
    2x

    28x
    1x
    1x

    28x
    2x
    6x
    6x
    6x
    2x
    2x

    28x

    1x
    1x
    2x
    2x
    2x
    2x
    2x
    2x
    1x
    1x
    28x/**
     * 通用 Provider 注册表
     *
     * 统一管理 TTS 和 LLM 供应商的生命周期：
     * - 注册/注销
     * - 按名称/供应商查找
     * - 状态查询（可用/禁用/熔断/额度耗尽）
     * - 轮转调度（平等，无优先级）
     *
     * 每个 Provider 节点包含：
     *   - provider: 实际的 Provider 实例
     *   - breaker: 该 Provider 专属的熔断器
     *   - enabled: 是否启用
     *   - exhausted: 是否额度耗尽
     */

    import { CircuitBreaker, CircuitBreakerConfig } from './circuit-breaker';

    export interface ProviderNode<T> {
      /** Provider 实例 */
      provider: T;
      /** 熔断器 */
      breaker: CircuitBreaker;
      /** 是否启用（false = 不参与调度） */
      enabled: boolean;
      /** 是否额度耗尽（true = 已耗尽，跳过） */
      exhausted: boolean;
      /** 额度耗尽原因 */
      exhaustedReason?: string;
      /** 额度耗尽时间（Unix ms） */
      exhaustedAt?: number;
    }

    export type ProviderFilter<T> = (node: ProviderNode<T>, index: number) => boolean;

    export class ProviderRegistry<T extends { readonly name: string; readonly vendor: string }> {
      private nodes: ProviderNode<T>[] = [];

      /**
       * 注册一个 Provider
       */
      register(
        provider: T,
        options?: {
          enabled?: boolean;
          breakerConfig?: Partial<CircuitBreakerConfig>;
        }
      ): void {
        const existingIdx = this.nodes.findIndex(n => n.provider.name === provider.name);
        const node: ProviderNode<T> = {
          provider,
          enabled: options?.enabled ?? true,
          exhausted: false,
          breaker: new CircuitBreaker({
            name: provider.name,
            ...(options?.breakerConfig || {}),
          }),
        };

        if (existingIdx >= 0) {
          this.nodes[existingIdx] = node;
        } else {
          this.nodes.push(node);
        }
      }

      /** 注销 Provider */
      unregister(name: string): boolean {
        const idx = this.nodes.findIndex(n => n.provider.name === name);
        if (idx >= 0) {
          this.nodes.splice(idx, 1);
          return true;
        }
        return false;
      }

      /** 按名称查找 */
      get(name: string): ProviderNode<T> | undefined {
        return this.nodes.find(n => n.provider.name === name);
      }

      /** 按供应商 key 查找 */
      getByVendor(vendor: string): ProviderNode<T> | undefined {
        return this.nodes.find(n => n.provider.vendor === vendor);
      }

      /** 获取所有节点 */
      list(filter?: ProviderFilter<T>): ProviderNode<T>[] {
        return filter ? this.nodes.filter((n, i) => filter(n, i)) : [...this.nodes];
      }

      /** 获取所有可用节点（启用 + 未熔断 + 未耗尽） */
      listAvailable(): ProviderNode<T>[] {
        return this.nodes.filter(n => n.enabled && !n.breaker.isOpen() && !n.exhausted);
      }

      /** 获取所有已启用节点 */
      listEnabled(): ProviderNode<T>[] {
        return this.nodes.filter(n => n.enabled);
      }

      /** 获取所有已熔断节点 */
      listBroken(): ProviderNode<T>[] {
        return this.nodes.filter(n => n.enabled && n.breaker.isOpen());
      }

      /** 获取所有额度耗尽的节点 */
      listExhausted(): ProviderNode<T>[] {
        return this.nodes.filter(n => n.exhausted);
      }

      /**
       * 标记供应商额度耗尽
       * @param name 供应商名称
       * @param reason 耗尽原因
       * @param ttlMs 可选TTL，0 = 永不过期（需手动恢复）
       */
      markExhausted(name: string, reason: string, ttlMs: number = 0): void {
        const node = this.get(name);
        if (!node) return;
        node.exhausted = true;
        node.exhaustedReason = reason;
        node.exhaustedAt = Date.now();
        console.log(`[Registry] 供应商 ${name} 额度耗尽: ${reason}${ttlMs > 0 ? `，${ttlMs / 1000}s后自动恢复` : ''}`);

        if (ttlMs > 0) {
          setTimeout(() => this.clearExhausted(name), ttlMs);
        }
      }

      /** 清除额度耗尽标记 */
      clearExhausted(name: string): boolean {
        const node = this.get(name);
        if (!node) return false;
        if (!node.exhausted) return false;
        node.exhausted = false;
        node.exhaustedReason = undefined;
        node.exhaustedAt = undefined;
        console.log(`[Registry] 供应商 ${name} 额度已恢复`);
        return true;
      }

      /**
       * 从当前 Provider 轮转到下一个可用 Provider（平等轮转）
       */
      getNextAvailable(currentName: string): ProviderNode<T> | undefined {
        const available = this.listAvailable();
        if (available.length === 0) return undefined;

        const currentIdx = available.findIndex(n => n.provider.name === currentName);
        if (currentIdx === -1) {
          return available[0];
        }
        return available[(currentIdx + 1) % available.length];
      }

      /** 获取第一个可用的 Provider */
      getPrimary(): ProviderNode<T> | undefined {
        return this.listAvailable()[0];
      }

      /** 检查所有 Provider 健康状态 */
      async healthCheckAll(checkFn: (provider: T) => Promise<boolean>): Promise<Map<string, boolean>> {
        const results = new Map<string, boolean>();
        for (const node of this.nodes) {
          if (!node.enabled) {
            results.set(node.provider.name, false);
            continue;
          }
          try {
            const healthy = await checkFn(node.provider);
            results.set(node.provider.name, healthy);
            if (!healthy) {
              node.breaker['onFailure']?.();
            }
          } catch {
            results.set(node.provider.name, false);
          }
        }
        return results;
      }

      /** Provider 数量 */
      get size(): number {
        return this.nodes.length;
      }

      /** 重置所有熔断器 */
      resetAllBreakers(): void {
        this.nodes.forEach(n => n.breaker.reset());
      }

      /** 重置所有额度耗尽标记 */
      clearAllExhausted(): void {
        this.nodes.forEach(n => {
          n.exhausted = false;
          n.exhaustedReason = undefined;
          n.exhaustedAt = undefined;
        });
      }

      /** 获取状态摘要 */
      getStatus(): Array<{
        name: string;
        vendor: string;
        enabled: boolean;
        exhausted: boolean;
        exhaustedReason?: string;
        state: string;
      }> {
        return this.nodes.map(n => ({
          name: n.provider.name,
          vendor: n.provider.vendor,
          enabled: n.enabled,
          exhausted: n.exhausted,
          exhaustedReason: n.exhaustedReason,
          state: n.breaker.getState(),
        }));
      }
    }