使用 Single-SPA 的 single-spa-store 实现灰度状态
解读
在国内一线/二线互联网公司的微前端落地场景中,single-spa-store(官方社区习惯称为“single-spa 全局状态仓库”)常被用来解决“主子应用共享灰度开关”这一高频需求。
面试官真正想考察的是:
- 你是否理解 single-spa 的“全局变量污染”红线,能否用官方推荐的 single-spa-store(或自研轻量 Store) 而非直接挂载 window;
- 能否把灰度状态从“静态配置”升级为“动态可灰、可回滚、可降级”的运行时能力;
- 能否给出中国合规灰度常见的“白名单+百分比+地域+渠道”四维模型,并用代码落地;
- 是否具备灰度状态一致性保障(主应用刷新后子应用不丢失)、性能兜底(灰度接口异常时默认走 stable 版本)等工程化思维。
知识点
- single-spa 生命周期:before-mount → mount → unmount,灰度判断必须在 before-mount 之前完成,否则会出现子应用已挂载后回退导致白屏。
- single-spa-store 本质:基于 single-spa 的
props.customProps做依赖注入,内部用 RxJS 或原生 Proxy 实现响应式,保证所有微应用拿到的是同一份引用,避免重复请求灰度接口。 - 灰度模型:
– 白名单:工号、手机号、uid 精确匹配;
– 百分比:uid 末 8 位 hash 取模;
– 地域:基于 CDN 边缘节点cloudflare-ip或阿里云X-Client-Region头;
– 渠道:App 内嵌 H5 用 userAgent 匹配,微信小程序用__wxConfig环境变量。 - 灰度快照:把灰度结果写入
sessionStorage并标记grayscaleExpire=300s,防止 F5 后重新请求造成抖动。 - 灰度降级:接口超时 300 ms 未返回,则
catch中直接返回{ gray: false, reason: 'timeout' },走 stable 版本,保证可用性优先。 - 灰度埋点:使用国内主流埋点方案(阿里 SLS、腾讯 MTA、字节 Ranger),灰度命中后必须上报一次
grayscale_hit事件,方便实时计算灰度效果。
答案
下面给出可直接在阿里/腾讯/字节等内部 GitLab 通过 Code Review 的完整实现,全部使用 TypeScript,主应用基于 single-spa@6,子应用基于 vue3+vite3,灰度服务走内部 Apollo 配置中心。
- 主应用初始化 single-spa-store
// src/store/grayscale.ts
import { BehaviorSubject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
export interface GrayRule {
whiteList: string[]; // 工号白名单
percent: number; // 0~100
regions: string[]; // ['shanghai', 'beijing']
channels: string[]; // ['app', 'wechat']
}
export interface GrayState {
gray: boolean;
reason: 'whiteList' | 'percent' | 'region' | 'channel' | 'timeout' | 'none';
}
const gray$ = new BehaviorSubject<GrayState>({ gray: false, reason: 'none' });
export const grayscaleStore = {
gray$,
setGray: (g: GrayState) => gray$.next(g),
getGray: () => gray$.value,
};
// 防止重复请求,300s 内复用快照
const GRAY_CACHE_KEY = 'gray_snapshot';
const GRAY_TTL = 300_000;
export async function fetchGrayRule(): Promise<GrayRule> {
const cached = sessionStorage.getItem(GRAY_CACHE_KEY);
if (cached) {
const { data, ts } = JSON.parse(cached);
if (Date.now() - ts < GRAY_TTL) return data;
}
// 国内一般用内网域名,走 HTTPS,100ms 超时
const rule = await fetch('/api/gray-rule', { timeout: 300 })
.then(r => r.json())
.catch(() => ({ whiteList: [], percent: 0, regions: [], channels: [] }));
sessionStorage.setItem(GRAY_CACHE_KEY, JSON.stringify({ data: rule, ts: Date.now() }));
return rule;
}
// 四维灰度判定
export async function calcGray(uid: string, region: string, channel: string): Promise<GrayState> {
const rule = await fetchGrayRule();
if (rule.whiteList.includes(uid)) return { gray: true, reason: 'whiteList' };
if (rule.regions.length && !rule.regions.includes(region)) return { gray: false, reason: 'region' };
if (rule.channels.length && !rule.channels.includes(channel)) return { gray: false, reason: 'channel' };
const hash = uid.slice(-8);
const mod = parseInt(hash, 16) % 100;
const hit = mod < rule.percent;
return { gray: hit, reason: 'percent' };
}
- 主应用在注册子应用前完成灰度计算
// src/main.ts
import { registerApplication, start } from 'single-spa';
import { calcGray, grayscaleStore } from './store/grayscale';
(async () => {
const uid = window.__USER_INFO__.uid; // 登录后注入
const region = window.__CDN_REGION__ || 'unknown';
const channel = /MicroMessenger/.test(navigator.userAgent) ? 'wechat' : 'app';
const grayState = await calcGray(uid, region, channel);
grayscaleStore.setGray(grayState);
// 埋点:灰度命中即上报
if (grayState.gray) {
navigator.sendBeacon('/log/gray', JSON.stringify({ uid, ...grayState }));
}
registerApplication({
name: 'product-list',
app: () => import('productList/App'),
activeWhen: '/product',
customProps: (name) => ({
grayscale: grayscaleStore.getGray(), // 一次性注入
gray$: grayscaleStore.gray$, // 响应式流,子应用可订阅
}),
});
start({ urlRerouteOnly: true });
})();
- 子应用(Vue3)实时响应灰度
// productList/src/main.ts
import { h, createApp } from 'vue';
import singleSpaVue from 'single-spa-vue';
import AppStable from './AppStable.vue';
import AppGray from './AppGray.vue';
const vueLifecycles = singleSpaVue({
createApp,
appOptions: (props) => ({
render() {
const gray = props.grayscale.gray;
return h(gray ? AppGray : AppStable);
},
}),
});
export const bootstrap = vueLifecycles.bootstrap;
export const mount = (props) => {
// 子应用也可继续监听灰度变化,实现运行时切换
props.gray$.pipe(distinctUntilChanged()).subscribe((g) => {
if (g.gray !== props.grayscale.gray) {
location.reload(); // 简单回退方案,也可热替换
}
});
return vueLifecycles.mount(props);
};
export const unmount = vueLifecycles.unmount;
- 灰度回滚
运维在 Apollo 把 percent 从 30 改为 0,或把白名单清空,主应用 30s 拉一次长轮询,发现规则变更后调用grayscaleStore.setGray({ gray: false, reason: 'none' }),子应用收到后自动降级到 stable 版本,全程用户无感知。
拓展思考
- 多集群灰度:国内大厂单元化部署,上海单元与北京单元各一套灰度规则,需在灰度接口里返回
unit=shanghai字段,主应用根据window.__UNIT__做隔离,防止跨单元污染。 - SSR 灰度:如果主应用采用 Next.js 同构,需在 getServerSideProps 里预取灰度,把结果序列化到
__INITIAL_GRAY_STATE__,防止客户端 hydrate 时闪屏。 - 灰度与 CDN 缓存:灰度命中后需在 url 后加
?gray=1版本号,或把gray=1写入 cookie,让 CDN 根据 cookie 做边缘缓存分片,否则会出现灰度用户命中缓存旧版本。 - 合规审计:金融、出行、医疗等强监管行业,灰度必须留痕,灰度规则变更需走 4-eye 审批,并在灰度接口返回
approvalId,前端埋点一并上报,方便合规抽查。