第五章-科举考场EventBus - 会试放榜事件传播

76 阅读3分钟

殿试黄榜架构(类结构设计)

class ImperialExaminationEventBus {
  // 三级事件缓存机制
  _eventRegistry = new Map()       // 正榜登记处(常规订阅)
  _expressChannels = new Set()     // 加急榜通道(通配符*)
  _emergencyPigeons = new WeakMap()// 密奏系统(Symbol事件)
  
  constructor(config) {
    this.maxListeners = config?.maxListeners || 20 // 科场容纳上限
    this._courierSystem = this._initCouriers()     // 启动驿马调度
  }
}
// 示例:创建带容量的通信网络
const examBus = new ImperialExaminationEventBus({
  maxListeners: 50, // 最多同时监听的考生数
  timeout: 5000     // 放榜超时时间
})

考生报名全流程(订阅机制增强)

多级事件注册

// 户籍分级订阅(命名空间)
eventBus.on('江南省/苏州府/吴县', scholarCallback)
// 通识事件订阅(正则匹配)
eventBus.on(/^癸卯.*/, generalCallback)
// 密字事件订阅(Symbol保密)
const 暗榜事件 = Symbol('舞弊调查')
eventBus.on(暗榜事件, imperialGuardHandler)

权重登记系统

// 高优先级考生(权重值)
function registerWithPriority(event, callback, priority) {
  const wrapper = { callback, priority }
  const listeners = [...eventBus._eventRegistry.get(event)]
  listeners.push(wrapper)
  listeners.sort((a,b) => b.priority - a.priority)
  eventBus._eventRegistry.set(event, new Set(listeners))
}
// 用例:主考官优先接收消息
registerWithPriority('放榜', chiefExaminer, 10)

放榜流程优化(事件触发增强)

异步发榜机制

async emitAsync(eventName, ...args) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const results = []
      this._eventRegistry.get(eventName).forEach(cb => {
        results.push(cb.apply(null, args))
      })
      resolve(results)
    }, 0)
  })
}
// 用例:异步等待所有考生查阅
await examBus.emitAsync('殿试结果', finalList)

区域限流策略

// 按省份限流执行
function throttleByProvince(province, callback) {
  let lastCall = 0
  return (...args) => {
    const now = Date.now()
    if (now - lastCall > 1000) {
      console.log(`【${province}】榜房开启`)
      callback(...args)
      lastCall = now
    } else {
      console.warn(`${province}考生请勿拥挤`)
    }
  }
}
// 应用:江南省考生分批次查阅
eventBus.on('放榜', throttleByProvince('江南省', jiangnanHandler))

落榜善后体系(错误处理机制)

试卷复查管道

// 错误拦截中间件
function createErrorPipeline(callback) {
  return async (...args) => {
    try {
      await callback(...args)
    } catch (e) {
      console.error(`考生申诉:${e.message}`)
      eventBus.emit('复核请求', {
        examinee: callback.name,
        error: e.stack
      })
    }
  }
}
// 注册安全回调
eventBus.on('放榜', createErrorPipeline(unstableScholar))

分布式复核系统

// 多级复核机制
eventBus.on('复核请求', async (caseInfo) => {
  // 州府初审
  const preResult = await countyReview(caseInfo)
  
  // 行省复审
  if (preResult.controversial) {
    await provinceReview(caseInfo)
  }
  // 京城终审
  eventBus.emit('三司会审', caseInfo)
})

科场监控体系(调试工具)

锦衣卫监察模块

class EventBusInspector {
  static audit(eventBus) {
    return {
      activeEvents: [...eventBus._eventRegistry.keys()],
      totalListeners: [...eventBus._eventRegistry.values()]
                         .reduce((sum, set) => sum + set.size, 0),
      memoryUsage: `${JSON.stringify(eventBus).length / 1024}KB`
    }
  }
}
// 随时审查通信网
console.log(EventBusInspector.audit(examBus))

考场沙盘推演

// 测试用例集
describe("会试放榜流程", () => {
  test("状元消息应走八百里加急", () => {
    const mockExpress = jest.fn()
    examBus._expressChannels.add(mockExpress)
    
    examBus.emit('放榜', ['张居正'])
    expect(mockExpress).toHaveBeenCalledWith('放榜', ['张居正'])
  })
  test("落榜生应在三日后除名", async () => {
    const tempHandler = () => {}
    examBus.once('副榜', tempHandler)
    await new Promise(r => setTimeout(r, 3000))
    expect(examBus._eventRegistry.get('副榜')).not.toContain(tempHandler)
  })
})

科场百年演进(架构升级方案)

事件类型诏书(TypeScript增强)

type ImperialEvents = {
  '会试放榜': string[],
  '殿试策问': { topic: string; duration: number },
  [Symbol('密折')]: (securityLevel: number) => void
}
class TypedEventBus extends EventBus {
  emit<T extends keyof ImperialEvents>(
    event: T, 
    payload: ImperialEvents[T]
  ) {
    super.emit(event, payload)
  }
}
// 示例:类型安全的放榜
const typedBus = new TypedEventBus()
typedBus.emit('会试放榜', ['徐阶', '高拱']) // 合法
typedBus.emit('会试放榜', 123) // 编译报错

跨省通信驿站(多总线模式)

// 创建区域事件总线
const 江南驿站 = examBus.createScope('江南')
const 西北驿站 = examBus.createScope('西北')
// 跨域消息传递
江南驿站.on('旱情警报', (severity) => {
  西北驿站.emit('调粮请求', severity * 1000)
})


(臣再奏:此架构已含十二项科举制度改良——

  1. 三级事件缓存对应县试、乡试、会试三级科考
  2. 异步发榜如驿站快慢不同的驿马
  3. 错误管道似考生申诉复核流程
  4. 类型诏书类比礼部颁发的科场条例
  5. 沙盘推演如同科考前模拟测试
  6. 权重登记对应举人出身等级制度
    ...(余下六项略)
    然技术如科举,需与时俱进。建议:
  • 采用RxJS如设立六科给事中监管事件流
  • 引入WebSocket如开通海运加急通道
  • 使用Worker如训练八百里加急驿卒
    方可应对现代前端之复杂场景!)