image.core\types\error.mbt

98.1% · 105 / 107 points · 262 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/// # 错误模型 Error model
  3. 3///
  4. 4/// 面向"放进服务"的统一错误面:稳定的错误码 + 结构化分类 + 建议动作。
  5. 5/// 既有 `LoadError` 保持不变(避免动 70 个包),通过 `image_error_from_load` 投影到新模型。
  6. 6///
  7. 7/// Stable, structured error surface for service use: stable codes + category + hint.
  8. 8/// `LoadError` stays untouched; `image_error_from_load` projects it into this model.
  9. 9
  10. 10///|
  11. 11/// 稳定错误码(字符串形式是小写蛇形,可直接出现在 JSON 的 `code` 字段)。
  12. 12/// Stable error codes; the string form is lower_snake_case and safe for a JSON `code` field.
  13. 13#derive(Eq, @debug.Debug)
  14. 14pub(all) enum ErrorCode {
  15. 15 UnsupportedFormat
  16. 16 InvalidHeader
  17. 17 InvalidDimensions
  18. 18 InvalidArgument
  19. 19 Truncated
  20. 20 DecodeFailed
  21. 21 EncodeFailed
  22. 22 ProcessFailed
  23. 23 LimitBytes
  24. 24 LimitPixels
  25. 25 LimitTime
  26. 26 Cancelled
  27. 27}
  28. 28
  29. 29///|
  30. 30/// 错误码 → 稳定字符串(小写蛇形,跨版本不变)。Error code to stable lower_snake_case string.
  31. 31pub fn ErrorCode::to_string(self : ErrorCode) -> String {
  32. 32● match self {
  33. 33● UnsupportedFormat => "unsupported_format"
  34. 34● InvalidHeader => "invalid_header"
  35. 35● InvalidDimensions => "invalid_dimensions"
  36. 36● InvalidArgument => "invalid_argument"
  37. 37● Truncated => "truncated"
  38. 38● DecodeFailed => "decode_failed"
  39. 39● EncodeFailed => "encode_failed"
  40. 40● ProcessFailed => "process_failed"
  41. 41● LimitBytes => "limit_bytes"
  42. 42● LimitPixels => "limit_pixels"
  43. 43● LimitTime => "limit_time"
  44. 44● Cancelled => "cancelled"
  45. 45 }
  46. 46}
  47. 47
  48. 48///|
  49. 49/// 是否属于资源限额类错误(调用方可据此决定"换大预算重试"还是"直接拒绝")。
  50. 50/// Whether the code is a budget/limit failure (caller may raise the budget and retry).
  51. 51pub fn ErrorCode::is_budget(self : ErrorCode) -> Bool {
  52. 52● match self {
  53. 53● LimitBytes | LimitPixels | LimitTime => true
  54. 54● _ => false
  55. 55 }
  56. 56}
  57. 57
  58. 58///|
  59. 59/// 统一图像错误 Unified image error
  60. 60///
  61. 61/// 变体 Variants:
  62. 62/// - `Decode(ErrorCode, String)` - 解码阶段 Decode phase
  63. 63/// - `Encode(ErrorCode, String)` - 编码阶段 Encode phase
  64. 64/// - `Process(ErrorCode, String)` - 像素处理阶段 Process phase
  65. 65/// - `Budget(ErrorCode, String)` - 预算/限额拒绝 Budget rejection
  66. 66/// - `Cancelled(String)` - 调用方取消 Caller cancelled
  67. 67pub(all) suberror ImageError {
  68. 68 Decode(ErrorCode, String)
  69. 69 Encode(ErrorCode, String)
  70. 70 Process(ErrorCode, String)
  71. 71 Budget(ErrorCode, String)
  72. 72 Cancelled(String)
  73. 73}
  74. 74
  75. 75///|
  76. 76/// 稳定错误码字符串,形如 `decode/truncated`、`budget/limit_pixels`、`cancelled`。
  77. 77/// Stable code string such as `decode/truncated`, `budget/limit_pixels`, `cancelled`.
  78. 78pub fn ImageError::code(self : ImageError) -> String {
  79. 79● match self {
  80. 80● Decode(c, _) => "decode/" + c.to_string()
  81. 81● Encode(c, _) => "encode/" + c.to_string()
  82. 82● Process(c, _) => "process/" + c.to_string()
  83. 83● Budget(c, _) => "budget/" + c.to_string()
  84. 84● Cancelled(_) => "cancelled"
  85. 85 }
  86. 86}
  87. 87
  88. 88///|
  89. 89/// 错误消息(面向人,含具体数值)。Human-readable message (may include concrete numbers).
  90. 90pub fn ImageError::message(self : ImageError) -> String {
  91. 91● match self {
  92. 92 Decode(_, m) | Encode(_, m) | Process(_, m) | Budget(_, m) | Cancelled(m) =>
  93. 93● m
  94. 94 }
  95. 95}
  96. 96
  97. 97///|
  98. 98/// 建议动作:给下游/agent 的处置建议(稳定文本,便于直接回给调用方)。
  99. 99/// Suggested action for callers/agents; stable text suitable to return as-is.
  100. 100pub fn image_error_hint(code : String) -> String {
  101. 101● let base = if code.contains("limit_pixels") {
  102. 102● "图像像素数超出预算:提高 max_pixels 或先降采样/分区解码;不要放宽到无上限。"
  103. 103● } else if code.contains("limit_bytes") {
  104. 104● "输入字节或内存分配超出预算:提高 max_bytes 或改为流式/分块处理;拒绝超限输入。"
  105. 105● } else if code.contains("limit_time") {
  106. 106● "处理耗时超出预算:缩小任务(降采样、裁剪 ROI)或提高 max_ms;必要时异步化。"
  107. 107● } else if code.contains("unsupported_format") {
  108. 108● "格式无对应编解码器:先用 detect_format 确认格式,或转成 PNG/JPEG/QOI 再处理。"
  109. 109● } else if code.contains("truncated") {
  110. 110● "输入被截断:丢弃该输入(不要重试同一份坏数据),并记录来源。"
  111. 111● } else if code.contains("invalid_header") ||
  112. 112● code.contains("invalid_dimensions") {
  113. 113● "文件头/尺寸非法:当作坏图拒绝,不要按头部声明去预分配内存。"
  114. 114● } else if code.contains("invalid_argument") {
  115. 115● "调用参数非法:检查尺寸/通道/质量/策略取值范围。"
  116. 116● } else if code.contains("cancelled") {
  117. 117● "调用方主动取消:按取消语义返回,不要当作错误重试。"
  118. 118● } else if code.contains("encode") {
  119. 119● "编码失败:检查输入通道数与尺寸;必要时改格式(无损用 PNG/WebP-VP8L)。"
  120. 120 } else {
  121. 121● "解码/处理失败:按坏图处理,记录 code 与 message 便于定位。"
  122. 122 }
  123. 123 base
  124. 124}
  125. 125
  126. 126///|
  127. 127/// 把旧 `LoadError` 投影成 `ImageError`(按消息特征归类到稳定码)。
  128. 128/// Project legacy `LoadError` into `ImageError`, classifying by message traits.
  129. 129pub fn image_error_from_load(e : LoadError) -> ImageError {
  130. 130● match e {
  131. 131● FileIO(m) => Decode(InvalidArgument, m)
  132. 132● UnsupportedFormat(m) => Decode(UnsupportedFormat, m)
  133. 133● EncodeFailed(m) => Encode(EncodeFailed, m)
  134. 134 DecodeFailed(m) =>
  135. 135● if m.contains("budget/limit_time") || m.contains("limit_time") {
  136. 136○ Budget(LimitTime, m)
  137. 137● } else if m.contains("cancelled") {
  138. 138○ Cancelled(m)
  139. 139● } else if m.contains("截断") ||
  140. 140● m.contains("过短") ||
  141. 141● m.contains("truncated") {
  142. 142● Decode(Truncated, m)
  143. 143● } else if m.contains("超过") ||
  144. 144● m.contains("溢出") ||
  145. 145● m.contains("exceed") {
  146. 146● Decode(InvalidDimensions, m)
  147. 147● } else if m.contains("尺寸无效") ||
  148. 148● m.contains("标记") ||
  149. 149● m.contains("marker") ||
  150. 150● m.contains("header") {
  151. 151● Decode(InvalidHeader, m)
  152. 152● } else if m.contains("不支持") || m.contains("unsupported") {
  153. 153● Decode(UnsupportedFormat, m)
  154. 154 } else {
  155. 155● Decode(DecodeFailed, m)
  156. 156 }
  157. 157 }
  158. 158}
  159. 159
  160. 160///|
  161. 161/// 解码/处理预算(默认保守)。Decode/process limits with conservative defaults.
  162. 162///
  163. 163/// - `max_pixels`:总像素上限(默认 5 亿,与 `MAX_TOTAL_PIXELS` 一致)
  164. 164/// - `max_bytes`:输入字节上限(默认 256 MiB)
  165. 165/// - `max_ms`:单次处理时间上限(默认 10 秒;纯 MoonBit 同步实现下为"准入检查 + 事后判定",不能强杀)
  166. 166pub(all) struct DecodeLimits {
  167. 167 max_pixels : Int64
  168. 168 max_bytes : Int64
  169. 169 max_ms : Int64
  170. 170}
  171. 171
  172. 172///|
  173. 173/// 默认预算。Default limits.
  174. 174pub fn DecodeLimits::default_limits() -> DecodeLimits {
  175. 175● { max_pixels: 500000000L, max_bytes: 268435456L, max_ms: 10000L, }
  176. 176}
  177. 177
  178. 178///|
  179. 179/// 严格预算(面向不可信输入的批处理/服务端)。Strict limits for untrusted input.
  180. 180pub fn DecodeLimits::strict_limits() -> DecodeLimits {
  181. 181● { max_pixels: 67108864L, max_bytes: 67108864L, max_ms: 3000L, }
  182. 182}
  183. 183
  184. 184///|
  185. 185/// 按格式上限构造预算(只覆盖像素数,字节/时间沿用默认)。
  186. 186/// Build limits overriding only the pixel budget.
  187. 187pub fn DecodeLimits::with_max_pixels(max_pixels : Int64) -> DecodeLimits {
  188. 188● let d = DecodeLimits::default_limits()
  189. 189 { ..d, max_pixels, }
  190. 190}
  191. 191
  192. 192///|
  193. 193/// 校验输入字节数是否超预算。Reject input whose byte length exceeds the budget.
  194. 194pub fn DecodeLimits::check_bytes(
  195. 195 self : DecodeLimits,
  196. 196 bytes : Int64,
  197. 197) -> Unit raise ImageError {
  198. 198● if bytes > self.max_bytes {
  199. 199● raise Budget(
  200. 200 LimitBytes,
  201. 201 "输入字节 \{bytes} 超过上限 \{self.max_bytes}",
  202. 202 )
  203. 203 }
  204. 204}
  205. 205
  206. 206///|
  207. 207/// 校验像素数是否超预算。Reject pixel counts exceeding the budget.
  208. 208pub fn DecodeLimits::check_pixels(
  209. 209 self : DecodeLimits,
  210. 210 width : Int64,
  211. 211 height : Int64,
  212. 212) -> Unit raise ImageError {
  213. 213● if width <= 0L || height <= 0L {
  214. 214● raise Decode(
  215. 215 InvalidDimensions,
  216. 216 "图像尺寸无效: width=\{width}, height=\{height}",
  217. 217 )
  218. 218 }
  219. 219 let pixels = width * height
  220. 220 if pixels > self.max_pixels {
  221. 221● raise Budget(
  222. 222 LimitPixels,
  223. 223 "图像像素数 \{pixels} 超过上限 \{self.max_pixels}",
  224. 224 )
  225. 225 }
  226. 226}
  227. 227
  228. 228///|
  229. 229/// 内存分配预算(供像素级算子使用)。Allocation budget for pixel operators.
  230. 230pub(all) struct AllocBudget {
  231. 231 max_bytes : Int64
  232. 232}
  233. 233
  234. 234///|
  235. 235/// 默认分配预算(512 MiB)。Default allocation budget.
  236. 236pub fn AllocBudget::default_budget() -> AllocBudget {
  237. 237● { max_bytes: 536870912L, }
  238. 238}
  239. 239
  240. 240///|
  241. 241/// 需要 `width × height × channels` 字节时的准入检查。Admission check for an allocation.
  242. 242pub fn AllocBudget::check_image(
  243. 243 self : AllocBudget,
  244. 244 width : Int64,
  245. 245 height : Int64,
  246. 246 channels : Int64,
  247. 247 what : String,
  248. 248) -> Unit raise ImageError {
  249. 249● if width <= 0L || height <= 0L || channels <= 0L {
  250. 250● raise Process(
  251. 251 InvalidArgument,
  252. 252 "\{what}: 尺寸/通道无效 (\{width}×\{height}×\{channels})",
  253. 253 )
  254. 254 }
  255. 255 let need = width * height * channels
  256. 256 if need > self.max_bytes {
  257. 257● raise Budget(
  258. 258 LimitBytes,
  259. 259 "\{what} 需要 \{need} 字节,超过分配预算 \{self.max_bytes}",
  260. 260 )
  261. 261 }
  262. 262}