runtimeApi.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /**
  2. * 运行链路领域接口(票 05 只交 REST 侧的分区读取;消费方是票 15/16)。
  3. *
  4. * ADR 0005 的 `runtimeApi`:WebSocket 是运行链路,前端消费的是**版本化领域事件**,
  5. * 不把 `/ws/deviceStatus` 的裸 JSON 当依赖。本文件先交 REST 侧能落地的部分
  6. * (新鲜度、设备状态增量帧 → 领域事件的**转换**),连接与重连归票 15。
  7. *
  8. * 增量帧的字段名有个坑(调研 §1 已核实):WS 线上帧的状态键是 `data.status`,
  9. * 而后端 DTO 命名为 `monitoringState`。转换层两个键都认,避免接错一边就静默丢状态。
  10. */
  11. import { toFreshness } from '../domain/freshness.js'
  12. import { fetchSection } from './domainRequest.js'
  13. import { SECTION_STATE, section } from '../domain/sectionState.js'
  14. /**
  15. * WS 消息类型(后端 `DeviceStatusWebSocketHandler` / `DeviceStatusRedisListener`)。
  16. *
  17. * 线上形状(2026-09-28 按 ADR 0005 修订后的后端协议核实):
  18. * · 连接后**直接** `cockpitSubscribe`(`scope` 只认 `"all"`),回 `cockpitSubscribed`
  19. * (只带 `scope` 与 `serverUpdatedAt`,**不带初始状态数组** —— REST 才是初始快照);
  20. * 免鉴权:**不再要求也不发送 `authenticate` 帧**(那是管理端工单推送的机制);
  21. * · 增量帧 `cockpitDeviceStatusDelta`:`deviceCode`/`device_code`/`monitoringPointCode`
  22. * 与 `data.{status,statusTime,serverUpdatedAt,reason}` **平级在顶层**(见
  23. * `DeviceStatusRedisListener.cockpitDeltaMessage`)。`monitoringPointCode`
  24. * 未关联设备时为 `null`(显式给,不静默丢)。
  25. *
  26. * `AUTHENTICATE`/`AUTHENTICATED` 常量保留:后端协议里它们仍服务管理端工单推送,
  27. * 驾驶舱消费方(runtimeSocket)已不再使用,留作字典完整性与旧走查兼容。
  28. */
  29. export const WS_MESSAGE = {
  30. SUBSCRIBE: 'cockpitSubscribe',
  31. SUBSCRIBED: 'cockpitSubscribed',
  32. DELTA: 'cockpitDeviceStatusDelta',
  33. ORDER_DELTA: 'cockpitWorkOrderStateDelta',
  34. AUTHENTICATE: 'authenticate',
  35. AUTHENTICATED: 'authenticated',
  36. PONG: 'pong',
  37. ERROR: 'error',
  38. }
  39. /**
  40. * 设备状态增量帧 → 领域事件。
  41. *
  42. * 只做字段归一,不做取舍:是否采纳(旧消息要丢弃)由运行时服务按 `serverUpdatedAt` 判。
  43. * `monitoringPointCode` 是**点位状态联动的唯一依据**(CONTEXT.md:前端不重算点位状态,
  44. * 所以只有后端在帧里指名了点位,才允许改写那个点位的状态;没给就只更新设备维度)。
  45. * @param {object} frame WS 线上帧
  46. * @returns {object|null} 认不出的帧回 null(调用方据此忽略,不猜)
  47. */
  48. export function toDeviceStatusEvent(frame) {
  49. const raw = frame && typeof frame === 'object' ? frame : null
  50. if (!raw || raw.type !== WS_MESSAGE.DELTA) return null
  51. const payload = raw.data && typeof raw.data === 'object' ? raw.data : {}
  52. const deviceCode = raw.deviceCode || raw.device_code || payload.deviceCode || ''
  53. if (!deviceCode) return null
  54. return {
  55. deviceCode,
  56. // 后端在顶层给点位码(票 25 的 BT-1);两个位置都认,避免接错一边就静默丢联动。
  57. monitoringPointCode: raw.monitoringPointCode || payload.monitoringPointCode || '',
  58. // 线上帧用 status,DTO 用 monitoringState:两个都认。
  59. status: payload.status || payload.monitoringState || '',
  60. statusTime: payload.statusTime || '',
  61. serverUpdatedAt: payload.serverUpdatedAt || raw.serverUpdatedAt || '',
  62. reason: payload.reason || '',
  63. // 增量帧不带坐标与行业(只能靠 deviceCode 回联 REST 快照)——运行时服务据此设计合并。
  64. sampledAt: payload.sampledAt || '',
  65. eventId: typeof raw.eventId === 'string' ? raw.eventId : null,
  66. }
  67. }
  68. /** 工单扫描增量独立解析;不借设备状态帧推断工单或伪造操作时间。 */
  69. export function toWorkOrderDelta(frame) {
  70. if (!frame || frame.type !== WS_MESSAGE.ORDER_DELTA) return null
  71. if (typeof frame.serverUpdatedAt !== 'string' || !Number.isFinite(Date.parse(frame.serverUpdatedAt))) return null
  72. const rows = frame.data && frame.data.items
  73. if (!Array.isArray(rows)) return null
  74. const items = rows.filter((row) => row && typeof row.workOrderCode === 'string' && row.workOrderCode.trim())
  75. .map((row) => ({
  76. code: row.workOrderCode.trim(),
  77. deviceCode: typeof row.deviceCode === 'string' ? row.deviceCode : '',
  78. stateCode: Number.isInteger(row.stateCode) ? row.stateCode : null,
  79. stateName: typeof row.stateName === 'string' ? row.stateName : '',
  80. }))
  81. if (!items.length) return null
  82. return {
  83. items,
  84. serverUpdatedAt: frame.serverUpdatedAt,
  85. scanIntervalMs: Number.isFinite(frame.scanIntervalMs) && frame.scanIntervalMs > 0 ? frame.scanIntervalMs : null,
  86. }
  87. }
  88. /**
  89. * 鉴权回帧 → 领域事件。**历史接口**:驾驶舱免鉴权后不再消费该帧
  90. * (`authenticated` 只在管理端工单推送链路出现);保留供旧调用方/走查兼容。
  91. */
  92. export function toAuthenticatedEvent(frame) {
  93. const raw = frame && typeof frame === 'object' ? frame : null
  94. if (!raw || raw.type !== WS_MESSAGE.AUTHENTICATED) return null
  95. return {
  96. ok: raw.success === true,
  97. // 失败时后端给的中文原因(如「token 无效或已过期」);成功时为空串。
  98. reason: raw.msg || '',
  99. }
  100. }
  101. /** 订阅确认帧 → 领域事件。 */
  102. export function toSubscribedEvent(frame) {
  103. const raw = frame && typeof frame === 'object' ? frame : null
  104. if (!raw || raw.type !== WS_MESSAGE.SUBSCRIBED) return null
  105. return { scope: raw.scope || '', serverUpdatedAt: raw.serverUpdatedAt || '' }
  106. }
  107. /**
  108. * 设备新鲜度分区(票 16 的统一新鲜度模型)。
  109. * @param {string} deviceCode 设备编码
  110. * @param {object} [options] `{ calibrationPeriodSeconds, config, fetchImpl }`
  111. */
  112. export async function fetchFreshnessSection(deviceCode, options = {}) {
  113. if (!deviceCode) {
  114. return section(SECTION_STATE.FAILED, { reason: '缺少设备编码' })
  115. }
  116. const result = await fetchSection(`/equipments/${encodeURIComponent(deviceCode)}/freshness`, {
  117. params: { calibrationPeriodSeconds: options.calibrationPeriodSeconds },
  118. toData: toFreshness,
  119. config: options.config,
  120. fetchImpl: options.fetchImpl,
  121. })
  122. if (result.state !== SECTION_STATE.SUCCESS) return result
  123. const freshness = result.data || {}
  124. // 后端四态 → 分区状态:EXPIRED/STALE 归「过期但保留旧值」,EMPTY 归「确实没有」。
  125. if (freshness.freshness === 'EMPTY') {
  126. return section(SECTION_STATE.EMPTY, { mode: result.mode, data: freshness, freshness: 'EMPTY' })
  127. }
  128. if (freshness.freshness === 'EXPIRED' || freshness.freshness === 'STALE') {
  129. return section(SECTION_STATE.STALE, {
  130. mode: result.mode,
  131. reason: freshness.staleReason || '',
  132. data: freshness,
  133. freshness: freshness.freshness,
  134. retained: freshness.retained === true,
  135. })
  136. }
  137. return section(SECTION_STATE.SUCCESS, { mode: result.mode, data: freshness, freshness: freshness.freshness || 'CURRENT' })
  138. }