当查询时间超过 200ms 时,如何自动创建 GitHub Issue?

解读

面试官真正想考察的是:

  1. 你是否理解 Apollo Client 的“链路”思想——请求从组件出发,经过链路(link chain)再到网络,链路里可以插入任意逻辑。
  2. 你是否能把“性能监控”与“运维自动化”打通,把前端慢查询直接沉淀为可追踪的 GitHub Issue,而不是仅仅打一条 console.warn。
  3. 你是否熟悉国内可落地的工程化方案:私有 GitLab、内网代理、权限密钥管理、CI 审批流,而不是照搬国外公开仓库的 Personal Access Token。
  4. 你是否能在不阻塞主线程、不泄露敏感信息的前提下,把“采样、去重、分级、告警”做全。

一句话:不是“怎么算 200ms”,而是“怎么把 200ms 变成可落地的内部工单”。

知识点

  1. Apollo Link 体系
    • ApolloLink 的拆分:Request → Forward → Response → Next → Complete 的管道模型。
    • 自定义 Link 的两种写法:class 继承或 link 工厂函数;必须返回 Observable。
  2. 性能采样
    • performance.now() 高分辨率计时;Node 环境可用 process.hrtime.bigint()。
    • 采样率控制:可配置为 1%、10%,防止 GitHub API 被打爆。
  3. GitHub Issue 自动化
    • GitHub REST v4(GraphQL)endpoint:/repos/{owner}/{repo}/issues。
    • 国内私有 GitLab 同理,endpoint 为 /api/v4/projects/{id}/issues。
    • 身份凭证:
      – 公有云 GitHub:GitHub App 安装令牌(推荐,可细粒度授权)。
      – 私有 GitLab:project access token 或 CI_JOB_TOKEN(需 maintainer 开权限)。
    • 去重逻辑:用 title 哈希(如 gql 指纹 + 阈值)+ label=perf-regression,避免重复工单。
  4. 安全与合规
    • 不把查询变量明文写进 Issue,只放指纹(operationName + 变量哈希)。
    • 密钥走环境变量 → 构建时注入 → 浏览器侧不可见;SSR 场景只在服务端触发。
  5. 错误与重试
    • GitHub 返回 401/403 时静默降级,不能阻塞用户查询。
    • 可内联 retry-link,保证原查询不受影响。

答案

下面给出一条“最小可落地、国内团队可直接复制”的完整链路,全部代码用 TypeScript 书写,可直接放进微前端基座或 SSR 网关。

  1. 自定义 SlowQueryLink
import { ApolloLink, Observable } from '@apollo/client/core';
import { print } from 'graphql';
import { createHash } from 'crypto';

interface Options {
  threshold?: number;          // 默认 200ms
  sampleRate?: number;         // 默认 0.1(10%)
  gitlabProjectId: string;     // 私有 GitLab 项目 id
  gitlabToken: string;         // 项目访问令牌,只给 api 权限
  endpoint?: string;           // 默认 https://gitlab.example.com/api/v4
}

export const slowQueryLink = ({
  threshold = 200,
  sampleRate = 0.1,
  gitlabProjectId,
  gitlabToken,
  endpoint = 'https://gitlab.example.com/api/v4'
}: Options) => new ApolloLink((operation, forward) => {
  return new Observable(observer => {
    const start = performance.now();
    const subscription = forward(operation).subscribe({
      next: result => {
        const cost = performance.now() - start;
        if (cost > threshold && Math.random() < sampleRate) {
          // 异步上报,不阻塞主链路
          submitIssue(operation, cost, gitlabProjectId, gitlabToken, endpoint)
            .catch(() => { /* 静默失败 */ });
        }
        observer.next(result);
      },
      error: e  => observer.error(e),
      complete: () => observer.complete()
    });
    return () => subscription.unsubscribe();
  });
});
  1. 提交 GitLab Issue(私有 GitHub 同理,只换 endpoint)
async function submitIssue(
  operation: any,
  cost: number,
  projectId: string,
  token: string,
  endpoint: string
) {
  const query = print(operation.query);
  const fingerprint = createHash('md5')
                        .update(operation.operationName || 'anonymous')
                        .update(JSON.stringify(operation.variables))
                        .digest('hex').slice(0, 8);

  const title = `[Perf] ${operation.operationName || 'anonymous'} > 200ms`;
  const body = `
| 字段        | 内容                          |
|-------------|-------------------------------|
| 耗时        | ${cost.toFixed(2)} ms         |
| 查询指纹    | ${fingerprint}                |
| 变量哈希    | ${createHash('md5').update(JSON.stringify(operation.variables)).digest('hex')} |
| 发生时间    | ${new Date().toISOString()}   |

> 注:变量值已哈希脱敏,如需复现请联系前端值班。
`;

  const payload = {
    title,
    description: body,
    labels: 'perf-regression,apollo-client'
  };

  await fetch(`${endpoint}/projects/${encodeURIComponent(projectId)}/issues`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'PRIVATE-TOKEN': token
    },
    body: JSON.stringify(payload)
  });
}
  1. 注入客户端
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { slowQueryLink } from './slowQueryLink';

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: ApolloLink.from([
    slowQueryLink({
      threshold: 200,
      sampleRate: 0.1,
      gitlabProjectId: process.env.GITLAB_PROJECT_ID!,
      gitlabToken: process.env.GITLAB_TOKEN!
    }),
    httpLink({ uri: '/graphql' })
  ])
});
  1. 国内运维配套
    • 密钥:GitLab Token 走 GitLab CI Variables → 构建时注入 → 浏览器 bundle 不含 token;只在 SSR 层或 BFF 层触发。
    • 审批:给 label=perf-regression 的 Issue 配置 webhook,自动@值班人,进企业微信/飞书群。
    • 去重:title 哈希 + label 过滤,24h 内同一指纹不再开单。
    • 降级:GitLab 4xx/5xx 时 catch 掉,用户无感知。

至此,200ms 阈值一旦触发,10% 采样会自动在私有 GitLab 创建 Issue,全程不阻塞用户,且符合国内公司“内网 GitLab + 审批流”的合规要求。

拓展思考

  1. 如何把“慢查询”与“后端 traceId”串联?
    在响应头里返回 x-trace-id,SlowQueryLink 里读取并写进 Issue,方便后端 SRE 直接定位日志。
  2. 如何区分“网络慢”还是“服务端慢”?
    在浏览器端再加一个 Resource Timing 指标,把 domainLookupStart→responseEnd 的时间差与 graphql 耗时对比,若两者接近说明网络问题,Issue 加 label=network。
  3. 如何支持“动态阈值”?
    把阈值配置放在配置中心(Nacos、Apollo 配置中心),SlowQueryLink 每 30s 拉一次,实现“白天 200ms、夜间 500ms”的弹性阈值。
  4. 如何防止恶意刷 Issue?
    在服务端加一层“慢查询网关”:同一 IP+指纹 5 分钟内只能开 1 个 Issue,利用 Redis 计数器滑动窗口。
  5. 如果公司用“飞书多维表格”替代 GitLab Issue 如何改?
    只需把 submitIssue 函数换成飞书开放平台 API(/bitable/v1/apps/{app_token}/tables/{table_id}/records),字段映射一致即可,链路思想不变。