imgcli\serve_run.mbt
79.6% · 227 / 285 points · 621 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # `imgtool serve` 的监听实现(serve@1,native only) - 3
/// - 4
/// 契约在 [serve_contract.mbt] 与 `docs/serve_contract.md`;这里只负责把它跑起来: - 5
/// `async/http` 的 `Server::run_forever(handler, max_connections=max_conn)`, - 6
/// 每个连接一个任务,单线程并发,峰值内存 ≈ max_conn × 单请求预算。 - 7
/// - 8
/// 不做的事(与契约 §9 一致):不落盘、不做 TLS、不做鉴权、不自己造请求队列。 - 9
/// 满载时 `run_forever` 停止 accept,新连接停在内核 listen backlog —— 这正是契约里 - 10
/// 「满载不排队、延迟不失控」的实现形态,另造一个队列只会让它反悔。 - 11
- 12
///| - 13
#cfg(target="native") - 14
priv struct ServeCtx { - 15
max_conn : Int32 - 16
mem_budget : Int32 - 17
max_ms : Int32 - 18
quiet : Bool - 19
started : Int64 - 20
} - 21
- 22
///| - 23
/// 绑定结果。把「解析地址失败」和「端口占用」分开,是为了让调用方看到可区分的码, - 24
/// 也让这两条错误路径能被白盒测试直接喂进坏地址 / 已占端口。 - 25
#cfg(target="native") - 26
priv enum BindOut { - 27
Bound(@http.Server) - 28
BadAddr - 29
BindFailed - 30
} - 31
- 32
///| - 33
#cfg(target="native") - 34
fn bad_addr_json(addr : String, port : Int32) -> String { - 35●
"{\"ok\":false,\"code\":\"serve/bad_addr\",\"message\":\"地址无法解析:\{addr}:\{port}\",\"hint\":\"用 --addr 127.0.0.1 --port 8730 这种形式\"}" - 36
} - 37
- 38
///| - 39
#cfg(target="native") - 40
fn bind_failed_json(addr : String, port : Int32) -> String { - 41●
"{\"ok\":false,\"code\":\"serve/bind_failed\",\"message\":\"绑定失败:\{addr}:\{port}\",\"hint\":\"端口被占用就换一个;对外暴露才需要 --addr 0.0.0.0\"}" - 42
} - 43
- 44
///| - 45
#cfg(target="native") - 46
fn listen_json(addr : String, max_conn : Int32) -> String { - 47●
"{\"ok\":true,\"event\":\"listen\",\"addr\":\"\{addr}\",\"schema\":\"\{SERVE_SCHEMA}\",\"max_conn\":\{max_conn}}" - 48
} - 49
- 50
///| - 51
#cfg(target="native") - 52
async fn serve_bind(addr : String, port : Int32) -> BindOut { - 53●
let a = @socket.Addr::parse("\{addr}:\{port}") catch { _ => return BadAddr } - 54○
let s = @http.Server::Server(a) catch { _ => return BindFailed } - 55
Bound(s) - 56
} - 57
- 58
///| - 59
/// 事件循环本体:只剩 `run_forever` 这一层不可测的尾巴,所以刻意做薄。 - 60
#cfg(target="native") - 61
async fn serve_loop(server : @http.Server, ctx : ServeCtx) -> Unit { - 62○
server.run_forever( - 63○
async fn(req, conn) { serve_handle(req, conn, ctx) }, - 64
max_connections=ctx.max_conn, - 65
) - 66
} - 67
- 68
///| - 69
/// 同步入口:`fn main` 里直接调用;内部 `run_async_main` 驱动事件循环。 - 70
/// 因此 `imgtool` 的普通子命令仍是纯同步路径,不多背一次运行时启动。 - 71
#cfg(target="native") - 72
pub fn serve_run( - 73
addr : String, - 74
port : Int32, - 75
max_conn : Int32, - 76
mem_budget : Int32, - 77
max_ms : Int32, - 78
quiet : Bool, - 79
) -> Unit { - 80○
@async.run_async_main(async fn() { - 81○
match serve_bind(addr, port) { - 82○
Bound(server) => { - 83
let ctx : ServeCtx = { - 84
max_conn, - 85
mem_budget, - 86
max_ms, - 87
quiet, - 88○
started: @async.now(), - 89
} - 90
if !quiet { - 91○
println(listen_json(server.local_addr().to_string(), max_conn)) - 92
} - 93○
serve_loop(server, ctx) - 94
} - 95○
BadAddr => { - 96○
eprintln(bad_addr_json(addr, port)) - 97○
@env.exit(1) - 98
} - 99○
BindFailed => { - 100○
eprintln(bind_failed_json(addr, port)) - 101○
@env.exit(1) - 102
} - 103
} - 104
}) - 105
} - 106
- 107
///| - 108
/// max_ms 的**事后**判定:Recipe 链路还没有 Deadline 参数,只能在结果出来时判 - 109
/// 「超了没有」,超了把这次成功降级成 422,让调用方拿到确定信号而不是一条慢成功。 - 110
#cfg(target="native") - 111
fn build_reply( - 112
code0 : Int32, - 113
ctype0 : String, - 114
body0 : Bytes, - 115
elapsed : Int64, - 116
max_ms : Int32, - 117
) -> (Int32, String, Bytes) { - 118●
if code0 == 200 && max_ms > 0 && elapsed > max_ms.to_int64() * 1000 { - 119●
( - 120
422, - 121
"application/json", - 122●
err_body( - 123
"budget/limit_time", - 124
"本次处理 \{ms_text(elapsed)}ms 超过 --max-ms \{max_ms}", - 125
"调高 --max-ms,或缩小请求(图太大就先缩再发);Recipe 链路的真中断还没接线", - 126
), - 127
) - 128
} else { - 129●
(code0, ctype0, body0) - 130
} - 131
} - 132
- 133
///| - 134
/// 一个请求的全过程:解析 path/query → 决策 → 回字节或 JSON。 - 135
#cfg(target="native") - 136
async fn serve_handle( - 137
req : @http.RequestHeader, - 138
conn : @http.ServerConnection, - 139
ctx : ServeCtx, - 140
) -> Unit { - 141○
let t0 = @async.now() - 142
let raw = req.path - 143○
let (path, query) = split_path_query(raw) - 144○
let verb = verb_of(req.meth) - 145
let (code0, ctype0, body0) = match - 146○
route_plan( - 147
verb, - 148
path, - 149
query, - 150○
declared_length(req.headers), - 151○
@async.now(), - 152
ctx, - 153
) { - 154○
Reply(c, t, b) => (c, t, b) - 155
NeedBody(name, q) => - 156○
match read_body(conn) { - 157
None => - 158○
( - 159
400, - 160
"application/json", - 161○
err_body( - 162
"decode/body_read", "请求体读取失败", "重发一次;确认没有用 chunked", - 163
), - 164
) - 165○
Some(b) => recipe_reply(name, b, q, req.headers, ctx) - 166
} - 167
} - 168○
let (code, ctype, body) = build_reply( - 169
code0, - 170
ctype0, - 171
body0, - 172○
@async.now() - t0, - 173
ctx.max_ms, - 174
) - 175
let hdrs : Map[@http.CaseInsensitiveString, String] = Map([]) - 176
hdrs["Content-Type"] = ctype - 177○
hdrs["Content-Length"] = body.length().to_string() - 178○
hdrs["X-Img-Ms"] = ms_text(@async.now() - t0) - 179○
conn.send_response(code, reason_of(code), extra_headers=hdrs) - 180○
conn.write(body) - 181○
conn.end_response() - 182
if !ctx.quiet { - 183○
println( - 184
"{\"event\":\"req\",\"method\":\"\{verb}\",\"path\":\"\{path}\",\"status\":\{code},\"out\":\{body.length()},\"ms\":\"\{ms_text(@async.now() - t0)}}", - 185
) - 186
} - 187
} - 188
- 189
///| - 190
/// 路由决策的两种结果:要么直接回,要么还需要请求体才能算。 - 191
#cfg(target="native") - 192
priv enum RoutePlan { - 193
Reply(Int32, String, Bytes) - 194
NeedBody(String, Map[String, String]) - 195
} - 196
- 197
///| - 198
/// 路由决策(纯函数,不碰连接):查表 + 参数校验,**副作用为零**,所以能直接单测。 - 199
/// `now` 显式传入而不是在函数里取时间,一是可测,二是让 uptime 只有一个来源。 - 200
#cfg(target="native") - 201
fn route_plan( - 202
verb : String, - 203
path : String, - 204
query : Map[String, String], - 205
declared : Int32, - 206
now : Int64, - 207
ctx : ServeCtx, - 208
) -> RoutePlan { - 209●
if path == "/healthz" { - 210●
if verb != "GET" { - 211●
return Reply( - 212
405, - 213
"application/json", - 214●
err_body( - 215
"method_not_allowed", "healthz 只接受 GET", "换 GET 再来", - 216
), - 217
) - 218
} - 219
return Reply( - 220
200, - 221
"application/json", - 222●
json_bytes({ - 223●
"ok": jbool(true), - 224●
"version": jstr(version), - 225●
"uptime_s": jnum(((now - ctx.started) / 1000).to_int()), - 226●
"max_conn": jnum(ctx.max_conn), - 227
}), - 228
) - 229
} - 230
if path == "/version" { - 231●
if verb != "GET" { - 232●
return Reply( - 233
405, - 234
"application/json", - 235●
err_body( - 236
"method_not_allowed", "version 只接受 GET", "换 GET 再来", - 237
), - 238
) - 239
} - 240
return Reply( - 241
200, - 242
"application/json", - 243○
json_bytes({ - 244○
"ok": jbool(true), - 245○
"version": jstr(version), - 246○
"target": jstr("native"), - 247○
"schema": jstr(SERVE_SCHEMA), - 248
}), - 249
) - 250
} - 251
if path == "/recipes" { - 252●
if verb != "GET" { - 253●
return Reply( - 254
405, - 255
"application/json", - 256●
err_body( - 257
"method_not_allowed", "recipes 只接受 GET", "换 GET 再来", - 258
), - 259
) - 260
} - 261
let items : Array[@json.Json] = [] - 262●
for n in @recipe.recipe_names() { - 263●
items.push( - 264●
@json.Json::object({ - 265●
"id": jstr(n), - 266●
"about": jstr(@recipe.recipe_about(n)), - 267
}), - 268
) - 269
} - 270
return Reply( - 271
200, - 272
"application/json", - 273●
json_bytes({ "ok": jbool(true), "recipes": @json.Json::array(items) }), - 274
) - 275
} - 276●
if path.has_prefix("/recipe/") { - 277●
let name = path[8:].to_owned() - 278
if verb != "POST" { - 279●
return Reply( - 280
405, - 281
"application/json", - 282●
err_body( - 283
"method_not_allowed", "recipe 只接受 POST", "把图片字节放进请求体", - 284
), - 285
) - 286
} - 287●
if !is_known_recipe(name) { - 288●
return Reply( - 289
404, - 290
"application/json", - 291●
err_body( - 292
"unknown_recipe", - 293
"未注册的 Recipe:\{name}", - 294
"GET /recipes 看全部 8 条", - 295
), - 296
) - 297
} - 298
// 预算先于读取:Content-Length 超了就直接 413,一个字节都不读进内存。 - 299
if declared > ctx.mem_budget { - 300●
return Reply( - 301
413, - 302
"application/json", - 303●
err_body( - 304
"budget/limit_bytes", - 305
"请求体 \{declared} 字节超过 --mem-budget \{ctx.mem_budget}", - 306
"调高 --mem-budget 或先缩图再发", - 307
), - 308
) - 309
} - 310
return NeedBody(name, query) - 311
} - 312
Reply( - 313
404, - 314
"application/json", - 315●
err_body( - 316
"unknown_path", - 317
"没有这条路由:\{path}", - 318
"GET /healthz · GET /version · GET /recipes · POST /recipe/<name>", - 319
), - 320
) - 321
} - 322
- 323
///| - 324
/// 读请求体:失败给 `None`,由调用方决定回什么(读失败不是「空体」)。 - 325
#cfg(target="native") - 326
async fn read_body(conn : @http.ServerConnection) -> Bytes? { - 327○
let b = conn.read_all() catch { _ => return None } - 328
Some(b) - 329
} - 330
- 331
///| - 332
/// 请求体到手之后的全部工作:空体 / 超预算 / 跑 Recipe / 决定回图还是回 JSON。 - 333
/// 纯同步(`run_recipe` 本身是同步的),因此也能单测。 - 334
#cfg(target="native") - 335
fn recipe_reply( - 336
name : String, - 337
in_bytes : Bytes, - 338
query : Map[String, String], - 339
headers : @http.Headers, - 340
ctx : ServeCtx, - 341
) -> (Int32, String, Bytes) { - 342●
if in_bytes.length() == 0 { - 343●
return ( - 344
400, - 345
"application/json", - 346●
err_body( - 347
"decode/empty", "请求体为空", "POST /recipe/<name> 时把图片字节放进 body", - 348
), - 349
) - 350
} - 351●
if in_bytes.length() > ctx.mem_budget { - 352●
return ( - 353
413, - 354
"application/json", - 355●
err_body( - 356
"budget/limit_bytes", - 357
"请求体 \{in_bytes.length()} 字节超过 --mem-budget \{ctx.mem_budget}", - 358
"调高 --mem-budget 或先缩图再发", - 359
), - 360
) - 361
} - 362●
let opts = opts_of(query) - 363●
let r = @recipe.run_recipe(name, in_bytes, opts) catch { - 364
e => - 365●
return ( - 366●
status_of_image_error(e), - 367
"application/json", - 368●
json_bytes(error_json(e)), - 369
) - 370
} - 371●
if query.get("dry-run") == Some("1") || wants_json(headers, query) { - 372●
let steps : Array[@json.Json] = [] - 373
for s in r.steps { - 374●
steps.push( - 375●
@json.Json::object({ - 376●
"name": jstr(s.name), - 377●
"width": jnum(s.width), - 378●
"height": jnum(s.height), - 379●
"bytes": jnum(s.bytes), - 380●
"ms": jnum(s.ms.to_int()), - 381
}), - 382
) - 383
} - 384
return ( - 385
200, - 386
"application/json", - 387●
json_bytes({ - 388●
"ok": jbool(true), - 389●
"recipe": jstr(r.recipe), - 390●
"width": jnum(r.image.width()), - 391●
"height": jnum(r.image.height()), - 392●
"channels": jnum(r.image.channels()), - 393●
"bytes": jnum(r.bytes.length().to_int()), - 394●
"format": jstr(format_name(r.format)), - 395●
"quality": jnum(r.quality), - 396●
"steps": @json.Json::array(steps), - 397
}), - 398
) - 399
} - 400●
(200, mime_of(r.format), r.bytes) - 401
} - 402
- 403
// --------------------------------------------------------------------------- - 404
// 小工具 - 405
// --------------------------------------------------------------------------- - 406
- 407
///| - 408
#cfg(target="native") - 409
fn split_path_query(raw : String) -> (String, Map[String, String]) { - 410●
match raw.find("?") { - 411●
Some(i) => (raw[0:i].to_owned(), parse_query(raw[i + 1:].to_owned())) - 412●
None => (raw, Map([])) - 413
} - 414
} - 415
- 416
///| - 417
#cfg(target="native") - 418
fn parse_query(s : String) -> Map[String, String] { - 419●
let out : Map[String, String] = Map([]) - 420●
for pair_v in s.split("&") { - 421●
let pair = pair_v.to_owned() - 422●
if pair.length() == 0 { - 423●
continue - 424
} - 425●
match pair.find("=") { - 426●
Some(i) => out[pair[0:i].to_owned()] = pair[i + 1:].to_owned() - 427●
None => out[pair] = "1" - 428
} - 429
} - 430
out - 431
} - 432
- 433
///| - 434
#cfg(target="native") - 435
fn verb_of(m : @http.RequestMethod) -> String { - 436●
match m { - 437●
@http.RequestMethod::Get => "GET" - 438●
@http.RequestMethod::Post => "POST" - 439●
@http.RequestMethod::Head => "HEAD" - 440○
_ => "OTHER" - 441
} - 442
} - 443
- 444
///| - 445
#cfg(target="native") - 446
fn declared_length(headers : @http.Headers) -> Int32 { - 447●
match headers.get(@http.CaseInsensitiveString("content-length")) { - 448
Some(s) => - 449●
match parse_int(s.trim().to_owned()) { - 450●
Some(n) => n - 451●
None => -1 - 452
} - 453●
None => -1 - 454
} - 455
} - 456
- 457
///| - 458
#cfg(target="native") - 459
fn warns_json(headers : @http.Headers) -> Bool { - 460●
match headers.get(@http.CaseInsensitiveString("accept")) { - 461●
Some(a) => a.contains("application/json") - 462●
None => false - 463
} - 464
} - 465
- 466
///| - 467
#cfg(target="native") - 468
fn wants_json(headers : @http.Headers, query : Map[String, String]) -> Bool { - 469●
match query.get("format") { - 470●
Some(f) => f == "json" - 471●
None => warns_json(headers) - 472
} - 473
} - 474
- 475
///| - 476
#cfg(target="native") - 477
fn is_known_recipe(name : String) -> Bool { - 478●
for n in @recipe.recipe_names() { - 479●
if n == name { - 480●
return true - 481
} - 482
} - 483
false - 484
} - 485
- 486
///| - 487
#cfg(target="native") - 488
fn opts_of(query : Map[String, String]) -> @recipe.RecipeOpts { - 489●
let mut opts = @recipe.RecipeOpts::new() - 490●
match query.get("format") { - 491
Some(f) => - 492●
match format_of(f) { - 493●
Some(fmt) => opts = { ..opts, format: fmt, } - 494●
None => () - 495
} - 496●
None => () - 497
} - 498●
match query.get("quality") { - 499
Some(q) => - 500●
match parse_int(q) { - 501●
Some(n) => opts = { ..opts, quality: n, } - 502●
None => () - 503
} - 504●
None => () - 505
} - 506●
match query.get("max-bytes") { - 507
Some(b) => - 508●
match parse_int(b) { - 509●
Some(n) => opts = { ..opts, max_bytes: n, } - 510○
None => () - 511
} - 512●
None => () - 513
} - 514●
match query.get("longest") { - 515
Some(l) => - 516●
match parse_int(l) { - 517●
Some(n) => opts = { ..opts, longest: n, } - 518●
None => () - 519
} - 520●
None => () - 521
} - 522
opts - 523
} - 524
- 525
///| - 526
#cfg(target="native") - 527
fn format_of(s : String) -> @types.ImageFormat? { - 528●
match s { - 529●
"png" => Some(@types.ImageFormat::Png) - 530●
"jpeg" | "jpg" => Some(@types.ImageFormat::Jpeg) - 531●
"webp" => Some(@types.ImageFormat::Webp) - 532●
"pnm" | "pgm" | "ppm" => Some(@types.ImageFormat::Pnm) - 533●
"bmp" => Some(@types.ImageFormat::Bmp) - 534●
"qoi" => Some(@types.ImageFormat::Qoi) - 535●
_ => None - 536
} - 537
} - 538
- 539
///| - 540
#cfg(target="native") - 541
fn mime_of(f : @types.ImageFormat) -> String { - 542●
match f { - 543●
@types.ImageFormat::Png => "image/png" - 544●
@types.ImageFormat::Jpeg => "image/jpeg" - 545●
@types.ImageFormat::Webp => "image/webp" - 546●
@types.ImageFormat::Pnm => "image/x-portable-anymap" - 547●
@types.ImageFormat::Bmp => "image/bmp" - 548●
@types.ImageFormat::Qoi => "image/qoi" - 549●
_ => "application/octet-stream" - 550
} - 551
} - 552
- 553
///| - 554
#cfg(target="native") - 555
fn reason_of(code : Int32) -> String { - 556●
match code { - 557●
200 => "OK" - 558●
400 => "Bad Request" - 559●
404 => "Not Found" - 560●
405 => "Method Not Allowed" - 561●
413 => "Payload Too Large" - 562●
422 => "Unprocessable Entity" - 563○
503 => "Service Unavailable" - 564●
_ => "Internal Server Error" - 565
} - 566
} - 567
- 568
///| - 569
#cfg(target="native") - 570
fn status_of_image_error(e : @types.ImageError) -> Int32 { - 571●
let code = e.code() - 572●
if code.has_prefix("decode/") { - 573●
400 - 574●
} else if code == "budget/limit_bytes" { - 575●
413 - 576●
} else if code.has_prefix("budget/") || code.has_prefix("process/") { - 577●
422 - 578
} else { - 579○
500 - 580
} - 581
} - 582
- 583
///| - 584
#cfg(target="native") - 585
fn json_bytes(out : Out) -> Bytes { - 586●
@utf8.encode(@json.Json::object(out).stringify()) - 587
} - 588
- 589
///| - 590
#cfg(target="native") - 591
fn err_body(code : String, message : String, hint : String) -> Bytes { - 592●
json_bytes({ - 593●
"ok": jbool(false), - 594●
"code": jstr(code), - 595●
"message": jstr(message), - 596●
"hint": jstr(hint), - 597
}) - 598
} - 599
- 600
///| - 601
/// 十进制解析:复用 core 的 `parse_int`,失败给 `None`(query 参数是用户输入,不能 abort)。 - 602
#cfg(target="native") - 603
fn parse_int(s : String) -> Int32? { - 604●
let v = @string.parse_int(s) catch { _ => return None } - 605
Some(v) - 606
} - 607
- 608
///| - 609
#cfg(target="native") - 610
fn ms_text(us : Int64) -> String { - 611●
let ms = us / 1000 - 612●
let frac = (us % 1000).to_int() - 613
let f = if frac < 10 { - 614●
"00" + frac.to_string() - 615●
} else if frac < 100 { - 616●
"0" + frac.to_string() - 617
} else { - 618●
frac.to_string() - 619
} - 620●
ms.to_string() + "." + f - 621
}