refreshStore.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /**
  2. * 统一刷新(票 61)—— 一次动作刷新「地图摘要 + 当前一级模式的面板分区」。
  3. *
  4. * 为什么要有这个 store(票 61 验收第 2 条「刷新动作只有一处入口」):
  5. * 右上角按钮与新鲜度轮询(`START_FRESHNESS` 的 tick)**都只调本文件的 requestRefresh()**,
  6. * 所以"刷新到底做了什么"整页只有一份定义,不存在按钮一套、定时一套。外壳只做两件事:
  7. * 把真实取数接缝 `configure` 进来,以及把它绑到按钮/tick 上。
  8. *
  9. * 四条纪律(逐条对着票面要求):
  10. * ① **并发**:地图摘要与面板互不依赖,同时发起 —— 任一失败都拖不住另一路;
  11. * ② **分区独立成败**:逐项结果各自记(`lastRun.parts`),一块面板失败只让它自己出现在
  12. * `failed` 里,其余照常更新;不整页报错、不回退 mock;
  13. * ③ **单飞**:进行中再次调用返回**同一轮**,连点或与轮询重叠都不会重复发请求;
  14. * ④ **记账同源**:本轮成败写进 freshnessService 那一本账(`recordFreshness` →
  15. * `recordExternal`),不在本文件另存一份「最近刷新时间」。
  16. *
  17. * 判据不在这里:哪些面板算失败、整轮怎么结论、文案怎么说,全在
  18. * `domain/refreshRun.js`(纯函数,可脱浏览器断言)。
  19. */
  20. import { computed, ref } from 'vue'
  21. import { defineStore } from 'pinia'
  22. import {
  23. REFRESH_PART,
  24. REFRESH_STATE,
  25. judgeFacilityLayer,
  26. judgeMapRefresh,
  27. judgePanels,
  28. planRefresh,
  29. refreshText,
  30. summarizeRefresh,
  31. } from '../domain/refreshRun.js'
  32. /** 取数接缝(外壳 configure 注入真实现;逻辑闸门注入假服务,不依赖网络)。 */
  33. function emptyDeps() {
  34. return { refreshMap: null, refreshFacilityLayer: null, refreshPanels: null, recordFreshness: null }
  35. }
  36. /** 接缝没接上时如实失败,而不是静默跳过(跳过会被读成"刷新成功")。 */
  37. function callDependency(fn, plan, missing, extra) {
  38. if (typeof fn !== 'function') throw new Error(missing)
  39. return fn(plan, extra)
  40. }
  41. /** 单路取数隔离:任一路抛错都收成 `{ ok:false, reason }`,不影响另一路。 */
  42. async function guard(run) {
  43. try {
  44. return { ok: true, value: await run() }
  45. } catch (error) {
  46. return { ok: false, reason: String((error && error.message) || error) }
  47. }
  48. }
  49. export const useRefreshStore = defineStore('refreshStore', () => {
  50. /** 是否正有一轮统一刷新在跑(按钮禁用 + aria-busy 的唯一依据)。 */
  51. const refreshing = ref(false)
  52. /** 状态机:idle / running / ok / partial / failed。 */
  53. const state = ref(REFRESH_STATE.IDLE)
  54. /** 本轮(或上一轮)的刷新计划:地图摘要 + 当前模式的全部分区。 */
  55. const plan = ref(null)
  56. /** 上一轮结论(逐项结果、失败项、文案);走查与排查读它。 */
  57. const lastRun = ref(null)
  58. let deps = emptyDeps()
  59. let inFlight = null
  60. /** 轮次纪元:`reset()` 作废在跑的那一轮,迟到的结论不再写状态、不再记账(票 14 的同款纪律)。 */
  61. let runEpoch = 0
  62. /** 注入取数接缝(合并语义:与 mapStore.setup 同一条纪律,后到的不抹掉先到的)。 */
  63. function configure(next = {}) {
  64. deps = { ...deps, ...next }
  65. }
  66. /** 可见进度/说明文案(按钮 aria-label 与 title 读它,界面不自己拼)。 */
  67. const text = computed(() => refreshText(state.value, {
  68. plan: plan.value,
  69. parts: (lastRun.value && lastRun.value.parts) || [],
  70. failed: (lastRun.value && lastRun.value.failed) || [],
  71. }))
  72. /** 上一轮失败项的 key(`data-refresh-failed` 断言面;空串 = 没有失败)。 */
  73. const failedKeys = computed(() => ((lastRun.value && lastRun.value.failed) || []).join(','))
  74. /**
  75. * 统一刷新:地图摘要 + 当前模式面板。
  76. * @param {object} [options] `{ mode, account, facilityMode }`
  77. * `mode` 当前一级模式(计划据此取面板清单);
  78. * `account` 是否记新鲜度(默认 true;轮询那条路传 false —— 本轮记账归
  79. * `freshnessService` 的周期,同一本账不重复记);
  80. * `facilityMode` 设施点刷新节奏 `full`(手动全量)/ `details`(轮询只补详情)/
  81. * `skip`(本轮不动设施点,如启动时首轮 freshness 紧接首屏加载),默认 `full`。
  82. * @returns {Promise<object>} 本轮结论(`summarizeRefresh` 的结果)
  83. */
  84. function requestRefresh(options = {}) {
  85. if (inFlight) return inFlight
  86. const current = planRefresh(options.mode)
  87. const mine = ++runEpoch
  88. plan.value = current
  89. state.value = REFRESH_STATE.RUNNING
  90. refreshing.value = true
  91. inFlight = runOnce(current, options, mine)
  92. return inFlight
  93. }
  94. /**
  95. * 跑一轮:两路并发 → 逐项判据 → 整轮结论 → 记账。
  96. *
  97. * 这里刻意**不写 try 包住业务**:单路抛错已在 `guard` 里收成结果;
  98. * 只有判据/计划本身出问题(编程错误)才会落到外层兜底,且仍如实报失败、绝不外抛。
  99. */
  100. async function runOnce(current, options, mine) {
  101. let outcome = null
  102. try {
  103. const skipFacility = options.facilityMode === 'skip'
  104. const [mapResult, facilityResult, panelResult] = await Promise.all([
  105. guard(() => callDependency(deps.refreshMap, current, '地图摘要取数未接入')),
  106. skipFacility
  107. ? Promise.resolve(null)
  108. : guard(() => callDependency(deps.refreshFacilityLayer, current, '设施点图层取数未接入', {
  109. mode: options.facilityMode === 'details' ? 'details' : 'full',
  110. })),
  111. guard(() => callDependency(deps.refreshPanels, current, '面板取数未接入')),
  112. ])
  113. outcome = summarizeRefresh({
  114. mode: current.mode,
  115. plan: current,
  116. parts: [
  117. mapPartOf(current, mapResult),
  118. skipFacility ? skippedFacilityPartOf(current) : facilityPartOf(current, facilityResult),
  119. ...panelPartsOf(current, panelResult),
  120. ],
  121. })
  122. } catch (error) {
  123. // 兜底:连计划/判据都炸了也要给出一轮"全失败"的结论(界面不能停在刷新中)。
  124. const reason = String((error && error.message) || error)
  125. outcome = summarizeRefresh({
  126. mode: current.mode,
  127. plan: current,
  128. parts: current.parts.map((part) => ({ ...part, ok: false, reason })),
  129. })
  130. } finally {
  131. if (mine === runEpoch) {
  132. refreshing.value = false
  133. inFlight = null
  134. }
  135. }
  136. // 被 reset() 作废的轮次:结论丢弃,不再写状态、不再记新鲜度(离开外壳后不该再动 store)。
  137. if (mine !== runEpoch) return outcome
  138. lastRun.value = outcome
  139. state.value = outcome.state
  140. if (options.account !== false && typeof deps.recordFreshness === 'function') {
  141. deps.recordFreshness(outcome.ok, outcome.reason)
  142. }
  143. return outcome
  144. }
  145. /** 地图摘要那一项的逐项结果(取数抛错时按抛错原因记失败)。 */
  146. function mapPartOf(current, result) {
  147. const base = current.parts.find((part) => part.kind === 'map') || { key: REFRESH_PART.MAP, kind: 'map', label: '地图摘要' }
  148. if (!result.ok) return { ...base, ok: false, reason: result.reason }
  149. return { ...base, ...judgeMapRefresh(result.value) }
  150. }
  151. /** 首轮 freshness 紧跟首屏加载时设施点不动:如实标 skipped,不算失败也不触发请求。 */
  152. function skippedFacilityPartOf(current) {
  153. const base = current.parts.find((part) => part.kind === REFRESH_PART.FACILITY_LAYER)
  154. || { key: REFRESH_PART.FACILITY_LAYER, kind: REFRESH_PART.FACILITY_LAYER, label: '设施点' }
  155. return { ...base, ok: true, state: 'skipped', reason: '' }
  156. }
  157. /** 设施点图层那一项的逐项结果(取数抛错时按抛错原因记失败)。 */
  158. function facilityPartOf(current, result) {
  159. const base = current.parts.find((part) => part.kind === REFRESH_PART.FACILITY_LAYER)
  160. || { key: REFRESH_PART.FACILITY_LAYER, kind: REFRESH_PART.FACILITY_LAYER, label: '设施点' }
  161. if (!result.ok) return { ...base, ok: false, reason: result.reason }
  162. return { ...base, ...judgeFacilityLayer(result.value) }
  163. }
  164. /**
  165. * 面板各项的逐项结果。
  166. *
  167. * `refreshPanels` 的契约:取完数后回一个「panelId → 分区」的查表函数,
  168. * 由 `domain/refreshRun.js` 按分区状态判成败(判据只有一处,外壳不自己数)。
  169. * 整路取数就抛错时,该模式的面板**全部**如实记失败并带同一个原因。
  170. */
  171. function panelPartsOf(current, result) {
  172. const bases = current.parts.filter((part) => part.kind === 'panel')
  173. if (!result.ok) return bases.map((base) => ({ ...base, ok: false, state: '', reason: result.reason }))
  174. const judged = judgePanels(current.panels, result.value)
  175. return bases.map((base) => {
  176. const item = judged.find((entry) => entry.key === base.key)
  177. return { ...base, ok: Boolean(item && item.ok), state: (item && item.state) || '', reason: (item && item.reason) || 'unavailable' }
  178. })
  179. }
  180. /** 仅测试用/离开外壳用:作废在跑的那一轮并回到未刷新状态。 */
  181. function reset() {
  182. runEpoch += 1
  183. inFlight = null
  184. refreshing.value = false
  185. state.value = REFRESH_STATE.IDLE
  186. plan.value = null
  187. lastRun.value = null
  188. deps = emptyDeps()
  189. }
  190. return {
  191. refreshing,
  192. state,
  193. plan,
  194. lastRun,
  195. text,
  196. failedKeys,
  197. configure,
  198. requestRefresh,
  199. reset,
  200. }
  201. })