config.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "config.hpp"
  2. #include <fstream>
  3. #include <stdexcept>
  4. namespace svapi {
  5. Config Config::fromJson(const nlohmann::json& j) {
  6. Config c;
  7. c.logLevel = j.value("log_level", c.logLevel);
  8. if (j.contains("http") && j["http"].is_object()) {
  9. const auto& h = j["http"];
  10. c.httpBind = h.value("bind_address", c.httpBind);
  11. c.httpPort = h.value("port", c.httpPort);
  12. c.httpThreadPoolSize = h.value("thread_pool_size", c.httpThreadPoolSize);
  13. }
  14. if (j.contains("database") && j["database"].is_object()) {
  15. c.dbAddress = j["database"].value("address", c.dbAddress);
  16. c.dbTimeoutMs = j["database"].value("timeout_ms", c.dbTimeoutMs);
  17. }
  18. if (j.contains("functions") && j["functions"].is_object()) {
  19. const auto& f = j["functions"];
  20. if (f.contains("runners") && f["runners"].is_array()) {
  21. // Bind before iterating: a range-for over a temporary subobject of a
  22. // parsed document dangles.
  23. const nlohmann::json& runners = f["runners"];
  24. for (const auto& e : runners)
  25. if (e.is_string() && !e.get<std::string>().empty())
  26. c.runnerEndpoints.push_back(e.get<std::string>());
  27. }
  28. c.functionRunsKept = f.value("runs_kept", c.functionRunsKept);
  29. c.runnerToken = f.value("runner_token", c.runnerToken);
  30. if (f.contains("scheduler") && f["scheduler"].is_object()) {
  31. const auto& s = f["scheduler"];
  32. c.schedulerEnabled = s.value("enabled", c.schedulerEnabled);
  33. c.schedulerTickSec = s.value("tick_interval_sec", c.schedulerTickSec);
  34. c.reclaimIntervalSec = s.value("reclaim_interval_sec", c.reclaimIntervalSec);
  35. }
  36. if (f.contains("jobs") && f["jobs"].is_object()) {
  37. const auto& j2 = f["jobs"];
  38. c.claimTimeoutSec = j2.value("claim_timeout_sec", c.claimTimeoutSec);
  39. c.jobMaxAttempts = j2.value("max_attempts", c.jobMaxAttempts);
  40. }
  41. if (f.contains("events") && f["events"].is_object()) {
  42. const auto& e = f["events"];
  43. c.eventsEnabled = e.value("enabled", c.eventsEnabled);
  44. c.eventsMaxDepth = e.value("max_depth", c.eventsMaxDepth);
  45. c.eventsRefreshSec = e.value("refresh_interval_sec", c.eventsRefreshSec);
  46. c.eventsMaxPending = e.value("max_pending", c.eventsMaxPending);
  47. }
  48. }
  49. return c;
  50. }
  51. Config Config::load(const std::string& path) {
  52. std::ifstream f(path);
  53. if (!f) throw std::runtime_error("cannot open config file: " + path);
  54. nlohmann::json j;
  55. f >> j;
  56. return fromJson(j);
  57. }
  58. } // namespace svapi