#include "errors.hpp" #include "function_record.hpp" #include "json_http.hpp" #include "project_settings.hpp" #include "server.hpp" #include #include #include namespace svapi { namespace { /// The runner pool, or 503. /// /// "No runner configured" and "every runner is down" are the same answer to the /// caller: the route exists, the capability behind it does not right now. It is /// never a 404 - a 404 would say the function feature is not part of this API. RunnerPool& requireRunner(ServerDeps& d) { if (d.runners == nullptr) throw ApiError(ErrCode::Unavailable, "no_runner", "no function runner is configured on this server"); if (!d.runners->anyHealthy()) throw ApiError(ErrCode::Unavailable, "no_runner", "no healthy function runner is available"); return *d.runners; } /// What a code push carries. `policy` is deliberately absent: see below. struct CodePush { std::string source; std::string path; }; CodePush codePush(const nlohmann::json& body) { if (!body.is_object()) throw ApiError(ErrCode::Unprocessable, "validation", "the body must be an object"); if (!body.contains("source") || !body["source"].is_string() || body["source"].get().empty()) throw ApiError(ErrCode::Unprocessable, "validation", "source is required"); if (body.contains("path") && !body["path"].is_string()) throw ApiError(ErrCode::Unprocessable, "validation", "path must be a string"); // A `policy` field in a code push is IGNORED, not rejected: a client that // GETs a function and PUTs it back would otherwise be unable to write at // all, and ignoring the field has no escalation failure mode, while // "is this narrower than what is stored?" is where one would live (design // doc, Addendum). Policy changes go through the admin-only policy route. return {body["source"].get(), body.value("path", "")}; } /// Compile the push on a runner and turn the result into a storable row. /// /// The engine that validates is the engine that will execute, so nothing is /// stored that has not compiled on a real runner. FunctionRecord validateOnRunner(ServerDeps& d, const CodePush& push) { RunnerValidateResult v = requireRunner(d).validate(push.source, push.path); if (v.transportFailure) throw ApiError(ErrCode::Unavailable, "runner_unreachable", v.error.empty() ? "the function runner could not be reached" : v.error); if (!v.ok) throw ApiError(ErrCode::Unprocessable, "compile_failed", v.error.empty() ? "the function did not compile" : v.error); const std::string declared = v.descriptor.is_object() ? v.descriptor.value("id", std::string()) : std::string(); if (declared.empty()) throw ApiError(ErrCode::Unprocessable, "missing_function_id", "the script's `on` block must declare an id; the file path is never " "used as a fallback"); FunctionRecord rec; rec.functionId = declared; rec.path = push.path; rec.source = push.source; rec.contentHash = functionContentHash(push.source); rec.descriptor = v.descriptor; rec.valid = true; return rec; } /// The policy a first registration inherits: the project's configured /// `default_function_policy`, else the built-in floor, which grants no /// collection at all. /// /// Only ever consulted for a FIRST registration - mergeForCodePush keeps an /// existing function's policy - so changing a project's default never /// retroactively alters anything already deployed. KeyScope projectDefaultPolicy(ServerDeps& d, const std::string& project) { const auto proj = d.settings.projectSnapshot(project); return defaultFunctionPolicyFor(proj.get()); } /// Validate and read a policy document. Shaped like keys.cpp parseScope, with /// one deliberate difference: an empty rule set is legal here. It is the /// deny-everything default a function starts on, so an admin must be able to /// put it back. KeyScope parsePolicy(const nlohmann::json& body) { // {"policy":{...}} and a bare scope object are both unambiguous, so both // are accepted - the admin UI sends the first, a curl the second. const nlohmann::json& p = body.contains("policy") ? body.at("policy") : body; if (!p.is_object()) throw ApiError(ErrCode::Unprocessable, "validation", "policy must be an object"); if (p.contains("rules")) { if (!p["rules"].is_array()) throw ApiError(ErrCode::Unprocessable, "validation", "policy.rules must be an array"); for (const auto& r : p["rules"]) { if (!r.is_object() || r.value("collection", std::string()).empty()) throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs a collection"); if (!r.contains("ops") || !r["ops"].is_array() || r["ops"].empty()) throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs ops"); for (const auto& o : r["ops"]) if (!o.is_string() || !keyOpFromString(o.get())) throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in policy"); } } return KeyScope::fromJson(p); } /// A function that cannot run, as an error - or nothing. /// /// 409 rather than 422: the request is fine, the server's state refuses it, and /// the caller fixes it by enabling or re-pushing the function, not by editing /// the request. void requireRunnable(const FunctionRecord& fn) { if (!fn.valid) throw ApiError(ErrCode::Conflict, "function_invalid", fn.lastError.empty() ? "this function is marked invalid" : fn.lastError); if (!fn.enabled) throw ApiError(ErrCode::Conflict, "function_disabled", "this function is disabled"); } uint32_t limitParam(const httplib::Request& req, uint32_t fallback) { if (!req.has_param("limit")) return fallback; const std::string raw = req.get_param_value("limit"); if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos) throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer"); unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10); if (wide == 0 || wide > std::numeric_limits::max()) throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer"); return static_cast(wide); } /// The trigger a manual invoke synthesises. Every field is optional: invoking a /// function with no body is the common case ("does it still run?"), so the /// defaults have to produce a usable request. nlohmann::json manualTrigger(const FunctionRecord& fn, const nlohmann::json& body) { const std::string route = fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string(); nlohmann::json t; t["method"] = body.value("method", std::string("POST")); t["path"] = body.value("path", route); t["params"] = body.contains("params") && body["params"].is_object() ? body["params"] : nlohmann::json::object(); t["query"] = body.contains("query") && body["query"].is_object() ? body["query"] : nlohmann::json::object(); t["headers"] = body.contains("headers") && body["headers"].is_object() ? body["headers"] : nlohmann::json::object(); t["body"] = body.contains("body") ? body["body"] : nlohmann::json(); return t; } nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) { return {{"run_id", runId}, {"ok", r.ok}, {"status", r.status}, {"headers", r.headers}, {"body", r.body}, {"console", r.console}, {"duration_ms", r.durationMs}, {"error", r.error}, {"timed_out", r.timedOut}, {"out_of_memory", r.outOfMemory}}; } } // namespace void registerFunctionRoutes(ApiServer& s) { auto& svr = s.raw(); ServerDeps* d = &s.deps(); svr.Get(R"(/api/v1/projects/([^/]+)/functions)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1]; requireProjectManage(requireKey(*d, req), project); d->functions.ensure(project); nlohmann::json arr = nlohmann::json::array(); // Summaries, never full rows: a listing that shipped every function's // source would grow without bound in the one response people poll. for (const auto& fn : d->functions.list(project)) arr.push_back(fn.toSummaryJson()); sendJson(res, 200, {{"functions", arr}}); }); svr.Post(R"(/api/v1/projects/([^/]+)/functions)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1]; requireProjectManage(requireKey(*d, req), project); FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req))); // POST creates. An id that already exists is a genuine conflict, and // answering 409 keeps a second author from quietly overwriting the // first's code just because both chose the same `on.id`. if (d->functions.get(project, incoming.functionId)) throw ApiError(ErrCode::Conflict, "function_exists", "a function with this id already exists - PUT it to update", {{"function_id", incoming.functionId}}); FunctionRecord stored = d->functions.put(project, incoming, projectDefaultPolicy(*d, project)); sendJson(res, 201, stored.toSummaryJson()); }); svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); auto fn = d->functions.get(project, id); if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); sendJson(res, 200, fn->toJson()); // the single-function view carries the source }); svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req))); // The id lives in the source, so the URL cannot rename a function. Say // which is which: silently trusting either one would either move the // code to another function's row or move a policy to other code. if (incoming.functionId != id) throw ApiError(ErrCode::Unprocessable, "id_mismatch", "the script's `on` block declares id '" + incoming.functionId + "' but the URL names '" + id + "' - the id is part of the source, not of the URL", {{"declared", incoming.functionId}, {"url", id}}); const bool existed = d->functions.get(project, id).has_value(); // put() preserves the stored policy and enabled flag via // mergeForCodePush, which is why a push can never widen access. FunctionRecord stored = d->functions.put(project, incoming, projectDefaultPolicy(*d, project)); sendJson(res, existed ? 200 : 201, stored.toSummaryJson()); }); svr.Delete(R"(/api/v1/projects/([^/]+)/functions/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); if (!d->functions.remove(project, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); sendJson(res, 200, {{"deleted", id}}); }); // ADMIN ONLY, and the only route that changes a policy. Developers push // code, admins grant what it may touch - the same split keys already have. svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/policy)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireAdmin(requireKey(*d, req)); KeyScope policy = parsePolicy(bodyJson(req)); if (!d->functions.setPolicy(project, id, policy)) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); auto fn = d->functions.get(project, id); if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); sendJson(res, 200, fn->toSummaryJson()); }); svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/enabled)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); auto body = bodyJson(req); if (!body.contains("enabled") || !body["enabled"].is_boolean()) throw ApiError(ErrCode::Unprocessable, "validation", "enabled must be a boolean"); if (!d->functions.setEnabled(project, id, body["enabled"].get())) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); sendJson(res, 200, {{"function_id", id}, {"enabled", body["enabled"].get()}}); }); svr.Post(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/invoke)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); auto fn = d->functions.get(project, id); if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); requireRunnable(*fn); RunnerPool& pool = requireRunner(*d); const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req); // A run id is just a random token with no secret meaning; generateApiKey // is reused rather than adding a second hex generator. const std::string runId = generateApiKey(); const uint64_t startedAt = static_cast(std::time(nullptr)); RunnerRunResult r = pool.run(project, id, manualTrigger(*fn, body)); FunctionRunLog entry; entry.runId = runId; entry.functionId = id; entry.trigger = "invoke"; entry.ok = r.ok; entry.status = r.status; entry.durationMs = r.durationMs; entry.error = r.error; entry.console = r.console; entry.startedAt = startedAt; // Logged before the 503 below: an attempt that never reached a runner is // exactly the one an operator goes looking for afterwards. d->functionRuns.append(project, entry); if (r.transportFailure) throw ApiError(ErrCode::Unavailable, "runner_unreachable", r.error.empty() ? "the function runner could not be reached" : r.error, {{"run_id", runId}}); // 200 even when the function itself failed: an invoke REPORTS a run, it // does not serve it. The function's own status lives in the envelope, and // flattening it into the HTTP status would make "the function returned // 500" indistinguishable from "the invoke could not be performed". sendJson(res, 200, runEnvelope(runId, r)); }); svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/logs)", [d](const httplib::Request& req, httplib::Response& res) { std::string project = req.matches[1], id = req.matches[2]; requireProjectManage(requireKey(*d, req), project); if (!d->functions.get(project, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such function"); nlohmann::json arr = nlohmann::json::array(); for (const auto& e : d->functionRuns.list(project, id, limitParam(req, 50))) arr.push_back(e.toJson()); sendJson(res, 200, {{"function_id", id}, {"runs", arr}}); }); } } // namespace svapi