| 2163 | } |
| 2164 | |
| 2165 | void cbm_http_server_run(cbm_http_server_t *srv) { |
| 2166 | if (!srv) |
| 2167 | return; |
| 2168 | int expected = HTTP_RUN_SCHEDULED; |
| 2169 | if (!atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_RUNNING, |
| 2170 | memory_order_acq_rel, memory_order_acquire)) |
| 2171 | return; |
| 2172 | if (!srv->listener_ok) { |
| 2173 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 2174 | return; |
| 2175 | } |
| 2176 | |
| 2177 | while (!atomic_load(&srv->stop_flag)) { |
| 2178 | cbm_http_conn_t *conn = cbm_httpd_accept(srv->listener, 200); |
| 2179 | if (!conn) |
| 2180 | continue; /* timeout — re-check stop flag */ |
| 2181 | |
| 2182 | uint64_t request_start_ms = cbm_now_ms(); |
| 2183 | cbm_http_req_t req; |
| 2184 | int rc = cbm_httpd_read_request(conn, &req); |
| 2185 | if (rc == 0) { |
| 2186 | if (atomic_load(&srv->stop_flag)) { |
| 2187 | cbm_http_req_free(&req); |
| 2188 | cbm_httpd_conn_close(conn); |
| 2189 | break; |
| 2190 | } |
| 2191 | dispatch_request(srv, conn, &req); |
| 2192 | cbm_log_http_request("graph_ui", req.method, req.path, cbm_http_conn_status(conn), |
| 2193 | (int64_t)(cbm_now_ms() - request_start_ms), req.body_len, |
| 2194 | cbm_http_conn_response_bytes(conn)); |
| 2195 | cbm_http_req_free(&req); |
| 2196 | } else if (rc > 0) { |
| 2197 | /* Parse/transport error with a known HTTP status (400/408/411/413/431). |
| 2198 | * No CORS reflection here — the request was never parsed. */ |
| 2199 | cbm_http_replyf(conn, rc, "", "bad request"); |
| 2200 | cbm_log_http_request("graph_ui", "", "", cbm_http_conn_status(conn), |
| 2201 | (int64_t)(cbm_now_ms() - request_start_ms), 0, |
| 2202 | cbm_http_conn_response_bytes(conn)); |
| 2203 | } |
| 2204 | cbm_httpd_conn_close(conn); |
| 2205 | } |
| 2206 | atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release); |
| 2207 | } |
| 2208 | |
| 2209 | cbm_httpd_activity_t cbm_http_server_activity_for_test(cbm_http_server_t *srv) { |
| 2210 | return srv ? cbm_httpd_activity_for_test(srv->listener) : CBM_HTTPD_ACTIVITY_IDLE; |