POST /api/adr — save ADR content. Body: {"project":"...","content":"..."} */
| 1419 | |
| 1420 | /* POST /api/adr — save ADR content. Body: {"project":"...","content":"..."} */ |
| 1421 | static void handle_adr_save(cbm_http_server_t *srv, cbm_http_conn_t *c, const cbm_http_req_t *req) { |
| 1422 | if (req->body_len == 0 || req->body_len > 16384) { |
| 1423 | cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"invalid body\"}"); |
| 1424 | return; |
| 1425 | } |
| 1426 | |
| 1427 | yyjson_doc *doc = yyjson_read(req->body, req->body_len, 0); |
| 1428 | if (!doc) { |
| 1429 | cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"invalid json\"}"); |
| 1430 | return; |
| 1431 | } |
| 1432 | |
| 1433 | yyjson_val *root = yyjson_doc_get_root(doc); |
| 1434 | yyjson_val *v_proj = yyjson_obj_get(root, "project"); |
| 1435 | yyjson_val *v_content = yyjson_obj_get(root, "content"); |
| 1436 | if (!v_proj || !yyjson_is_str(v_proj) || !v_content || !yyjson_is_str(v_content)) { |
| 1437 | yyjson_doc_free(doc); |
| 1438 | cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"missing project or content\"}"); |
| 1439 | return; |
| 1440 | } |
| 1441 | |
| 1442 | const char *proj = yyjson_get_str(v_proj); |
| 1443 | const char *content = yyjson_get_str(v_content); |
| 1444 | |
| 1445 | if (srv->mutation_begin && !srv->mutation_begin(srv->mutation_context, proj)) { |
| 1446 | yyjson_doc_free(doc); |
| 1447 | cbm_http_replyf(c, 423, g_cors_json, |
| 1448 | "{\"error\":\"project is busy; retry after indexing\"}"); |
| 1449 | return; |
| 1450 | } |
| 1451 | bool mutation_held = srv->mutation_begin != NULL; |
| 1452 | |
| 1453 | char db_path[1024]; |
| 1454 | db_path_for_project(proj, db_path, sizeof(db_path)); |
| 1455 | |
| 1456 | cbm_store_t *store = cbm_store_open_path(db_path); |
| 1457 | if (!store) { |
| 1458 | if (mutation_held) { |
| 1459 | srv->mutation_end(srv->mutation_context, proj); |
| 1460 | } |
| 1461 | yyjson_doc_free(doc); |
| 1462 | cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"cannot open store\"}"); |
| 1463 | return; |
| 1464 | } |
| 1465 | |
| 1466 | int rc = cbm_store_adr_store(store, proj, content); |
| 1467 | cbm_store_close(store); |
| 1468 | if (mutation_held) { |
| 1469 | srv->mutation_end(srv->mutation_context, proj); |
| 1470 | } |
| 1471 | /* proj/content are owned by doc; keep it alive through both SQLite and |
| 1472 | * the mutation-end callback. */ |
| 1473 | yyjson_doc_free(doc); |
| 1474 | |
| 1475 | if (rc == CBM_STORE_OK) { |
| 1476 | cbm_http_replyf(c, 200, g_cors_json, "{\"saved\":true}"); |
| 1477 | } else { |
| 1478 | cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"save failed\"}"); |
no test coverage detected