remoteConfig.ts 9.2 KB
import { requestViaHost } from './subapp';

/**
 * 全系统统一的远程配置中心读取层(平台级,非 UI 组件)。
 *
 * 对齐源 dj-car-life-system `src/main.js:102`:
 *   fetch(`${CONFIG_CENTER}?moduleUrl=<模块名>`) → parseConfigCenterResponse → 整包替换本地配置。
 *
 * 子应用接入只差一个 moduleUrl,例如 `loadRemoteConfig({ moduleUrl: 'uj-admin-usedcar' })`。
 * 返回什么就用什么:不裁剪、不改写、不硬编码任何网关地址 / appkey / secret / 超时值。
 *
 * 设计约束:
 *  - 请求走主壳 props.request(请求层绝不下放);配置中心是无鉴权引导请求,
 *    固定携带 _noVerify / _skipHostSignature / _skipAuthorization 三个开关。
 *  - 环境判定在服务端,依据跨域请求自动携带的 `Origin` 请求头(不是 TCP 源 IP,
 *    也不是 Referer / X-Forwarded-For)。地址栏直开配置中心 URL 或用
 *    --disable-web-security 启动 Chrome 都会丢失 Origin 头,服务端无从映射。
 *  - 每个 moduleUrl 单飞(single-flight):并发调用共享同一个 Promise;
 *    失败后缓存失效,允许重试。`invalidateRemoteConfig()` 可主动失效。
 *  - 响应形态容错:可能是 { code, data } 信封 / { status, data, headers } 原样信封 /
 *    直接是配置体;data 还可能是 JSON 字符串。逐层剥壳,不假定层数。
 */

const DEFAULT_CONFIG_CENTER_BASE = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config';

const metaEnv: Record<string, string | undefined> =
  (import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {};

/** 可用环境变量覆盖的配置中心基址(元配置;模块名始终作为 moduleUrl 查询参数拼接)。 */
export const CONFIG_CENTER_BASE_URL = metaEnv.VITE_CONFIG_CENTER_URL || DEFAULT_CONFIG_CENTER_BASE;

/** 远程配置体:返回什么就用什么,调用方按需读取自己的块。 */
export type RemoteConfig = Record<string, unknown>;

export interface LoadRemoteConfigOptions {
  /** 配置中心模块名,如 'uj-admin-usedcar'。缓存与去重均以此键为准。 */
  moduleUrl: string;
  /** 覆盖完整请求 URL(含查询串);默认 `${CONFIG_CENTER_BASE_URL}?moduleUrl=<moduleUrl>`。 */
  url?: string;
  /** 请求超时毫秒数,默认 15000。 */
  timeout?: number;
  /** 回调糖:成功时触发(Promise 语义不受影响,仍会 resolve/reject)。 */
  onSuccess?: (config: RemoteConfig) => void;
  /** 回调糖:失败时触发;不传时错误只经 Promise 传播。 */
  onError?: (error: unknown) => void;
}

/** 有辨识度的配置体特征;不要求字段齐全,命中任一即可。 */
// 保留旧 key(axios/axios2/axios8)以兼容仍下发旧名的其他配置模块(如 mp 的 dj-car-boutique-*);
// 追加新 key(ropMain/ropScrm/ropBoutique/ropPadRouter/ropCarlifeRouter)以识别已更名的 usedcar 模块。
const CONFIG_MARKERS = ['gsc', 'axios', 'axios2', 'axios8', 'sysName', 'errCode', 'baseConfig', 'ropMain', 'ropScrm', 'ropBoutique', 'ropPadRouter', 'ropCarlifeRouter'];

function parseMaybeJson(value: unknown): unknown {
  if (typeof value !== 'string' || !value.trim()) return undefined;
  try {
    return JSON.parse(value) as unknown;
  } catch {
    return undefined;
  }
}

function isConfigBody(value: unknown): value is Record<string, unknown> {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  const obj = value as Record<string, unknown>;
  return CONFIG_MARKERS.some((key) => key in obj);
}

/**
 * 逐层剥壳找到真正的配置体,字段一个不少地返回。
 * 主壳 props.request 在 _noVerify 下用 returnAll 返回「原样信封」(可能是
 * { status, data, headers } 或 { code, data }),配置中心自身又可能再包一层,
 * data 还可能是 JSON 字符串。这里不假定层数,也不按 code 值做分支。
 */
function findConfigBody(payload: unknown): Record<string, unknown> | undefined {
  let current: unknown = typeof payload === 'string' ? parseMaybeJson(payload) : payload;
  const visited = new Set<unknown>();
  for (let depth = 0; depth < 8; depth += 1) {
    if (!current || typeof current !== 'object' || visited.has(current)) return undefined;
    visited.add(current);
    if (isConfigBody(current)) return current;
    const obj = current as Record<string, unknown>;
    let next: unknown;
    for (const key of ['data', 'result', 'config', 'content', 'body']) {
      if (!(key in obj)) continue;
      const raw = obj[key];
      const candidate = typeof raw === 'string' ? parseMaybeJson(raw) : raw;
      if (candidate && typeof candidate === 'object') {
        next = candidate;
        break;
      }
    }
    if (!next) return undefined;
    current = next;
  }
  return undefined;
}

/**
 * 配置中心返回「失败信封」时把服务端 code/message 原样带出来。
 * 例如 `{code:'0',data:'',message:'不存在该环境配置'}`:findConfigBody 找不到配置体,
 * 若不做这一步,错误会被吞成笼统的「未返回有效配置体」,排查时看不到真实原因。
 */
function findFailureMessage(payload: unknown): string | undefined {
  let current: unknown = typeof payload === 'string' ? parseMaybeJson(payload) : payload;
  const visited = new Set<unknown>();
  for (let depth = 0; depth < 8; depth += 1) {
    if (!current || typeof current !== 'object' || visited.has(current)) return undefined;
    visited.add(current);
    const obj = current as Record<string, unknown>;
    const message = typeof obj.message === 'string' ? obj.message.trim() : '';
    const code = obj.code === undefined ? undefined : String(obj.code);
    // 成功信封(code 200)里的 message 只是提示文字;配置体本身不带 code。
    if (message && !isConfigBody(obj) && code !== '200') {
      return code === undefined ? message : `[code ${code}] ${message}`;
    }
    let next: unknown;
    for (const key of ['data', 'result', 'config', 'content', 'body']) {
      if (!(key in obj)) continue;
      const raw = obj[key];
      const candidate = typeof raw === 'string' ? parseMaybeJson(raw) : raw;
      if (candidate && typeof candidate === 'object') {
        next = candidate;
        break;
      }
    }
    if (!next) return undefined;
    current = next;
  }
  return undefined;
}

/** 每个 moduleUrl 单飞的进行中请求;失败即移除,成功后保留至主动失效。 */
const pendingByModule = new Map<string, Promise<RemoteConfig>>();

function buildUrl(moduleUrl: string, url?: string): string {
  if (url) return url;
  return `${CONFIG_CENTER_BASE_URL}?moduleUrl=${encodeURIComponent(moduleUrl)}`;
}

function originDiagnosticHint(requestUrl: string): string {
  return [
    '该接口按请求头 Origin 判定环境(不是 IP / Referer / XFF)。请检查:',
    '① 浏览器是否从配置中心已映射的地址访问主壳;',
    '② 是否用 --disable-web-security 启动了 Chrome(会丢失 Origin 头);',
    '③ DevTools Network 中请求是否带 Origin、响应是否带 Access-Control-Allow-Origin。',
    `请求地址:${requestUrl}`,
  ].join('');
}

/**
 * 拉取远程配置:同一 moduleUrl 会话内只拉一次(Promise 复用),失败后允许重试。
 *
 * 异步用法:`const cfg = await loadRemoteConfig({ moduleUrl: 'uj-admin-usedcar' });`
 * 回调用法:`loadRemoteConfig({ moduleUrl, onSuccess: render, onError: toast });`
 */
export function loadRemoteConfig(options: LoadRemoteConfigOptions): Promise<RemoteConfig> {
  const { moduleUrl, url, timeout = 15_000, onSuccess, onError } = options;
  if (!moduleUrl) return Promise.reject(new Error('loadRemoteConfig 缺少 moduleUrl。'));

  let pending = pendingByModule.get(moduleUrl);
  if (!pending) {
    const requestUrl = buildUrl(moduleUrl, url);
    pending = requestViaHost()({
      method: 'GET',
      url: requestUrl,
      timeout,
      // 配置中心是无鉴权引导请求。主壳 http.ts 支持这三个开关:跳过登录态、
      // 跳过主壳加签、跳过业务码验签(_noVerify 会以 returnAll 原样返回信封)。
      _noVerify: true,
      _skipHostSignature: true,
      _skipAuthorization: true,
    })
      .then((response: unknown) => {
        const config = findConfigBody(response);
        if (!config) {
          const remoteMessage = findFailureMessage(response);
          throw new Error(
            remoteMessage
              ? `配置中心返回失败:${remoteMessage}。${originDiagnosticHint(requestUrl)}`
              : `配置中心未返回有效的 ${moduleUrl} 配置体。${originDiagnosticHint(requestUrl)}`,
          );
        }
        return config as RemoteConfig;
      })
      .catch((error: unknown) => {
        pendingByModule.delete(moduleUrl);
        throw error;
      });
    pendingByModule.set(moduleUrl, pending);
  }

  if (onSuccess || onError) {
    pending.then(
      (config) => onSuccess?.(config),
      (error: unknown) => onError?.(error),
    );
  }
  return pending;
}

/** 配置中心内容变更后可主动失效缓存(例如切换环境、重新登录);不传则清空全部模块。 */
export function invalidateRemoteConfig(moduleUrl?: string): void {
  if (moduleUrl) pendingByModule.delete(moduleUrl);
  else pendingByModule.clear();
}