Vercel CLI 告警规则:`vc alerts rules schema` 与内置/自定义告警规则创建实战指南

原创2026-09-20 22:45:321,333 阅读
文章标签:CLI云原生Serverless构建工具DevOps后端前端边缘计算

Vercel CLI 告警规则:vc alerts rules schema 与内置/自定义告警规则创建实战指南

导读

本文基于 Vercel CLI(本仓库 packages/cli)中新增的 alerts rules schema 命令及其配套的规则创建示例,系统讲解如何通过 CLI 以 JSON body 的形式创建、查询、更新和删除告警通知规则(Alert Rules)。你将掌握三种规则类型(usage_anomaly、error_anomaly、custom_alert)的完整字段定义与可复制示例、--project 与 --all 作用域语义,以及自定义告警查询(queryJsonString)从指标发现到 JSON 转义的完整链路,实现与 Vercel 控制台(Dashboard)对齐的告警管理能力。

一、背景:本次变更带来了什么

本次变更(见 .changeset/alert-rules-schema-help.md)为 vercel CLI 增加了 alerts rules schema 子命令,并补充了内置规则与自定义告警规则的创建示例。其核心改进有三点:

  1. 新增 schema 子命令:开发者无需翻阅文档即可在终端查看告警规则 body 的字段定义与示例;
  2. 显式 --project 作为内置规则的目标:创建内置规则时通过 --project <name-or-id> 明确指定目标项目,避免依赖隐式上下文;
  3. 完整自定义告警项目元数据:创建自定义告警规则时自动补齐 scope 中的 projectId/projectName 等项目元数据,确保规则创建后可以直接在 Dashboard 中编辑。

这些改动落在 packages/cli/src/commands/alerts/rules/ 目录下,与已有的 ls、add、inspect、update、rm 子命令共同构成一套完整的告警规则命令行管理能力(源码中的 rulesAggregateCommand 将其描述为 "Create, list, update, or delete alert notification rules (dashboard parity)",见 command.ts)。

二、alerts rules 命令族速览

在深入 schema 之前,先整体认识 vc alerts rules 的六个子命令(定义见 command.ts):

子命令 别名 作用 示例
ls list 列出当前作用域下的告警规则,可按类型过滤 vc alerts rules ls --type custom_alert
schema — 按告警类型展示规则 body schema 与示例 vc alerts rules schema --type error_anomaly
add create 从 JSON body 文件创建规则 vc alerts rules add --body ./rule.json
inspect get 按 ruleId 查看单条规则 vc alerts rules inspect ar_abc123
update patch 从 JSON body 文件局部更新规则 vc alerts rules update ar_abc123 --body ./patch.json
rm remove、delete 删除规则 vc alerts rules rm ar_abc123 --yes

所有子命令都共享两个作用域选项:

  • --project <name-or-id>(简写 -p):指定项目作用域,覆盖当前链接项目;需要团队上下文;
  • --all(简写 -a):仅操作团队级规则(省略项目过滤,忽略链接项目)。

从源码可以确认 --all 与 --project 是互斥的:parseRulesFlagsAndScope 会调用 validateAllProjectMutualExclusivity 做校验,同时传入两个参数会报参数错误(见 parse-scope.ts)。

三、vc alerts rules schema 命令详解

3.1 列出支持的规则类型

不带任何参数运行:

vc alerts rules schema

会以表格形式输出三种受支持的规则类型(源码见 schema.ts):

Type Description
usage_anomaly Built-in usage anomaly alerts(内置用量异常告警)
error_anomaly Built-in error anomaly alerts(内置错误异常告警)
custom_alert Custom Observability metric alerts(自定义可观测性指标告警)

并提示运行 vc alerts rules schema --type <type> 查看具体规则 body schema。

3.2 查看某一类型的完整 schema

vc alerts rules schema --type custom_alert

--type 参数接受 usage_anomaly、error_anomaly、custom_alert 三者之一。从源码看,参数会经过 normalizeRuleType 归一化处理:会 trim()、转小写,并将连字符/空白替换为下划线(如 custom-alert 或 custom alert 都会被识别为 custom_alert,见 schema.ts);传入非法类型时则返回 INVALID_ARGUMENTS 错误并提示可用的三种类型。

CLI 文本输出结构为:字段表(Fields)→ alertTypes[].filter 允许值 → 自定义告警字段表 → queryJsonString 字段表 → 转义前的查询 JSON 示例 → 完整 body 示例。

3.3 JSON 输出模式

对脚本/自动化场景,可以追加 --format json(对应源码中的 formatOption):

vc alerts rules schema --type custom_alert --format json

此时整个 schema 对象(含 type、description、fields、examples 等)以 JSON 形式输出到 stdout(见 schema.ts),便于被 jq 等工具进一步处理。

四、内置规则 schema:usage_anomaly 与 error_anomaly

4.1 公共字段

两类内置规则共享 BUILT_IN_COMMON_FIELDS(见 schema.ts):

Field Required Type 说明
name yes string 规则名称
alertTypes yes array 一个或多个告警类型配置
projectId no string OData 项目过滤表达式;省略则作用于团队级
autosubscribeOwnersInKnock no boolean 是否自动订阅项目所有者

4.2 usage_anomaly(用量异常)

除公共字段外,alertTypes[].type 固定为 usage_anomaly(必填),alertTypes[].filter 为可选的 OData 过滤表达式。filter 支持的指标(metric 字段取值)为:

fluid_cpu_duration, fluid_duration, fast_data_transfer, edge_requests, function_invocations

最小示例(团队级,监控所有用量指标):

{
  "name": "Usage anomalies",
  "alertTypes": [{ "type": "usage_anomaly" }]
}

过滤到单一指标的项目级示例:

{
  "name": "Edge request anomalies",
  "projectId": "projectId eq 'prj_123'",
  "alertTypes": [{ "type": "usage_anomaly", "filter": "metric eq 'edge_requests'" }]
}

4.3 error_anomaly(错误异常)

结构同 usage_anomaly,alertTypes[].type 固定为 error_anomaly。filter 的典型维度与取值示例:

Field Allowed values / examples
statusGroup 4xx, 5xx
route route eq '/api/checkout', contains(route, '/api')

最小示例:

{
  "name": "Error anomalies",
  "alertTypes": [{ "type": "error_anomaly" }]
}

按 5xx 状态组与路由过滤:

{
  "name": "Checkout 5xx errors",
  "projectId": "projectId eq 'prj_123'",
  "alertTypes": [
    { "type": "error_anomaly", "filter": "statusGroup eq '5xx' and route eq '/api/checkout'" }
  ]
}

五、自定义告警规则 schema:custom_alert

5.1 公共字段

custom_alert 使用 CUSTOM_ALERT_COMMON_FIELDS(见 schema.ts),其中 projectId 是可选的,默认取 --project 或当前链接项目:

Field Required Type 说明
name yes string 规则名称
projectId no string 默认为 --project 或链接项目
alertTypes yes array 一个或多个告警类型配置(type 为 custom_alert)
customAlert yes object 自定义告警定义
autosubscribeOwnersInKnock no boolean 自动订阅项目所有者

5.2 customAlert 字段

Field Required Type 说明
customAlert.queryJsonString yes string 转义后的查询 JSON 字符串
customAlert.triggerType yes string threshold(阈值)或 anomaly(异常检测)
customAlert.triggerOperator yes string gt, gte, lt, lte
customAlert.triggerThreshold yes number 阈值或 z-score
customAlert.minThreshold no number 最小观测值
customAlert.formula no object 比率公式;left/right 引用 rollup 键

5.3 queryJsonString 内部字段

queryJsonString 本质是查询引擎(query-engine)查询 JSON 的转义字符串,其字段为:

Field Required Type 说明
scope no object 项目作用域
event yes string 告警查询事件名,例如 incomingRequest
rollups yes object 具名度量聚合
rollups.*.measure yes string 度量指标
rollups.*.aggregation yes string 聚合方式
rollups.*.filter no string rollup 级 OData 过滤
groupBy no array 最多一个维度
filter no string 顶层 OData 过滤
granularity no object 5m、1h 或 1d,默认 5m

例如一个按 route 分组的 5 分钟请求量查询(转义前,源码 schema.ts):

{
  "event": "incomingRequest",
  "rollups": {
    "requests": { "measure": "count", "aggregation": "sum" }
  },
  "groupBy": ["route"],
  "granularity": { "minutes": 5 }
}

以及一个计算错误率的比率查询(numerator/denominator 两个 rollup 键配合 formula 使用,见 schema.ts):

{
  "event": "incomingRequest",
  "rollups": {
    "numerator": { "measure": "count", "aggregation": "sum", "filter": "httpStatus ge 500" },
    "denominator": { "measure": "count", "aggregation": "sum" }
  },
  "granularity": { "hours": 1 }
}

5.4 自定义告警示例

异常检测(Anomaly):

{
  "name": "Request volume anomaly",
  "alertTypes": [{ "type": "custom_alert" }],
  "customAlert": {
    "queryJsonString": "{\"event\":\"incomingRequest\",\"rollups\":{\"requests\":{\"measure\":\"count\",\"aggregation\":\"sum\"}},\"groupBy\":[\"route\"],\"granularity\":{\"minutes\":5}}",
    "triggerType": "anomaly",
    "triggerOperator": "gt",
    "triggerThreshold": 3
  }
}

阈值 + 比率(Threshold ratio):

{
  "name": "Checkout error rate",
  "alertTypes": [{ "type": "custom_alert" }],
  "customAlert": {
    "queryJsonString": "{\"event\":\"incomingRequest\",\"rollups\":{\"numerator\":{\"measure\":\"count\",\"aggregation\":\"sum\",\"filter\":\"httpStatus ge 500\"},\"denominator\":{\"measure\":\"count\",\"aggregation\":\"sum\"}},\"granularity\":{\"hours\":1}}",
    "triggerType": "threshold",
    "triggerOperator": "gt",
    "triggerThreshold": 0.05,
    "formula": { "operator": "divide", "left": "numerator", "right": "denominator" },
    "minThreshold": 20
  }
}

注意:queryJsonString 必须是转义后的 JSON 字符串。实际编写时可将上述未转义 JSON 用 JSON.stringify 处理后嵌入(源码示例正是这样生成的,见 schema.ts)。

5.5 自定义告警指标发现

schema 命令的 help 部分提供了指标发现指引(见 schema-help.ts):

  • 运行 vc metrics schema <metric-or-prefix> 可以发现可用指标、聚合与维度;指标 ID 使用 vercel. 命名空间,如 vercel.request.count;
  • 自定义告警查询使用 query-engine 的 event/measure 名称,而非公开指标 ID,映射关系如下:
公开指标 ID event measure
vercel.request.count incomingRequest count
vercel.function_invocation.count serverlessFunctionInvocation count
vercel.external_api_request.count outgoingRequest count
vercel.sandbox.cpu_total_time_ms sandboxUsage cpuTotalTimeMs

六、规则创建实战:vc alerts rules add

6.1 完整的内置规则示例

以下示例直接来自 CLI 帮助文本(见 add-help.ts)。

显式指定项目的内置用量异常规则(注意 --project 用法与 projectId 使用 in 运算符):

{
  "name": "Production usage anomalies",
  "alertTypes": [{ "type": "usage_anomaly" }],
  "projectId": "projectId in ('prj_123')",
  "autosubscribeOwnersInKnock": true
}

内置 4xx 错误异常规则:

{
  "name": "Production 4xx error anomalies",
  "alertTypes": [{ "type": "error_anomaly", "filter": "statusGroup eq '4xx'" }],
  "projectId": "projectId in ('prj_123')"
}

6.2 自定义阈值规则与异常规则

自定义阈值规则(错误率 > 5%,基于比率公式):

{
  "name": "Checkout error rate",
  "alertTypes": [{ "type": "custom_alert" }],
  "customAlert": {
    "queryJsonString": "{\"event\":\"incomingRequest\",\"rollups\":{\"errors\":{\"measure\":\"count\",\"aggregation\":\"sum\",\"filter\":\"httpStatus ge 500\"},\"requests\":{\"measure\":\"count\",\"aggregation\":\"sum\"}},\"granularity\":{\"hours\":1}}",
    "triggerType": "threshold",
    "triggerOperator": "gt",
    "triggerThreshold": 0.05,
    "formula": { "operator": "divide", "left": "errors", "right": "requests" },
    "minThreshold": 20
  }
}

自定义异常规则(请求量 z-score > 3):

{
  "name": "Edge request volume anomaly",
  "alertTypes": [{ "type": "custom_alert" }],
  "customAlert": {
    "queryJsonString": "{\"event\":\"incomingRequest\",\"rollups\":{\"requests\":{\"measure\":\"count\",\"aggregation\":\"sum\"}},\"groupBy\":[\"route\"],\"granularity\":{\"minutes\":5}}",
    "triggerType": "anomaly",
    "triggerOperator": "gt",
    "triggerThreshold": 3
  }
}

6.3 执行创建命令

将上述任一 body 保存为 JSON 文件(如 rule.json),替换占位符后运行:

vc alerts rules add --body ./rule.json

也可以显式指定目标项目:

vc alerts rules add --project my-app --body ./rule.json

从源码(add.ts)可以确认整个创建流程:

  1. 解析参数并校验 --body 必填;
  2. 解析作用域(--project / --all 互斥校验);
  3. 读取并 JSON.parse body 文件(文件不存在或 JSON 非法会给出明确错误);
  4. 若 body 是自定义告警规则,会解析 customAlert.queryJsonString,校验其合法性(非法 JSON 会提示 "Provide queryJsonString as an escaped JSON string",见 custom-alert-query.ts);
  5. 自动删除 id 与 teamId——这两个字段由 API 分配,不应手动传入;
  6. POST 到 /alerts/v2/alert-rules?teamId=...&projectId=...(路径构造见 util.ts)。

6.4 自定义告警项目元数据的自动补齐

这是本次变更的亮点之一。对于自定义告警规则,若 body 中未提供 projectId,CLI 会将其默认到 --project 或链接项目(见 add.ts),并进一步通过 setMissingCustomAlertProjectScope 向 queryJsonString 内的 scope 注入完整的项目元数据:

{
  "type": "project",
  "ownerId": "<teamId>",
  "projectIds": ["<projectId>"],
  "projectId": "<projectId>",
  "projectName": "<projectName>"
}

其中 projectName 通过 resolveCustomAlertProjectName 按项目名或 ID 解析获得(见 custom-alert-query.ts)。补齐这些元数据后,规则在 Vercel Dashboard 中可以直接展示和编辑,不会出现项目信息缺失的问题。

6.5 查看、更新与删除

创建完成后,用以下命令管理规则(命令定义见 command.ts):

# 列出当前项目的规则
vc alerts rules ls

# 列出团队级规则
vc alerts rules ls --all

# 按类型过滤
vc alerts rules ls --type custom_alert

# JSON 输出,便于脚本处理
vc alerts rules ls --json

# 查看单条规则
vc alerts rules inspect ar_abc123

# 局部更新(省略的字段保持不变,null 清除可选的受支持字段)
vc alerts rules update ar_abc123 --body ./patch.json

# 删除(--yes 跳过确认)
vc alerts rules rm ar_abc123 --yes

七、底层实现与错误处理

7.1 API 端点

规则相关的 API 路径统一由 util.ts 构造:

  • 集合路径:GET/POST /alerts/v2/alert-rules?teamId=<id>&projectId=<id>;
  • 单项路径:GET/PATCH/DELETE /alerts/v2/alert-rules/<ruleId>?teamId=<id>。

projectId 查询参数仅在项目作用域下追加;团队级(--all)规则省略该参数。

7.2 常见错误与排查建议

handleRulesApiError(见 util.ts)对不同的 HTTP 状态码给出了针对性提示:

  • 401 / 403:当前身份无权管理该作用域的告警规则。建议确认角色是否具备管理 Alert Rules 的权限,必要时通过 --token 与 --scope 指定身份;可用 vc whoami 确认当前用户与团队,若规则属于其他团队则使用 --scope <team-slug>;
  • 5xx:告警规则端点服务异常,可加 --debug 重跑并附带失败请求的 x-vercel-id 反馈排查;
  • 404:规则不存在(对应 NOT_FOUND 原因码);
  • 429:触发限流(rate_limited);
  • 其他:透出 serverMessage。

此外,--body 文件不可读、JSON 非法、--project 缺少参数等场景均有专门的错误提示(见 emitRulesArgParseError),交互模式下会输出到 stderr,非交互模式则输出 JSON 到 stdout 并返回退出码 1,便于 CI 集成。

八、最佳实践小结

  1. 先 schema 后编写:创建规则前先运行 vc alerts rules schema --type <type>(文本或 --format json)获取当前版本支持的字段与示例,避免手写过时结构;
  2. 内置规则显式指定项目:使用 --project <name-or-id> 明确目标项目,或通过 --all 声明团队级规则,不要依赖模糊的隐式上下文;
  3. 自定义规则注意转义:queryJsonString 是转义后的 JSON 字符串,先用 JSON.stringify 处理查询对象再嵌入 body;若提示 Invalid JSON,优先检查转义;
  4. 不传 id/teamId:这两个字段由 API 分配,CLI 会自动删除 body 中的多余值;
  5. 让 CLI 补齐元数据:自定义告警的 projectId 缺省即取 --project/链接项目,scope 项目元数据会自动补齐,保证 Dashboard 可编辑。

通过以上命令与示例,你可以在不改动仓库代码的前提下,用 Vercel CLI 完成从内置用量/错误异常告警到自定义可观测性指标告警的全流程管理。相关源码与帮助文本可进一步查阅 schema.ts、add-help.ts、add.ts 与 command.ts。

登录后查看全文
vercel