remote-manifest.mjs 4.5 KB
/**
 * 远端清单合并 —— 解决「两个团队同时发版,后发的把先发的覆盖掉」。
 *
 * ── 问题 ──────────────────────────────────────────────────────────────
 * mfe/manifest.json 是一份**全量**清单,同时管着所有子系统。CI 里两个 job 并发跑
 * (A 发 store、B 发 system),两边都基于自己机器上的 .release-state 生成清单,
 * 最后上传的那个整份覆盖前一个 —— 先发的那条凭空消失,线上退回旧 URL。
 *
 * ── 做法 ──────────────────────────────────────────────────────────────
 * 发布前 GET 一次**线上真实清单**,把它当作合并基线:
 *   - 本次要发的 app → 用本地(本次构建的)条目;
 *   - 其它 app → 用远端条目(别人可能刚发过,本地那份是旧的);
 *   - 远端没有、本地有的 → 保留本地(远端可能是首次部署,或该 app 还没上线)。
 *
 * 这不能彻底消除竞态(真正的原子性需要服务端 CAS 或 CI 串行),但把冲突窗口从
 * 「整个构建过程(几十秒到几分钟)」压缩到「上传的那几秒」,且后发的一定包含先发的。
 *
 * 拉取失败**不阻断发布** —— 可能是网络、可能是首次部署(线上还没有清单)。
 * 但必须明确告警,否则并发保护静默失效,人以为配了就安全了。
 */
import fs from 'node:fs/promises';
import path from 'node:path';

/**
 * @param {object} o
 * @param {string} o.stateFile  本地状态文件(.release-state/manifest.json)
 * @param {string} o.url        线上清单地址(绝对 URL,或配合 origin 的 /mfe/manifest.json)
 * @param {string[]} o.keepLocal 本次要发布的 app:这些条目以本地为准
 * @param {(m: string) => void} o.info
 * @param {number} [o.timeoutMs]
 * @returns {Promise<{ok: boolean, error?: string, adopted?: string[], kept?: string[],
 *   remoteSubapps?: Record<string, {url: string, version?: string}>}>}
 *   ok 时带 remoteSubapps(线上条目原样),供「该版本是否已在线上」判定使用。
 */
export async function mergeRemoteManifest({ stateFile, url, keepLocal, info, timeoutMs = 8000 }) {
  let remote;
  try {
    const res = await fetch(url, {
      signal: AbortSignal.timeout(timeoutMs),
      // 清单必须拿最新的:中间任何一层缓存命中,都会把刚发布的条目吃掉
      headers: { 'cache-control': 'no-cache', pragma: 'no-cache' },
    });
    if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
    remote = await res.json();
  } catch (err) {
    return { ok: false, error: err.message };
  }

  if (!remote || typeof remote.subapps !== 'object' || remote.subapps === null) {
    return { ok: false, error: '远端清单缺少 subapps 字段' };
  }

  // 全新机器可能还没有状态文件(首次启用 remote 或同事首跑):以空为基线,
  // 远端条目全部采纳 —— 这正是「以线上为真源」的初始状态,不能崩。
  let state = {};
  try {
    state = JSON.parse(await fs.readFile(stateFile, 'utf8'));
  } catch {
    /* 无文件或坏文件都按空状态处理 */
  }
  if (!state.subapps || typeof state.subapps !== 'object') state.subapps = {};

  const adopted = [];
  for (const [name, entry] of Object.entries(remote.subapps)) {
    if (keepLocal.includes(name)) continue;
    if (!entry || typeof entry.url !== 'string' || !entry.url) continue; // 坏条目不带进本地
    // 远端已有的 app 一律以远端为准:本地那份可能是几小时前的,把别人的发布覆盖回去
    // 就等于「后发的一次静默回滚」。
    const before = state.subapps[name];
    state.subapps[name] = entry;
    if (!before || before.version !== entry.version)
      adopted.push(`${name}@${entry.version ?? '?'}`);
  }

  await fs.mkdir(path.dirname(stateFile), { recursive: true });
  await fs.writeFile(stateFile, `${JSON.stringify(state, null, 2)}\n`, 'utf8');

  const kept = keepLocal.filter((n) => state.subapps[n]);
  if (adopted.length) info(`远端清单已合并:沿用 ${adopted.join(', ')}(本次未发,以线上为准)`);
  else info(`远端清单已合并:${kept.length} 个本次发布的条目以本地为准,其余无变化`);
  return { ok: true, adopted, kept, remoteSubapps: remote.subapps };
}