三层服务架构与消息总线:40 个分派组合里 20 个静默失败,以及没有序号的总线如何把一次操作执行两次

4 阅读27分钟

三层服务架构与消息总线:40 个分派组合里 20 个静默失败,以及没有序号的总线如何把一次操作执行两次

「三层」这个词最容易被滥用

每个系统都说自己有三层。但「三层」到底指什么,往往没人说得清:

  • 表现层 / 业务层 / 数据层?(Web 架构)
  • 接入层 / 逻辑层 / 存储层?(后端架构)
  • 应用层 / 中间件层 / 驱动层?(嵌入式)
  • 协议层 / 服务层 / 业务层?(通信设备)

同一个词指四种不同的切法。 混乱的根源是:分层应该按「变化的原因」切,但大多数时候是按「代码放的目录」切。

现网框架的服务层用的是第三种切法的变体:按「消息的处理类别」切。

switch (calcd_get_current_service_class())
{
    case CLASS_1:
        switch (ftype) { ... }
        break;
    case CLASS_2:
        switch (ftype) { ... }
        break;
    default:
        return UNKNOW_ERROR;
}

class × type 二维分派。这个结构看起来简单,但它决定了整个消息总线的行为。

本文实测四件事,其中两件的结果相当刺眼:

  • 40 个 (class, type) 组合里,20 个返回「成功」但什么都没做
  • 一次逻辑操作,因为超时重传,被实际执行了两次

消息编号:一个 U32 装四个字段

先看编号规则。消息类型形如 0x12 XX YY ZZ:

the 32 bit id, bit by bit:

  0x12 | XX | YY | ZZ
  ^^^^   ^^   ^^   ^^
  tag   src  dst  type
  [31:24][23:16][15:8][7:0]

  tag  0x12 is constant: every message starts with it
  src  XX = source module id      (group local)
  dst  YY = destination module id (group local)
  type ZZ = message type inside the (src,dst) pair

四个字段:

位段字段含义
[31:24]tag固定 0x12,标识「这是服务层消息」
[23:16]src源模块号
[15:8]dst目的模块号
[7:0]type这对模块之间的第几种消息

解码实测:

the 13 declared ids, decoded:
  name                 id         tag  src  dst   type     channel
  --------------------- ---------- ---- ---- ----- -------- --------
  OSP_MSG_CTL_PING     0x12421a01  0x12  0x42  0x1a  0x01    0x421a
  OSP_MSG_PWR_REPLY    0x121a4202  0x12  0x1a  0x42  0x02    0x1a42
  OSP_MSG_CTL_SET      0x12423303  0x12  0x42  0x33  0x03    0x4233
  OSP_MSG_SNS_DATA     0x12334204  0x12  0x33  0x42  0x04    0x3342
  OSP_MSG_LOG_WRITE    0x12084205  0x12  0x08  0x42  0x05    0x0842
  OSP_MSG_CTL_LOGREQ   0x12420806  0x12  0x42  0x08  0x06    0x4208
  OSP_MSG_FLT_REPORT   0x12554207  0x12  0x55  0x42  0x07    0x5542
  OSP_MSG_CTL_FLTREQ   0x12425508  0x12  0x42  0x55  0x08    0x4255
  OSP_MSG_PWR_SNSREQ   0x121a3309  0x12  0x1a  0x33  0x09    0x1a33
  OSP_MSG_SNS_PWRREP   0x12331a0a  0x12  0x33  0x1a  0x0a    0x331a
  OSP_MSG_LOG_FLTREQ   0x1208550b  0x12  0x08  0x55  0x0b    0x0855
  OSP_MSG_FLT_LOGREP   0x1255080c  0x12  0x55  0x08  0x0c    0x5508
  OSP_MSG_GRP2_PING    0x12421a01  0x12  0x42  0x1a  0x01    0x421a

这个编码的好处:从编号反推对端

--- reconstructing the peer pair from the id alone ---
  a receiver sees only the 32 bit number, yet it can name
  both ends of the conversation:

  0x12421a01 -> CTL(src) --> PWR(dst), type 0x01
  0x121a4202 -> PWR(src) --> CTL(dst), type 0x02
  0x12423303 -> CTL(src) --> SNS(dst), type 0x03

只看到一个 32 位数字,就能说出「谁发给谁、这是第几种消息」。 这对排障极有价值:日志里一行十六进制,就能还原出通信关系。

而且请求和应答天然成对:

方向编号关系
CTL → PWR, type 0x010x12421a01请求
PWR → CTL, type 0x020x121a4202应答

src 和 dst 交换,type 加一。编号本身编码了「回给谁」。

但这个编码有个致命前提

src / dst 是「组内局部编号」。

  group 1:  CTL=0x42  PWR=0x1a  SNS=0x33  LOG=0x08  FLT=0x55
  group 2:  CTL=0x42  PWR=0x1a  SNS=0x33  LOG=0x08  FLT=0x55
            (identical numbering, different physical modules)

  group 1's CTL -> PWR ping is  0x12421a01
  group 2's CTL -> PWR ping is  0x12421a01
  the two numbers are the same to the last bit

两个组用同一套局部编号,于是同一个 32 位数字代表两条不同的消息。

而最后一行 OSP_MSG_GRP2_PING 的 id 和第一行完全相同——这不是笔误,是真实的重复声明。

缺陷一:重复的消息编号,编译器一句话不说

enum osp_msg_id {
    OSP_MSG_CTL_PING     = 0x12421a01,   /* group1 */
    ...
    OSP_MSG_GRP2_PING    = 0x12421a01    /* group2 */
};

两个枚举项同值,在 C 里完全合法。 编译器没有任何意见。

two enumerators with the same value are perfectly legal C.
The compiler has nothing to complain about, so the clash only
surfaces when the two messages meet in one dispatch table.

运行时扫描才能发现(排序后比较相邻):

the runtime scan that DOES find it (sort by id, compare neighbours):
  name                 id         name
  -------------------- ---------- --------------------
  OSP_MSG_CTL_PING     0x12421a01 OSP_MSG_GRP2_PING     <== DUPLICATE

  duplicate ids found : 1
  duplicate pairs     : 1

但运行时扫描太晚了。 它:

  • 每次启动跑一遍,浪费启动时间
  • 只能看到编译期声明的 id(运行时生成的看不到)
  • 不能阻止构建——代码已经进设备了

一行 _Static_assert 就够了

_Static_assert(OSP_MSG_CTL_PING != OSP_MSG_GRP2_PING,
               "OSP message id 0x12421a01 is declared twice");

实测两次编译:

  --- build WITHOUT the assertion (must succeed) ---
    | gcc -O2 -c e30_bus.c -o e30_probe_ok.o   ->  exit=0

  --- build WITH the assertion (must fail) ---
    | e30_bus.c:180:1: error: static assertion failed: "OSP message id 0x12421a01 is declared twice: OSP_MSG_CTL_PING and OSP_MSG_GRP2_PING"
    | gcc -O2 -DE30_UNIQUENESS_PROBE -c e30_bus.c -o e30_probe_fail.o   ->  exit=1

Cost of the check: one compile time comparison per id pair.
Cost of not having it: a message routed to the wrong handler.

代价:一行代码、零运行时开销。收益:所有编号冲突在构建时暴露。

对于上百个消息类型的系统,这个 _Static_assert 列表会很长。更优雅的做法是用 X-Macro 或代码生成:

/* msg_ids.def —— 唯一的编号定义处 */
MSG_ID(CTL_PING,    0x12421a01)
MSG_ID(PWR_REPLY,   0x121a4202)
...

/* 生成枚举 */
#define MSG_ID(name, id) MSG_##name = id,
enum osp_msg_id { 
#include "msg_ids.def"
};
#undef MSG_ID

/* 生成唯一性检查(排序后两两比较) */
#define MSG_ID(name, id) +1
enum { MSG_COUNT = 0 
#include "msg_ids.def"
};
#undef MSG_ID

或者更简单——写一个 Python/awk 脚本在构建前扫一遍头文件。比手写 N² 个断言实际得多。

缺陷二:同一个编号,三种分派策略,两种失效

有了重复编号,接下来看分派表怎么处理它。实验对比了三种策略。

同一组编号出现在两个组,每个组各发 100 条消息,统计「路由到自己的处理器」的比例。

策略 A:一个全局表,后注册覆盖前注册

policy A: one global table keyed by the full 32 bit id,
          a second registration overwrites the first slot

  after both registrations the table holds:
    slot 0: id 0x12421a01 -> handler of group 2
  the group 1 handler was overwritten in slot 0.

  group 1 messages: 0 right, 100 MISROUTED
  group 2 messages: 100 right, 0 MISROUTED, 0 lost

1 组 100 条全部误路由。 而且:

  • 没有任何错误返回(注册「成功」了)
  • 没有任何告警
  • 1 组的消息被 2 组的处理器处理——拿到的是别人的数据

策略 B:同样一张表,重复注册被拒绝

policy B: the same table, but the duplicate registration is
          rejected with -EEXIST

  group 2's registration was rejected (-EEXIST)
  group 1 messages: 100 right, 0 MISROUTED
  group 2 messages: 0 right, 100 MISROUTED, 0 lost
  the clash is now loud at registration time, but group 2 is
  completely dead

失败变响亮了(注册时返回 -EEXIST),但 2 组整个死掉。

而且注意「0 lost」——2 组的消息没有丢,是被 1 组的处理器处理了。这比丢更糟:错误的处理器拿到了正确的数据,可能产生完全错误的副作用。

策略 C:按组作用域查表

policy C: a per group channel table keyed by (src,dst),
          so the group scopes the lookup

  group 1 messages: 100 right, 0 MISROUTED
  group 2 messages: 100 right, 0 MISROUTED, 0 lost

  the channel number that policy C keys on: 0x421a = (src 0x42, dst 0x1a)
  it is scoped by the group, the full id is not.

两个组、同样的编号、零误路由。

关键变化:查表的键从「完整 32 位 id」变成「(组, src, dst)三元组」。

  KEY RESULT: the same numeric id in two groups gives
    policy A (overwrite) : group 1 misrouted 100/100, group 2 misrouted 0/100
    policy B (reject)    : group 1 misrouted 0/100, group 2 misrouted 100/100
    policy C (per group) : group 1 misrouted 0/100, group 2 misrouted 0/100
策略1 组误路由2 组误路由判定
A 覆盖100/1000/100静默错
B 拒绝0/100100/100响亮错
C 按组作用域0/1000/100正确

教训

「编号唯一」和「编号在作用域内唯一」是两件事。

  • 如果设计上允许「组内局部编号」,那查表必须带组作用域
  • 如果查表只用全局 id,那编号必须全局唯一

源码的做法是「组内局部编号 + 全局查表」——两个假设互相矛盾。

_Static_assert 能在构建时抓到冲突(这是最便宜的),但如果设计上就需要两个组用同样的编号,那正确的做法是策略 C:改查表的键。

缺陷三:没有序号,62% 的应答配错请求

这是总线设计里最根本的一个决定:应答怎么和请求对上?

源码的消息头:

typedef struct tag_osp_msg_head
{
    U16 msg_size;
    U16 msg_type;
    U32 msg_id;
    U32 seq;
    U32 timestamp;
} osp_msg_head;

有 seq 字段——但实验里的模型和实际用法都表明,配对靠的是 msg_type,不是 seq。

为什么会配错

客户端发 5 个同类型的请求,服务端用 3 个工作线程并发处理,每个有不同的处理延迟。应答回来的顺序和请求发出的顺序不一致。

如果客户端按 FIFO 顺序配对(「第一个回来的应答对应第一个请求」):

configuration: 200 trials x 5 concurrent requests = 1000 responses

-- variant A: the reply carries NO correlator --
  responses                : 1000
  responses misassigned     : 622  (62.20%)
  trials with >=1 mismatch  : 186 of 200  (93.00%)

-- variant B: the reply carries the sequence number --
  responses                : 1000
  responses misassigned     : 0  (0.00%)
  trials with >=1 mismatch  : 0 of 200  (0.00%)
无关联符带序号
误配应答622 / 1000(62.20%)0 / 1000(0%)
出错试验186 / 200(93.00%)0 / 200(0%)

93% 的试验至少有一次配错。

测得的 62% 比理论值低,为什么

  the model: if the completion order were a uniformly random
  permutation of 5 requests, the expected number of responses
  that land on the right request is 1, so the per response
  mismatch rate would be 80% and a trial would be clean only
  1/5! = 0.8333% of the time.
  measured variant A: 62.20% per response, 93.00% per trial.
  The measurement is BELOW the uniform-permutation model because
  3 workers cannot shuffle 5 requests into every possible
  order -- the ordering is only partially random.

3 个工作线程无法把 5 个请求排成任意顺序(只有 3 个并发度),所以乱序程度低于「完全随机排列」。实测 62.20% 低于理论 80%,但量级一致:没有关联符时,误配是「大多数」而不是「少数」。

什么时候会踩到

只要同时有 2 个以上同类型请求在飞,就会错。

  • 单个请求串行发(发→等→收)→ 不出问题
  • 两个请求并发(比如 UI 上连点两次按钮)→ 开始错
  • 定时轮询 + 用户操作并发 → 经常错

而且错的表现是「数据看起来合理但不对应」:

  • 请求 A 问「温度」,请求 B 问「湿度」
  • 应答 A(温度值 25)被配给请求 B → 湿度 = 25
  • 值在合理范围内,看不出异常

缺陷四:超时重传,一次操作执行两次

这个比配错应答更严重。

场景

  • 客户端超时 120 ms
  • 服务端处理需要 400 ms
  • 客户端超时后重传,原请求不取消
  • 服务端没有去重

事件时间线

       0.0 ms  client: sending request #1 (logical operation #1)
     121.5 ms  client: TIMEOUT after 120 ms, retransmitting
     415.8 ms  server: finished request #1, sending reply #1
     415.8 ms  client: reply #1 arrived, applying the operation
     820.6 ms  server: finished request #2, sending reply #2
     820.6 ms  client: reply #2 arrived, applying the operation

  logical operations requested : 1
  operations actually applied   : 2

一次逻辑操作,执行了两次。

  the operation ran 2 times.  On a control path that is a
  double actuation, not a duplicated log line.

这不是「日志重复」级别的问题

操作类型执行两次的后果
查询状态无害(幂等)
记录日志多一条记录
设置寄存器幂等,无害
累加计数计数翻倍
发脉冲/触发一次动作执行了两次物理动作
扣款/记账资金损失

osp_timer_create_to_task + CALCD_RTVR_MAX_RETRY_ATMPT(重传次数上限),说明源码有重传机制。但有重传没去重,就是「至少一次」(at-least-once)语义——必须配合幂等或去重才能正确。

加序号 + 去重缓存

-- the same run with a sequence number and a de-duplication cache --

       0.0 ms  client: sending request #1 (seq=1, logical operation #1)
     121.4 ms  client: TIMEOUT after 120 ms, retransmitting (same seq=1)
     401.5 ms  server: finished request #1, sending reply #1
     401.6 ms  client: reply for seq=1, applying the operation
     804.5 ms  server: finished request #2, sending reply #2
     804.6 ms  client: reply for seq=1 again, DROPPED by the dedup cache

  operations applied with the sequence number: 1

  the extra round trip is still paid -- the timeout, the
  retransmission and the late first reply all still happen --
  but the operation is applied once.

关键:重传还在发生,网络开销没省,但操作只执行一次。

这就是「至少一次传输 + 恰好一次语义」的标准做法:

  • 传输层可以重传(保证不丢)
  • 应用层用序号去重(保证不重复执行)

两者缺一不可。

去重缓存的三个设计点

  1. 缓存放什么:(src, seq) 二元组,或者 (src, msg_type, seq)

  2. 缓存多大:至少覆盖「一个重传窗口内可能出现的最大在飞请求数」。太小会误判(旧请求被当成新的),太大浪费内存

  3. 什么时候清:按时间过期(比如 2 × 超时时间),不要按数量滚动——按数量滚动会在突发时把还没过期的条目挤掉

    struct dedup_entry { u32 src; u32 seq; u64 first_seen_ms; };

    /* 收到请求时 / if (dedup_lookup(src, seq, now_ms) != NULL) { / 重复请求:重发上次的应答,不重新执行 */ resend_cached_reply(src, seq); return; } dedup_insert(src, seq, now_ms); execute_operation();

注意「重发上次的应答」这一步——不是简单丢弃。否则客户端拿不到应答,会一直重传。

缺陷五:msg_size 一个词,三种解释

源码的消息体是双层头:

  +0                +16           +28                    +128
  | osp_msg_head   | csp_header  | payload              |
  | 16 bytes        | 12 bytes      | 100 bytes             |

编译器分配的偏移:

  struct osp_msg_head  (sizeof = 16)
    field          offset size
    msg_size       0      2
    msg_type       2      2
    msg_id         4      4
    seq            8      4
    timestamp      12     4
  struct csp_msg_header (sizeof = 12)
    field          offset size
    msg_class      0      2
    msg_type       2      2
    msg_size       4      2
    flags          6      2
    seq            8      4

  no padding: 16 + 12 = 28 bytes of header.

两个头都有一个叫 msg_size 的字段,语义不同。

--- the same word, two meanings ---
  osp_msg_head.msg_size   = 100   (the payload length)
  csp_msg_header.msg_size = 112   (the payload PLUS the 12 byte csp header)
  the two values differ by exactly 12 bytes = sizeof(csp_msg_header).

差 12 字节。而接收方要算 payload 指针:

  payload = (char *)frame + 16 + 12;      /* 正确:两层头都跳过 */
  payload = (char *)frame + 16;           /* 错误:把 csp 头当成 payload */

实测的越界读

MinGW 没有可用的 SIGSEGV 处理,所以实验在子进程里做真实越界读——帧结尾正好在页边界,下一页是 PAGE_NOACCESS:

    [child] read 100 payload bytes, sum=1700, SURVIVED
  reading 100 payload bytes at frame + 28 : child exit 0x00000000  no fault, inside the frame
  reading 104 payload bytes at frame + 28 : child exit 0xC0000005  STATUS_ACCESS_VIOLATION -> read past the end
  reading 108 payload bytes at frame + 28 : child exit 0xC0000005  STATUS_ACCESS_VIOLATION -> read past the end
  reading 112 payload bytes at frame + 28 : child exit 0xC0000005  STATUS_ACCESS_VIOLATION -> read past the end

  the frame is 128 bytes and the payload starts at +28, so a
  100 byte payload ends exactly at the page boundary.
  Reading 112 bytes instead of 100 overreads by 12 bytes and
  lands on the unmapped page.  The fault is REAL: it is the
  operating system killing the process, not a checksum.

读 100 字节安全,读 112 字节触发 STATUS_ACCESS_VIOLATION。 0xC0000005 是操作系统杀进程,不是软件检测——这是真崩溃。

第三种解释:msg_size 当总长度

--- the third interpretation: msg_size as the total length ---
  if the receiver treats osp_msg_head.msg_size = 100 as the
  TOTAL frame length, the payload it believes in is
      100 - 16 - 12 = 72 bytes
  but the sender actually put 100 payload bytes in the frame, so
  28 bytes of real payload are silently dropped.

  KEY RESULT: three plausible readings of msg_size, three
  different frames: 100 bytes read correctly, 112 bytes read past
  the end of the buffer, or 72 bytes of payload silently lost.
解释结果
osp.msg_size = payload 长度✓ 正确(100 字节)
csp.msg_size = payload 长度✗ 越界读 12 字节(崩溃)
osp.msg_size = 总帧长✗ 静默丢 28 字节

同一个字段名,两种头,三种可行解释,两种出错。 而传输格式里没有任何标记告诉你该用哪个。

修法

一个字段只能有一个语义,并且在头文件里写死。

typedef struct tag_osp_msg_head
{
    U16 total_len;    /* 整个帧的长度,含所有头部。不要叫 msg_size */
    U16 msg_type;
    U32 msg_id;
    U32 seq;
    U32 timestamp;
} osp_msg_head;

typedef struct tag_csp_msg_header
{
    U16 msg_class;
    U16 msg_type;
    U16 body_len;     /* 仅业务体长度。不要叫 msg_size */
    U16 flags;
    U32 seq;
} csp_msg_header;

/* 并且提供访问器,不让人手算偏移 */
static inline void *frame_payload(void *frame)
{
    return (char *)frame + sizeof(osp_msg_head) + sizeof(csp_msg_header);
}

三条改动:

  1. 重命名:msg_size → total_len / body_len,让语义自解释
  2. 用 sizeof 而不是魔法数字 16/12:头结构变了自动跟着变
  3. 提供访问器函数,禁止手写偏移

第 3 条最重要——手算偏移永远会算错,早晚的问题。

缺陷六:20 个组合返回「成功」但什么都没做

现在回到 class × type 的二维分派。

源码结构

switch (cls) {
case CLASS_CTRL:  switch (type) { case 1: ...; case 2: ...; default: break; } break;
case CLASS_DATA:  switch (type) { case 1: ...;              default: break; } break;
case CLASS_EVENT: switch (type) { case 1: ...;              default: break; } break;
case CLASS_DIAG:  switch (type) { case 1: ...;              default: return -1; }
default: return -1;
}
return 0;          <-- reached by three of the four classes

注意最后那个 return 0。 内层 switch 的 default 分支是 break,break 之后落到底部的 return 0。

于是「不认识这个 type」被报告成「处理成功」。

实测 40 个组合

  type   CLS_1  CLS_2  CLS_3  CLS_4  CLS_U
         1      2      3      4      5
  -------+ ------ ------ ------ ------ ------
  1      0      0      0      0      -1
  2      0      0      0      -1     -1
  3      0      0      0      -1     -1
  4      0      0      0      -1     -1
  5      0      0      0      -1     -1
  6      0      0      0      -1     -1
  7      0      0      0      -1     -1
  8      0      0      0      -1     -1

  combinations            : 40
  real handlers            : 5  (CTRL x2, DATA x1, EVENT x1, DIAG x1)
  returned 0 (accepted)    : 5
  returned 0 but SILENT    : 20   <-- dropped, reported as success
  returned -1 (loud)       : 15
  handler invocations      : 5

40 个组合里只有 5 个真的调用了处理器。20 个返回 0 但什么都没做。

按 class 拆:

  the silent ones, class by class:
    class 1 : 6 of 8 type values silently dropped
    class 2 : 7 of 8 type values silently dropped
    class 3 : 7 of 8 type values silently dropped
    class 4 : 0 of 8 type values silently dropped
    class 5 : 0 of 8 type values silently dropped
class静默丢弃的 type 比例
CLASS_16/8
CLASS_27/8
CLASS_37/8
CLASS_40/8(内层用了 return -1)
CLASS_5(未知)0/8(走外层 default)

为什么这是「总线里最坏的失败模式」

  KEY RESULT: 20 of the 40 class/type combinations return 0
  without doing anything.  A caller that checks the return
  value sees SUCCESS and carries on, so the message is lost
  silently -- the worst failure mode in a bus, because nothing
  is logged and nothing crashes.

对比三种失败模式:

失败模式可发现性危害
返回错误码调用方立刻知道低
崩溃立刻知道中(但能修)
返回成功 + 静默丢弃不知道最高

静默丢弃的特征:

  • 日志里没有错误
  • 计数器里没有异常
  • 调用方以为成功了
  • 症状在几小时/几天后才以「某个功能不生效」的形式出现

而 CLASS_4(诊断类)反而做对了——内层 default 是 return -1。同一份代码里,一个 class 做对,三个 class 做错。

修法

switch (cls) {
case CLASS_CTRL:
    switch (type) {
    case 1: ...; return 0;
    case 2: ...; return 0;
    default: return -ENOTSUP;      /* ← 不要 break */
    }
case CLASS_DATA:
    switch (type) {
    case 1: ...; return 0;
    default: return -ENOTSUP;
    }
...
default:
    return -EINVAL;
}

三个改动:

  1. 每个内层 default 都 return -ENOTSUP,不要 break 落到成功路径
  2. 每个 case 都显式 return 0,不依赖落到底部
  3. 外层 default 返回 -EINVAL,区分「class 不认识」和「type 不支持」

-ENOTSUP 和 -EINVAL 分开很重要:

  • -EINVAL = 「你发的消息我根本不认识」(版本不匹配?)
  • -ENOTSUP = 「这个 class 我认识,但这个 type 还没实现」(功能缺失)

两个错误码指向完全不同的排查方向。

还有一个「未实现的 class」

源码的 class 枚举里有 CLASS_3,但 svc_class3.c 从未存在——预留了位置,没实现。

而 CLASS_3 落进了 case CLASS_3: switch (type) { case 1: ...; default: break; } 这条路径(实验里对应 CLS_3),7/8 的 type 静默丢弃。

「预留但未实现」的 class 应该直接返回 -ENOTSUP,而不是走一条「看起来已实现」的分派路径。

缺陷七:路由热路径——键的「密度」决定成本

最后看性能。12 条路由,100 万次查找,5 次重复取最快值:

  variant                 best of N      ns/call   checksum
  ---------------------- ---------- ------------ ----------
  switch (sparse id)           3.9 ms        3.91   32564904
  if/else chain                4.0 ms        3.96   65129808
  switch (dense key)           2.9 ms        2.86   97694712
  hash table lookup            3.7 ms        3.74   130259616

  relative cost against the fastest (switch (dense key)):
  variant                   ratio
  ---------------------- --------
  switch (sparse id)        1.37x
  if/else chain             1.38x
  switch (dense key)        1.00x
  hash table lookup         1.31x
  fastest / slowest         1.38x

关键结论:成本由「键的密度」决定,不是「用哪个构造」

  3. The switch over the SPARSE ids costs 1.37x the dense
     switch (3.91 vs 2.86 ns/call).  Same 12 routes, same
     switch construct, only the key differs -- so the cost is
     the SPARSITY of the key, not the switch itself.  gcc
     turns a dense key into a jump table; a sparse key forces
     a comparison tree whose branches the predictor cannot
     learn from the data.

同样的 12 条路由、同样的 switch、只换键——成本差 1.37 倍。

原因:

  • 密集键 → gcc 生成跳转表(一次索引 + 一次间接跳转)
  • 稀疏键 → gcc 生成比较树(多次比较 + 分支预测)

源码的消息 id 是 0x12421a01 这种极度稀疏的值——switch (msg_type) 必然是比较树。

  the three levels, as the compiler sees them:
    level 1  switch(class)   : up to 6 comparisons
    level 2  switch(type)    : up to 9 comparisons
    level 3  the handler     : 1 call
    worst case branch tests  : 16

最坏 16 次分支测试才走到处理器。

但也必须给出诚实的边界

  2. The FASTEST is the switch (dense key) at 2.86 ns/call; the SLOWEST is
     1.38x that.  The whole spread on this host is 1.38x --
     small, because the host is shared and the noise floor is
     the same order as the effect being measured.

  the honest caveat is on the table above:
  the measured spread here is only 1.38x, and on a machine
  that is not shared it would be larger.  The direction of the
  effect is consistent across runs, the magnitude is not, and
  this experiment is reported with that uncertainty attached.

1.38 倍的差距很小,因为主机是共享的,噪声水平和效应量同量级。

方向和量级要分开说:

  • 方向可靠:密集键更快(跳转表 vs 比较树),多次运行一致
  • 量级不可靠:1.38 倍是这台共享主机的数字,独占机器上可能更大也可能更小

不能拿这个数字去论证「必须改成密集键」——只能说「密集键有利于生成跳转表」,这是编译器行为的定性结论。

hash 表为什么没赢

  5. The hash table costs 1.31x the dense switch: the lookup is
     one multiply, one shift, one load and one probe, but the
     probe is a memory access whose result the predictor
     cannot predict.

hash 查找比密集 switch 慢 1.31 倍。

hash 的开销是「一次乘法 + 一次移位 + 一次内存访问」。而密集 switch 的跳转表也是「一次索引 + 一次内存访问」——hash 多了一次乘法移位,没有优势。

hash 表在路由数量大(几百上千)时才划算,因为那时 switch 的比较树会退化成长链。

真正有价值的结论

  the practical conclusion: the routing KEY decides the cost.
  A dense route key turns the hot path into one indexed load.
  That is a change in WHAT the router is keyed on, not a
  tuning trick.

「改键」是设计变更,「改构造」是微优化。

如果消息 id 从 0x12 SS DD TT 改成「一个从 0 开始的密集序号 + 一张映射表」,路由就能变成跳转表。代价是失去「从 id 反推对端」的能力(P30 开头那个好处)。

这是个真实的权衡,不是免费的优化。

七处缺陷汇总

#位置缺陷后果
1编号枚举重复 id,无编译期检查静默冲突
2分派表全局 id 键 + 组内局部编号100% 误路由
3消息头应答无关联符(seq 未用)62% 应答配错
4重传机制有重传无去重一次操作执行两次
5双层头两个 msg_size 三种解释越界读 / 静默丢数据
6二维分派内层 default: break 落到 return 020/40 组合静默成功
7路由键稀疏 id 强制比较树最坏 16 次分支测试

排序:第 3、4、6 是「功能性错误」(数据错、操作错、消息丢),第 2、5 是「结构性错误」(会崩或错),第 1、7 是「工程性问题」。

一套可用的消息总线设计

把上面所有教训收成一份设计:

/* ---------- 1. 编号:唯一、可检、可反推 ---------- */
/* 用 X-Macro 保证单一来源 + 唯一性检查 */
#define MSG_ID(name, id)  MSG_##name = (id),
enum osp_msg_id {
#include "msg_ids.def"
};
#undef MSG_ID

/* 构建期唯一性检查(由脚本生成,或手写 N^2 断言) */
_Static_assert(MSG_CTL_PING != MSG_CTL_SET, "duplicate msg id");

/* ---------- 2. 消息头:字段语义单一、有 seq ---------- */
typedef struct {
    U16 total_len;     /* 整帧长度(含所有头) */
    U16 msg_type_hi;
    U32 msg_id;
    U32 seq;           /* ★ 必须用起来 */
    U32 timestamp;
    U16 body_len;      /* 仅业务体长度 */
    U16 flags;
} msg_hdr;

/* 访问器,禁止手算偏移 */
static inline void *msg_body(void *frame)
{
    return (char *)frame + sizeof(msg_hdr);
}

/* ---------- 3. 分派:每个 default 都报错 ---------- */
int dispatch(u16 cls, u16 type, void *body)
{
    switch (cls) {
    case CLS_CTRL:
        switch (type) {
        case T_CTRL_SET:   return ctrl_set(body);
        case T_CTRL_QUERY: return ctrl_query(body);
        default:           return -ENOTSUP;   /* ★ 不 break */
        }
    case CLS_DATA:
        switch (type) {
        case T_DATA_REPORT: return data_report(body);
        default:            return -ENOTSUP;
        }
    default:
        return -EINVAL;                          /* ★ 区分 class/type */
    }
}

/* ---------- 4. 请求-应答:序号 + 去重缓存 ---------- */
static u32 g_next_seq;

u32 send_request(u32 dst, u16 type, void *body, u32 len)
{
    u32 seq = __sync_add_and_fetch(&g_next_seq, 1);
    build_and_send(dst, type, seq, body, len);
    return seq;                                  /* ★ 返回给调用方配对 */
}

/* 收到应答 */
void on_reply(u32 seq, void *body)
{
    struct pending *p = pending_find(seq);
    if (NULL == p) {
        /* 迟到的应答(重传导致的重复),丢弃 */
        return;
    }
    pending_remove(p);
    p->callback(body);
}

/* 收到请求:去重 */
void on_request(u32 src, u32 seq, void *body)
{
    if (dedup_seen(src, seq)) {
        resend_cached_reply(src, seq);           /* ★ 重发,不是丢弃 */
        return;
    }
    dedup_mark(src, seq);
    int rc = dispatch(...);
    send_reply(src, seq, rc);
}

/* ---------- 5. 分派表按键的密度设计 ---------- */
/* 若路由在热路径上:把稀疏 msg_id 映射成密集索引 */
static const u8 id_to_route[4][4] = { /* (src,dst) -> 0..15 */
    /* 表内容由启动时构建一次 */
};
int route_fast(u8 src, u8 dst, u8 type)
{
    u8 idx = id_to_route[src][dst];              /* 索引,不是比较 */
    return g_route_table[idx][type](...);
}

工程落地清单

  1. 消息编号必须唯一,且用 _Static_assert 在构建期检查。重复 enum 值是合法 C,编译器不会提醒。

  2. 「组内局部编号」和「全局查表」不能共存。要么编号全局唯一,要么查表的键带组作用域。

  3. 每条请求必须带序号,应答必须回填同一个序号。靠 msg_type 配对,在并发下 62% 会配错。

  4. 有重传就必须有去重。「至少一次」传输 + 「恰好一次」执行,两者缺一不可。

  5. 去重命中要「重发上次的应答」,不是简单丢弃。否则客户端收不到应答,会无限重传。

  6. 一个字段一个语义。msg_size 这种名字必须拆成 total_len / body_len。

  7. 头长度用 sizeof 不要写魔法数字。16、12 这种数字会随结构体变化而失效。

  8. 提供 payload 访问器函数,禁止调用方手算偏移。

  9. 二维分派的每个内层 default 都必须返回错误。break 落到 return 0 是最坏的失败模式。

  10. 区分 -EINVAL(class 不认识)和 -ENOTSUP(type 未实现)。两个错误码指向不同的排查方向。

  11. 预留但未实现的 class 直接返回 -ENOTSUP,不要走一条「看起来已实现」的分派路径。

  12. 热路径的路由键要密集。稀疏 id 强制编译器生成比较树(最坏 16 次分支测试),密集键才生成跳转表。但这是设计变更不是微优化——会失去「从 id 反推对端」的能力。

  13. 性能数据要说清方向和量级。实测 1.38 倍差距在共享主机上噪声同量级——方向可靠,量级不可靠。

附:实验环境

项值
编译器MinGW gcc 8.1.0(i686,32 位)
主机Windows,12 逻辑核(共享,噪声较高)
源码基线私有工程 platform/apps/*/service/、platform/common/hpp_msgdef.h、platform/osp_nocompile/osp_msg.h
实验程序e30_bus.c(8 节)

沙箱适配说明:

部分真实性说明
编号解码 / 分派矩阵 / 计费统计真实计算纯逻辑,与平台无关
_Static_assert 检查真实编译两次 gcc 调用,错误输出原文附上
errno 传递真实用 SetLastError + 子进程退出码
越界读真实子进程 + 页边界保护(PAGE_NOACCESS),STATUS_ACCESS_VIOLATION 是操作系统杀进程
消息总线本身模型按源码布局复刻结构与分派逻辑,未链接真实 libosp.so
性能测量真实计时但主机共享,噪声与效应同量级,已标注

如实声明:性能一节(EXP-8)的 1.38 倍差距在共享主机上噪声与效应同量级。方向(密集键更快)多次运行一致,量级不可靠。文中已明确标注这个不确定性,没有把 1.38 倍当作可推广的结论。

声明:所有产品名、模块代号、业务语义均已脱敏。文中模块名(CTL/PWR/SNS/LOG/FLT)为通用角色代号,消息编号的位段结构保留原设计以便说明问题。源码引用保留原始行号以便对照。