functions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #include "errors.hpp"
  2. #include "function_record.hpp"
  3. #include "json_http.hpp"
  4. #include "project_settings.hpp"
  5. #include "server.hpp"
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <limits>
  9. namespace svapi {
  10. namespace {
  11. /// The runner pool, or 503.
  12. ///
  13. /// "No runner configured" and "every runner is down" are the same answer to the
  14. /// caller: the route exists, the capability behind it does not right now. It is
  15. /// never a 404 - a 404 would say the function feature is not part of this API.
  16. RunnerPool& requireRunner(ServerDeps& d) {
  17. if (d.runners == nullptr)
  18. throw ApiError(ErrCode::Unavailable, "no_runner",
  19. "no function runner is configured on this server");
  20. if (!d.runners->anyHealthy())
  21. throw ApiError(ErrCode::Unavailable, "no_runner",
  22. "no healthy function runner is available");
  23. return *d.runners;
  24. }
  25. /// What a code push carries. `policy` is deliberately absent: see below.
  26. struct CodePush {
  27. std::string source;
  28. std::string path;
  29. };
  30. CodePush codePush(const nlohmann::json& body) {
  31. if (!body.is_object())
  32. throw ApiError(ErrCode::Unprocessable, "validation", "the body must be an object");
  33. if (!body.contains("source") || !body["source"].is_string() ||
  34. body["source"].get<std::string>().empty())
  35. throw ApiError(ErrCode::Unprocessable, "validation", "source is required");
  36. if (body.contains("path") && !body["path"].is_string())
  37. throw ApiError(ErrCode::Unprocessable, "validation", "path must be a string");
  38. // A `policy` field in a code push is IGNORED, not rejected: a client that
  39. // GETs a function and PUTs it back would otherwise be unable to write at
  40. // all, and ignoring the field has no escalation failure mode, while
  41. // "is this narrower than what is stored?" is where one would live (design
  42. // doc, Addendum). Policy changes go through the admin-only policy route.
  43. return {body["source"].get<std::string>(), body.value("path", "")};
  44. }
  45. /// Compile the push on a runner and turn the result into a storable row.
  46. ///
  47. /// The engine that validates is the engine that will execute, so nothing is
  48. /// stored that has not compiled on a real runner.
  49. FunctionRecord validateOnRunner(ServerDeps& d, const CodePush& push) {
  50. RunnerValidateResult v = requireRunner(d).validate(push.source, push.path);
  51. if (v.transportFailure)
  52. throw ApiError(ErrCode::Unavailable, "runner_unreachable",
  53. v.error.empty() ? "the function runner could not be reached" : v.error);
  54. if (!v.ok)
  55. throw ApiError(ErrCode::Unprocessable, "compile_failed",
  56. v.error.empty() ? "the function did not compile" : v.error);
  57. const std::string declared =
  58. v.descriptor.is_object() ? v.descriptor.value("id", std::string()) : std::string();
  59. if (declared.empty())
  60. throw ApiError(ErrCode::Unprocessable, "missing_function_id",
  61. "the script's `on` block must declare an id; the file path is never "
  62. "used as a fallback");
  63. FunctionRecord rec;
  64. rec.functionId = declared;
  65. rec.path = push.path;
  66. rec.source = push.source;
  67. rec.contentHash = functionContentHash(push.source);
  68. rec.descriptor = v.descriptor;
  69. rec.valid = true;
  70. return rec;
  71. }
  72. /// The policy a first registration inherits: the project's configured
  73. /// `default_function_policy`, else the built-in floor, which grants no
  74. /// collection at all.
  75. ///
  76. /// Only ever consulted for a FIRST registration - mergeForCodePush keeps an
  77. /// existing function's policy - so changing a project's default never
  78. /// retroactively alters anything already deployed.
  79. KeyScope projectDefaultPolicy(ServerDeps& d, const std::string& project) {
  80. const auto proj = d.settings.projectSnapshot(project);
  81. return defaultFunctionPolicyFor(proj.get());
  82. }
  83. /// Validate and read a policy document. Shaped like keys.cpp parseScope, with
  84. /// one deliberate difference: an empty rule set is legal here. It is the
  85. /// deny-everything default a function starts on, so an admin must be able to
  86. /// put it back.
  87. KeyScope parsePolicy(const nlohmann::json& body) {
  88. // {"policy":{...}} and a bare scope object are both unambiguous, so both
  89. // are accepted - the admin UI sends the first, a curl the second.
  90. const nlohmann::json& p = body.contains("policy") ? body.at("policy") : body;
  91. if (!p.is_object())
  92. throw ApiError(ErrCode::Unprocessable, "validation", "policy must be an object");
  93. if (p.contains("rules")) {
  94. if (!p["rules"].is_array())
  95. throw ApiError(ErrCode::Unprocessable, "validation", "policy.rules must be an array");
  96. for (const auto& r : p["rules"]) {
  97. if (!r.is_object() || r.value("collection", std::string()).empty())
  98. throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs a collection");
  99. if (!r.contains("ops") || !r["ops"].is_array() || r["ops"].empty())
  100. throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs ops");
  101. for (const auto& o : r["ops"])
  102. if (!o.is_string() || !keyOpFromString(o.get<std::string>()))
  103. throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in policy");
  104. }
  105. }
  106. return KeyScope::fromJson(p);
  107. }
  108. /// A function that cannot run, as an error - or nothing.
  109. ///
  110. /// 409 rather than 422: the request is fine, the server's state refuses it, and
  111. /// the caller fixes it by enabling or re-pushing the function, not by editing
  112. /// the request.
  113. void requireRunnable(const FunctionRecord& fn) {
  114. if (!fn.valid)
  115. throw ApiError(ErrCode::Conflict, "function_invalid",
  116. fn.lastError.empty() ? "this function is marked invalid" : fn.lastError);
  117. if (!fn.enabled)
  118. throw ApiError(ErrCode::Conflict, "function_disabled", "this function is disabled");
  119. }
  120. uint32_t limitParam(const httplib::Request& req, uint32_t fallback) {
  121. if (!req.has_param("limit")) return fallback;
  122. const std::string raw = req.get_param_value("limit");
  123. if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
  124. throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
  125. unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
  126. if (wide == 0 || wide > std::numeric_limits<uint32_t>::max())
  127. throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
  128. return static_cast<uint32_t>(wide);
  129. }
  130. /// The trigger a manual invoke synthesises. Every field is optional: invoking a
  131. /// function with no body is the common case ("does it still run?"), so the
  132. /// defaults have to produce a usable request.
  133. nlohmann::json manualTrigger(const FunctionRecord& fn, const nlohmann::json& body) {
  134. const std::string route =
  135. fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string();
  136. nlohmann::json t;
  137. t["method"] = body.value("method", std::string("POST"));
  138. t["path"] = body.value("path", route);
  139. t["params"] = body.contains("params") && body["params"].is_object()
  140. ? body["params"] : nlohmann::json::object();
  141. t["query"] = body.contains("query") && body["query"].is_object()
  142. ? body["query"] : nlohmann::json::object();
  143. t["headers"] = body.contains("headers") && body["headers"].is_object()
  144. ? body["headers"] : nlohmann::json::object();
  145. t["body"] = body.contains("body") ? body["body"] : nlohmann::json();
  146. return t;
  147. }
  148. nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) {
  149. return {{"run_id", runId},
  150. {"ok", r.ok},
  151. {"status", r.status},
  152. {"headers", r.headers},
  153. {"body", r.body},
  154. {"console", r.console},
  155. {"duration_ms", r.durationMs},
  156. {"error", r.error},
  157. {"timed_out", r.timedOut},
  158. {"out_of_memory", r.outOfMemory}};
  159. }
  160. } // namespace
  161. void registerFunctionRoutes(ApiServer& s) {
  162. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  163. svr.Get(R"(/api/v1/projects/([^/]+)/functions)",
  164. [d](const httplib::Request& req, httplib::Response& res) {
  165. std::string project = req.matches[1];
  166. requireProjectManage(requireKey(*d, req), project);
  167. d->functions.ensure(project);
  168. nlohmann::json arr = nlohmann::json::array();
  169. // Summaries, never full rows: a listing that shipped every function's
  170. // source would grow without bound in the one response people poll.
  171. for (const auto& fn : d->functions.list(project)) arr.push_back(fn.toSummaryJson());
  172. sendJson(res, 200, {{"functions", arr}});
  173. });
  174. svr.Post(R"(/api/v1/projects/([^/]+)/functions)",
  175. [d](const httplib::Request& req, httplib::Response& res) {
  176. std::string project = req.matches[1];
  177. requireProjectManage(requireKey(*d, req), project);
  178. FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
  179. // POST creates. An id that already exists is a genuine conflict, and
  180. // answering 409 keeps a second author from quietly overwriting the
  181. // first's code just because both chose the same `on.id`.
  182. if (d->functions.get(project, incoming.functionId))
  183. throw ApiError(ErrCode::Conflict, "function_exists",
  184. "a function with this id already exists - PUT it to update",
  185. {{"function_id", incoming.functionId}});
  186. FunctionRecord stored =
  187. d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
  188. sendJson(res, 201, stored.toSummaryJson());
  189. });
  190. svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
  191. [d](const httplib::Request& req, httplib::Response& res) {
  192. std::string project = req.matches[1], id = req.matches[2];
  193. requireProjectManage(requireKey(*d, req), project);
  194. auto fn = d->functions.get(project, id);
  195. if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  196. sendJson(res, 200, fn->toJson()); // the single-function view carries the source
  197. });
  198. svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
  199. [d](const httplib::Request& req, httplib::Response& res) {
  200. std::string project = req.matches[1], id = req.matches[2];
  201. requireProjectManage(requireKey(*d, req), project);
  202. FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
  203. // The id lives in the source, so the URL cannot rename a function. Say
  204. // which is which: silently trusting either one would either move the
  205. // code to another function's row or move a policy to other code.
  206. if (incoming.functionId != id)
  207. throw ApiError(ErrCode::Unprocessable, "id_mismatch",
  208. "the script's `on` block declares id '" + incoming.functionId +
  209. "' but the URL names '" + id +
  210. "' - the id is part of the source, not of the URL",
  211. {{"declared", incoming.functionId}, {"url", id}});
  212. const bool existed = d->functions.get(project, id).has_value();
  213. // put() preserves the stored policy and enabled flag via
  214. // mergeForCodePush, which is why a push can never widen access.
  215. FunctionRecord stored =
  216. d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
  217. sendJson(res, existed ? 200 : 201, stored.toSummaryJson());
  218. });
  219. svr.Delete(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
  220. [d](const httplib::Request& req, httplib::Response& res) {
  221. std::string project = req.matches[1], id = req.matches[2];
  222. requireProjectManage(requireKey(*d, req), project);
  223. if (!d->functions.remove(project, id))
  224. throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  225. sendJson(res, 200, {{"deleted", id}});
  226. });
  227. // ADMIN ONLY, and the only route that changes a policy. Developers push
  228. // code, admins grant what it may touch - the same split keys already have.
  229. svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/policy)",
  230. [d](const httplib::Request& req, httplib::Response& res) {
  231. std::string project = req.matches[1], id = req.matches[2];
  232. requireAdmin(requireKey(*d, req));
  233. KeyScope policy = parsePolicy(bodyJson(req));
  234. if (!d->functions.setPolicy(project, id, policy))
  235. throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  236. auto fn = d->functions.get(project, id);
  237. if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  238. sendJson(res, 200, fn->toSummaryJson());
  239. });
  240. svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/enabled)",
  241. [d](const httplib::Request& req, httplib::Response& res) {
  242. std::string project = req.matches[1], id = req.matches[2];
  243. requireProjectManage(requireKey(*d, req), project);
  244. auto body = bodyJson(req);
  245. if (!body.contains("enabled") || !body["enabled"].is_boolean())
  246. throw ApiError(ErrCode::Unprocessable, "validation", "enabled must be a boolean");
  247. if (!d->functions.setEnabled(project, id, body["enabled"].get<bool>()))
  248. throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  249. sendJson(res, 200, {{"function_id", id}, {"enabled", body["enabled"].get<bool>()}});
  250. });
  251. svr.Post(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/invoke)",
  252. [d](const httplib::Request& req, httplib::Response& res) {
  253. std::string project = req.matches[1], id = req.matches[2];
  254. requireProjectManage(requireKey(*d, req), project);
  255. auto fn = d->functions.get(project, id);
  256. if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  257. requireRunnable(*fn);
  258. RunnerPool& pool = requireRunner(*d);
  259. const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req);
  260. // A run id is just a random token with no secret meaning; generateApiKey
  261. // is reused rather than adding a second hex generator.
  262. const std::string runId = generateApiKey();
  263. const uint64_t startedAt = static_cast<uint64_t>(std::time(nullptr));
  264. RunnerRunResult r = pool.run(project, id, manualTrigger(*fn, body));
  265. FunctionRunLog entry;
  266. entry.runId = runId;
  267. entry.functionId = id;
  268. entry.trigger = "invoke";
  269. entry.ok = r.ok;
  270. entry.status = r.status;
  271. entry.durationMs = r.durationMs;
  272. entry.error = r.error;
  273. entry.console = r.console;
  274. entry.startedAt = startedAt;
  275. // Logged before the 503 below: an attempt that never reached a runner is
  276. // exactly the one an operator goes looking for afterwards.
  277. d->functionRuns.append(project, entry);
  278. if (r.transportFailure)
  279. throw ApiError(ErrCode::Unavailable, "runner_unreachable",
  280. r.error.empty() ? "the function runner could not be reached" : r.error,
  281. {{"run_id", runId}});
  282. // 200 even when the function itself failed: an invoke REPORTS a run, it
  283. // does not serve it. The function's own status lives in the envelope, and
  284. // flattening it into the HTTP status would make "the function returned
  285. // 500" indistinguishable from "the invoke could not be performed".
  286. sendJson(res, 200, runEnvelope(runId, r));
  287. });
  288. svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/logs)",
  289. [d](const httplib::Request& req, httplib::Response& res) {
  290. std::string project = req.matches[1], id = req.matches[2];
  291. requireProjectManage(requireKey(*d, req), project);
  292. if (!d->functions.get(project, id))
  293. throw ApiError(ErrCode::NotFound, "not_found", "no such function");
  294. nlohmann::json arr = nlohmann::json::array();
  295. for (const auto& e : d->functionRuns.list(project, id, limitParam(req, 50)))
  296. arr.push_back(e.toJson());
  297. sendJson(res, 200, {{"function_id", id}, {"runs", arr}});
  298. });
  299. }
  300. } // namespace svapi