| 3552 | } |
| 3553 | |
| 3554 | void cbm_http_server_run(cbm_http_server_t *srv) { |
| 3555 | if (!srv) |
| 3556 | return; |
| 3557 | int expected = HTTP_RUN_SCHEDULED; |
| 3558 | if (!atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_RUNNING, |
| 3559 | memory_order_acq_rel, memory_order_acquire)) |
| 3560 | return; |
| 3561 | if (!srv->listener_ok) { |
| 3562 | cbm_mem_class_flush_thread(); |
| 3563 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 3564 | return; |
| 3565 | } |
| 3566 | |
| 3567 | while (!atomic_load(&srv->stop_flag)) { |
| 3568 | cbm_http_conn_t *conn = cbm_httpd_accept(srv->listener, 200); |
| 3569 | if (!conn) |
| 3570 | continue; /* timeout — re-check stop flag */ |
| 3571 | |
| 3572 | uint64_t request_start_ms = cbm_now_ms(); |
| 3573 | cbm_http_req_t req; |
| 3574 | int rc = cbm_httpd_read_request(conn, &req); |
| 3575 | if (rc == 0) { |
| 3576 | if (atomic_load(&srv->stop_flag)) { |
| 3577 | cbm_http_req_free(&req); |
| 3578 | cbm_httpd_conn_close(conn); |
| 3579 | break; |
| 3580 | } |
| 3581 | dispatch_request(srv, conn, &req); |
| 3582 | cbm_log_http_request("graph_ui", req.method, req.path, cbm_http_conn_status(conn), |
| 3583 | (int64_t)(cbm_now_ms() - request_start_ms), req.body_len, |
| 3584 | cbm_http_conn_response_bytes(conn)); |
| 3585 | cbm_http_req_free(&req); |
| 3586 | } else if (rc > 0) { |
| 3587 | /* Parse/transport error with a known HTTP status (400/408/411/413/431). |
| 3588 | * No CORS reflection here — the request was never parsed. */ |
| 3589 | cbm_http_replyf(conn, rc, "", "bad request"); |
| 3590 | cbm_log_http_request("graph_ui", "", "", cbm_http_conn_status(conn), |
| 3591 | (int64_t)(cbm_now_ms() - request_start_ms), 0, |
| 3592 | cbm_http_conn_response_bytes(conn)); |
| 3593 | } |
| 3594 | cbm_httpd_conn_close(conn); |
| 3595 | /* Retained response caches can be released by a different thread. */ |
| 3596 | cbm_mem_class_flush_thread(); |
| 3597 | } |
| 3598 | cbm_mem_class_flush_thread(); |
| 3599 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 3600 | } |
| 3601 | |
| 3602 | cbm_httpd_activity_t cbm_http_server_activity_for_test(cbm_http_server_t *srv) { |
| 3603 | return srv ? cbm_httpd_activity_for_test(srv->listener) : CBM_HTTPD_ACTIVITY_IDLE; |