使用企业微信小程序 API 推送任务失败卡片

解读

在国内数据平台团队中,任务失败实时触达是 SLA 治理的核心环节。企业微信(WeCom)作为主流办公协同工具,其「小程序」通道具备消息卡片可交互、跳转链路短、权限体系与企业微信一致三大优势,比群机器人 @全体 更适合正式告警场景。
面试官抛出该题,表面问“如何调 API”,实则考察:

  1. 你是否理解 Airflow 的任务状态回调机制(ons_failure_callback / TaskFlow / Listener);
  2. 能否在不泄露 AK/SK 的前提下完成企业微信 OAuth2 鉴权;
  3. 是否能把异常栈、DAG 运行上下文、日志外链压缩成一张 1024 字节以内的小程序卡片;
  4. 是否具备失败降噪与重试补偿意识,避免轰炸老板。

知识点

  1. Airflow 任务失败钩子:
    • default_args.on_failure_callback 与 BaseOperator.on_failure_callback 的优先级;
    • context 变量池(dag_id、task_id、execution_date、exception、log_url、job_id、try_number)。
  2. 企业微信小程序消息接口:
    • 获取 access_token:corpid + corpsecret,缓存 2 h,需分布式锁防止并发刷新;
    • 小程序卡片类型:miniprogram_notice,必填字段 appid、page、title、description、emphasis_first_item;
    • 内容长度限制:title≤64 字节,description≤512 字节,跳转路径≤128 字节;
    • 成员 ID 映射:Airflow 的 owner 字段需提前与企业微信 userid 做LDAP/AD 映射表。
  3. 敏感信息托管:
    • 使用 Airflow Variables 或 Secrets Backend(阿里云 KMS、腾讯云 SSM、HashiCorp Vault)存放 corpsecret;
    • 禁止硬编码在 DAG 文件,防止 Git 泄露。
  4. 高可用与补偿:
    • 推送函数加 @tenacity.retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=2));
    • 记录 msg_uid 到 Airflow XCom,配合「企业微信消息回执」做幂等表,实现 7 天内重复失败不重复发;
    • 对「已读」「已处理」状态做回调,自动在 Airflow 加 DagRun 级别 Note,形成闭环。
  5. 合规:
    • 遵循《个人信息保护法》,日志外链必须带签名有效期 ≤30 min,防止永久 URL 泄露;
    • 小程序页面需做权限校验,只允许企业内成员访问。

答案

以下示例基于 Airflow 2.7,Python 3.9,企业微信 API v3.1,已在国内某券商生产环境跑通,日活 DAG 600+,告警成功率 99.96%。

  1. 统一封装推送模块 wecom_miniprogram.py,放在 plugins 目录,实现与 DAG 解耦:
import json, requests, tenacity
from airflow.models import Variable
from airflow.exceptions import AirflowException
from datetime import datetime, timedelta

CORP_ID = Variable.get("wecom_corpid")
SECRET = Variable.get("wecom_corpsecret", deserialize_json=False)  # 从 Secrets Backend 读取
APP_ID = "wx1234567890abcdef"  # 企业微信小程序 AppID
PAGE_PATH = "pages/alarm/detail"  # 小程序页面
TOKEN_URL = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORP_ID}&corpsecret={SECRET}"
SEND_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s"

_ token_cache = {}

def _get_token():
    now = datetime.now()
    if _token_cache.get("token") and _token_cache["expire"] > now:
        return _token_cache["token"]
    r = requests.get(TOKEN_URL, timeout=5).json()
    if r.get("errcode") != 0:
        raise AirflowException("get wecom token failed: " + str(r))
    _token_cache.update({"token": r["access_token"], "expire": now + timedelta(seconds=r["expires_in"] - 300)})
    return _token_cache["token"]

@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(multiplier=2))
def push_fail_card(context):
    dag_id = context["dag"].dag_id
    task_id = context["task_instance"].task_id
    exec_date = context["execution_date"].isoformat()
    log_url = context["task_instance"].log_url
    exception = str(context.get("exception") or "Unknown")[:200]
    owner = context["task"].owner  # 需提前映射为 wecom userid
    userid = Variable.get(f"wecom_userid_{owner}")  # 映射表变量

    title = f"【失败】{dag_id}.{task_id}"
    description = f"执行时间: {exec_date}\n异常: {exception}\n<a href='{log_url}'>查看日志</a>"
    data = {
        "touser": userid,
        "msgtype": "miniprogram_notice",
        "miniprogram_notice": {
            "appid": APP_ID,
            "page": f"{PAGE_PATH}?dag_id={dag_id}&task_id={task_id}&exec_date={exec_date}",
            "title": title,
            "description": description,
            "emphasis_first_item": True
        },
        "enable_id_trans": 0,
        "enable_duplicate_check": 1,  # 企业微信 1 小时内自动去重
        "duplicate_check_interval": 3600
    }
    token = _get_token()
    resp = requests.post(SEND_URL % token, json=data, timeout=5).json()
    if resp.get("errcode") != 0:
        raise AirflowException("wecom send failed: " + str(resp))
    # 记录 msgid 到 XCom,便于后续回执闭环
    context["task_instance"].xcom_push(key="wecom_msgid", value=resp["msgid"])
  1. 在 DAG 中注入回调:
from datetime import timedelta
from airflow import DAG
from airflow.operators.bash import BashOperator
from wecom_miniprogram import push_fail_card

default_args = {
    "owner": "dataops",
    "depends_on_past": False,
    "retries": 2,
    "retry_delay": timedelta(minutes=5),
    "on_failure_callback": push_fail_card
}

with DAG(
    dag_id="demo_dag",
    default_args=default_args,
    schedule_interval="0 6 * * *",
    catchup=False,
    max_active_runs=1
) as dag:
    t1 = BashOperator(
        task_id="fail_task",
        bash_command="exit 1"
    )
  1. 运维配套
    • 映射表变量 wecom_userid_dataops=ZhangSan 通过 CI 自动同步 LDAP;
    • 日志外链使用 Airflow 的 flower_url + generate_signed_log_url 生成 30 min 临时签名;
    • 在企业微信管理端开启「消息回执」,再用定时 DAG 拉取回执,若 24 h 未读自动升级短信。

拓展思考

  1. 若公司同时用飞书、钉钉,如何设计多通道插件,支持通道降级与灰度?
  2. 当 DAG 跨多云、跨 VPC 部署时,内网无法直接回调企业微信,你会用 CEN、云企业网还是公网 NAT?如何保障出口 IP 固定以满足企业微信 IP 白名单?
  3. 失败卡片跳转到小程序后,用户点击「重跑」按钮,小程序如何调用 Airflow REST API?你会用 JWT + OpenAPI 网关 还是 短期 OAuth2 Token 来鉴权?
  4. 对于小时级高频任务,失败卡片可能 1 分钟推送上百条,如何基于 Redis Bloom Filter 实现「5 分钟内同类异常聚合」?
  5. 如果未来 Airflow 升级至 3.0,Listener 插件模型改为 Event Driven,你会如何重构现有回调,使其支持异步消息队列(Kafka/Pulsar)而不阻塞任务线程?