image.core\types\cancel.mbt

92.5% · 37 / 40 points · 172 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 取消与超时 Cancel & Timeout
  3. 3///
  4. 4/// 分块循环的让出点:调用方给一个 `Deadline`,实现方在每个块边界查一次,
  5. 5/// 命中就立刻返回 `budget/limit_time`,而不是跑完再看耗时。
  6. 6///
  7. 7/// 设计取舍:`Deadline` **不抛错误**,只暴露 `tripped_kind()`(0 正常 / 1 超时 / 2 取消)。
  8. 8/// 这样每个包的 `raise` 集合不用变(`LoadError` / `ImageError` 各自保留),
  9. 9/// 由调用点在原错误类型上自行抛,便于既有测试与调用点零迁移。
  10. 10///
  11. 11/// Yield points for chunked loops: the caller passes a `Deadline`, the implementation
  12. 12/// checks it at every chunk boundary and bails out immediately instead of finishing first.
  13. 13///
  14. 14/// `Deadline` deliberately does not raise; it only reports `tripped_kind()`
  15. 15/// (0 = fine, 1 = timeout, 2 = cancelled). Each package keeps its own `raise` set untouched.
  16. 16
  17. 17///|
  18. 18/// 取消位:可被多个分块循环共享的可变标志(同一线程内写,读方只看最新值)。
  19. 19/// Cancellation flag shared across chunked loops.
  20. 20pub(all) struct CancelToken {
  21. 21 flag : Ref[Bool]
  22. 22}
  23. 23
  24. 24///|
  25. 25/// 新建一个未取消的标志。A fresh, not-yet-cancelled token.
  26. 26pub fn CancelToken::new() -> CancelToken {
  27. 27● { flag: Ref(false), }
  28. 28}
  29. 29
  30. 30///|
  31. 31/// 置位(幂等)。Set the flag (idempotent).
  32. 32pub fn CancelToken::cancel(self : CancelToken) -> Unit {
  33. 33● self.flag.val = true
  34. 34}
  35. 35
  36. 36///|
  37. 37/// 是否已被取消。Whether cancellation was requested.
  38. 38pub fn CancelToken::is_cancelled(self : CancelToken) -> Bool {
  39. 39● self.flag.val
  40. 40}
  41. 41
  42. 42///|
  43. 43/// 软截止:时间上限 + 可选取消位。每 `watch_every` 次 `tick` 才读一次时钟,
  44. 44/// 把 `monotonic_clock` 的系统调用摊薄到 1/16,块内循环本身的开销不被让出点放大。
  45. 45/// Soft deadline: wall-clock budget plus an optional cancel token. The clock is read
  46. 46/// only once per `watch_every` ticks, so the yield point does not dominate the loop.
  47. 47pub(all) struct Deadline {
  48. 48 token : CancelToken
  49. 49 max_us : Double
  50. 50 started : @bench.Timestamp
  51. 51 ticks : Ref[Int32]
  52. 52 watch_every : Int32
  53. 53 tripped : Ref[Int32]
  54. 54}
  55. 55
  56. 56///|
  57. 57/// `0` = 正常,`1` = 超时(`budget/limit_time`),`2` = 调用方取消(`cancelled`)。
  58. 58pub const KIND_OK : Int32 = 0
  59. 59
  60. 60///|
  61. 61/// 超时。Timeout.
  62. 62pub const KIND_TIMEOUT : Int32 = 1
  63. 63
  64. 64///|
  65. 65/// 取消。Cancelled by caller.
  66. 66pub const KIND_CANCELLED : Int32 = 2
  67. 67
  68. 68///|
  69. 69/// 新建截止:`max_ms <= 0` 表示不限时(只保留取消位,调用成本接近零)。
  70. 70/// `max_ms <= 0` means unlimited time: only the cancel flag is kept, cost is negligible.
  71. 71pub fn Deadline::new(max_ms : Int32) -> Deadline {
  72. 72● {
  73. 73● token: CancelToken::new(),
  74. 74 max_us: if max_ms <= 0 {
  75. 75● 0.0
  76. 76 } else {
  77. 77● max_ms.to_double() * 1000.0
  78. 78 },
  79. 79● started: @bench.monotonic_clock_start(),
  80. 80 ticks: Ref(0),
  81. 81 watch_every: 16,
  82. 82 tripped: Ref(KIND_OK),
  83. 83 }
  84. 84}
  85. 85
  86. 86///|
  87. 87/// 从 `DecodeLimits` 建(`max_ms <= 0` 同样表示不限时)。Build from decode limits.
  88. 88pub fn Deadline::from_limits(limits : DecodeLimits) -> Deadline {
  89. 89● Deadline::new(limits.max_ms.to_int())
  90. 90}
  91. 91
  92. 92///|
  93. 93/// 冒烟:检查一次并累加计数。已判定过则直接返回,后续调用免费。
  94. 94/// One check plus counter bump. Once tripped, later calls are free.
  95. 95pub fn Deadline::tick(self : Deadline) -> Unit {
  96. 96● if self.tripped.val != KIND_OK {
  97. 97● return
  98. 98 }
  99. 99● if self.token.is_cancelled() {
  100. 100○ self.tripped.val = KIND_CANCELLED
  101. 101 return
  102. 102 }
  103. 103 if self.max_us <= 0.0 {
  104. 104● return
  105. 105 }
  106. 106 let n = self.ticks.val
  107. 107 self.ticks.val = n + 1
  108. 108 if n % self.watch_every != 0 {
  109. 109● return
  110. 110 }
  111. 111● if @bench.monotonic_clock_end(self.started) >= self.max_us {
  112. 112● self.tripped.val = KIND_TIMEOUT
  113. 113 }
  114. 114}
  115. 115
  116. 116///|
  117. 117/// 状态:见 `KIND_OK` / `KIND_TIMEOUT` / `KIND_CANCELLED`。
  118. 118pub fn Deadline::tripped_kind(self : Deadline) -> Int32 {
  119. 119● self.tripped.val
  120. 120}
  121. 121
  122. 122///|
  123. 123/// 已用毫秒(截到 3 位小数)。Elapsed milliseconds, rounded to 3 decimals.
  124. 124pub fn Deadline::elapsed_ms(self : Deadline) -> Double {
  125. 125● let us = @bench.monotonic_clock_end(self.started)
  126. 126 let ms = us / 1000.0
  127. 127● (ms * 1000.0).round() / 1000.0
  128. 128}
  129. 129
  130. 130///|
  131. 131/// 主动取消(外部把标志置位)。Cancel from the caller side.
  132. 132pub fn Deadline::cancel(self : Deadline) -> Unit {
  133. 133● self.token.cancel()
  134. 134 self.tripped.val = KIND_CANCELLED
  135. 135}
  136. 136
  137. 137///|
  138. 138/// 分块循环的让出点:`None` 立即返回,`Some(d)` 走 `d.tick()`。
  139. 139/// Yield point for chunked loops; `None` is a no-op.
  140. 140pub fn tick_optional(deadline : Deadline?) -> Unit {
  141. 141● match deadline {
  142. 142○ Some(d) => d.tick()
  143. 143● None => ()
  144. 144 }
  145. 145}
  146. 146
  147. 147///|
  148. 148/// 让出点 + 当场判定:命中就抛 `LoadError::DecodeFailed`,消息带 `budget/limit_time`
  149. 149/// 或 `cancelled` 关键字,由 `image_error_from_load` 归到稳定码。
  150. 150/// Yield point that raises immediately, with the keyword `budget/limit_time` (or `cancelled`)
  151. 151/// embedded so `image_error_from_load` can map it to the stable code.
  152. 152pub fn deadline_guard(
  153. 153 deadline : Deadline?,
  154. 154 phase : String,
  155. 155) -> Unit raise LoadError {
  156. 156● let d = match deadline {
  157. 157● Some(d) => d
  158. 158● None => return
  159. 159 }
  160. 160● d.tick()
  161. 161● match d.tripped_kind() {
  162. 162 KIND_TIMEOUT =>
  163. 163● raise LoadError::DecodeFailed(
  164. 164 "\{phase} 超出时间预算(budget/limit_time):已用 \{d.elapsed_ms()} ms",
  165. 165 )
  166. 166 KIND_CANCELLED =>
  167. 167● raise LoadError::DecodeFailed(
  168. 168 "\{phase} 被调用方取消(cancelled)",
  169. 169 )
  170. 170● _ => ()
  171. 171 }
  172. 172}