Skip to content

C 用配置结构体和回调上报状态变化 ​

传入两条规则,连续失败 2 次才告警,连续成功 3 次才恢复。每次状态改变同步调用一次回调。可以为两个实例共用回调函数,并用各自的 context 把事件写到不同地方。

沿执行路径读代码 ​

  1. health_init() 检查阈值大于 0,成功后按值复制 HealthConfig。调用者可以随后修改原配置,已经创建的实例保留各自的配置。回调和 context 的指针值被复制,context 指向的对象需要在回调执行时有效。
  2. health_record() 收到一次结果。若结果与当前健康状态一致,就清掉反方向的连续计数。达到另一个状态的阈值后,先更新状态和计数,再带着 context 调用 on_change。空回调仍会更新状态。
  3. record_change() 把 context 转成 EventLog *。同样的函数分别写两个实例自己的日志。调用者串行提交结果,回调不再次调用同一实例。

完整源码 ​

下载 main.c

c
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>

typedef void (*HealthChanged)(void *context, bool unhealthy);

typedef struct
{
  unsigned failures_to_alarm, successes_to_clear;
  HealthChanged on_change;
  void *context;
} HealthConfig;

typedef struct
{
  HealthConfig config;
  unsigned streak;
  bool unhealthy;
} HealthMonitor;

// 阈值以连续轮数计且必须大于 0。失败时不改 monitor。context 在通知期间必须有效。
static bool health_init(HealthMonitor *monitor, const HealthConfig *config)
{
  if (monitor == NULL || config == NULL ||
      config->failures_to_alarm == 0U || config->successes_to_clear == 0U)
  {
    return false;
  }
  *monitor = (HealthMonitor){.config = *config};
  return true;
}

// 接收一次操作的成功或失败。由同一任务串行调用,回调不重入本实例。
static void health_record(HealthMonitor *monitor, bool ok)
{
  // 1. 当前健康时累计失败,已告警时累计成功。输入与当前状态一致时清零。
  const bool unhealthy_now = !ok;
  if (unhealthy_now == monitor->unhealthy)
  {
    monitor->streak = 0U;
    return;
  }
  const unsigned threshold = monitor->unhealthy ?
    monitor->config.successes_to_clear : monitor->config.failures_to_alarm;
  if (++monitor->streak < threshold) { return; }

  // 2. 先切换状态、清计数,再同步调用可选回调。后续相同输入不会重复报告。
  monitor->unhealthy = unhealthy_now;
  monitor->streak = 0U;
  if (monitor->config.on_change != NULL)
  {
    monitor->config.on_change(monitor->config.context, monitor->unhealthy);
  }
}

typedef struct
{
  unsigned calls;
  bool last_unhealthy;
} EventLog;

static void record_change(void *context, bool unhealthy)
{
  EventLog *log = context;
  log->last_unhealthy = unhealthy;
  ++log->calls;
  puts(unhealthy ? "alarm" : "recovered");
}

int main(void)
{
  // 1. 两个实例接同一回调,各自传入自己的日志。修改局部配置不影响已初始化的实例。
  EventLog first = {0}, second = {0};
  HealthConfig config = {.failures_to_alarm = 2U, .successes_to_clear = 3U,
                        .on_change = record_change, .context = &first};
  HealthMonitor sensor, link;
  if (!health_init(&sensor, &config)) { return 1; }
  config.failures_to_alarm = 1U;
  config.context = &second;
  if (!health_init(&link, &config)) { return 1; }

  // 2. 连续两次失败只报告一次。另一实例独立计数,读取不到 sensor 的状态。
  health_record(&sensor, false);
  assert(first.calls == 0U && second.calls == 0U);
  health_record(&link, false);
  assert(first.calls == 0U && second.calls == 1U && second.last_unhealthy);
  health_record(&sensor, false);
  health_record(&sensor, false);
  assert(first.calls == 1U && first.last_unhealthy);

  // 3. 错误配置不能覆盖已有实例。中途一次失败打断“两次成功”的恢复计数。
  config.successes_to_clear = 0U;
  if (health_init(&sensor, &config)) { return 1; }
  assert(sensor.unhealthy && sensor.config.context == &first);
  health_record(&sensor, true);
  health_record(&sensor, true);
  health_record(&sensor, false);
  health_record(&sensor, true);
  health_record(&sensor, true);
  assert(first.calls == 1U);
  health_record(&sensor, true);
  assert(first.calls == 2U && !first.last_unhealthy && second.calls == 1U);

  // 4. 暂时没有事件接收者时,可传空回调并直接读取状态。
  config.successes_to_clear = 1U;
  config.on_change = NULL;
  config.context = NULL;
  HealthMonitor silent;
  if (!health_init(&silent, &config)) { return 1; }
  health_record(&silent, false);
  assert(silent.unhealthy);
  health_record(&silent, true);
  assert(!silent.unhealthy);
  puts("health callbacks: copied config, isolated context, alarm and recovery");
  return 0;
}

编译和观察 ​

在仓库根目录执行。需要本机 GCC。

powershell
New-Item -ItemType Directory -Force .work | Out-Null
gcc -std=c11 -Wall -Wextra -Werror -pedantic examples/c/health-callback/main.c -o .work/health-callback.exe
& ./.work/health-callback.exe

输出两次 alarm,分别来自链路和传感器,随后打印一次 recovered。自测另外检查非法配置失败后保留原状态、连续成功中断后重计以及空回调行为。

练习 ​

预测题 当前已告警,接着收到「成功、成功、失败、成功」。能恢复吗?

核对预测

仍处于告警。失败把前两次成功清零,最后一次成功重新计到 1,距离恢复还差连续两次成功。

改动题 令传感器也在第一次失败时报错,保持链路使用原来的独立日志。

核对改法

传给传感器的 failures_to_alarm 改为 1,并更新第一条记录后的断言。现在第一次调用 health_record(&sensor, false) 会使 first.calls 为 1,second.calls 仍为 0。随后给链路提交一次失败,second.calls 才变成 1。

验证记录 ​

使用 Windows MSYS2 UCRT64 GCC 15.2.0,以 -O2 -Wall -Wextra -Werror -pedantic 编译并运行。输出两次 alarm 和一次 recovered,自测通过。