summaryrefslogtreecommitdiffstats
path: root/server/src/config.cpp
blob: 200b8731653f729fba08a89c63e840f31994768f (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
module;

#include <boost/json.hpp>
#include <boost/system/system_error.hpp>

module routemon:config$impl;

import std;
import :config;
import :log;
import :util;

namespace json = boost::json;

namespace routemon::config {

class location
{
  std::optional<std::pair<std::string_view, util::not_null<location const*>>>
      next_;

  auto append_to(std::string& s) const -> void
  {
    if (next_)
    {
      next_->second->append_to(s);
      s += next_->first;
      s += ".";
    }
  }

public:
  location() = default;

  explicit location(location const& next, std::string_view entry)
    : next_{std::make_pair(entry, util::not_null{&next})}
  {
  }

  [[nodiscard]] auto to_string() const -> std::string
  {
    if (!next_)
      return "";
    auto s = std::string{};
    next_->second->append_to(s);
    s += next_->first;
    return s;
  }

  auto sub(std::string_view entry) const& -> location
  {
    return location{*this, entry};
  }
};

class object_reader
{
  location loc_;
  json::object const& obj_;
  std::unordered_set<std::string> visited_;

public:
  object_reader(json::value const& jv, location loc)
  try : loc_{std::move(loc)}, obj_{jv.as_object()} {}
  catch (boost::system::system_error const&)
  {
    throw std::runtime_error{std::format(
        "expected an object at {}", loc.to_string())};
  }

  auto check_unused() const -> void
  {
    for (auto const& kv : obj_)
    {
      if (!visited_.contains(std::string{kv.key()}))
      {
        throw std::runtime_error{std::format(
            "unexpected key {}", loc_.sub(kv.key()).to_string())};
      }
    }
  }

  template <class T>
  auto allow_at(std::string_view key) -> std::optional<T>
  {
    visited_.emplace(key);
    auto const loc = loc_.sub(key);
    if (auto const jv = obj_.try_at(key); jv && !jv->is_null())
    {
      try
      {
        return json::value_to<T>(*jv, loc);
      }
      catch (boost::system::system_error const& e)
      {
        throw std::runtime_error{std::format(
            "failed to read {}: {}", loc.to_string(), e.code().message())};
      }
    }
    else
    {
      return std::nullopt;
    }
  }

  template <class T>
  auto expect_at(std::string_view key) -> T
  {
    if (auto&& mv = allow_at<T>(key); mv)
    {
      return std::forward<T>(*mv);
    }
    else
    {
      throw std::runtime_error{std::format(
          "did not find expected key {}", loc_.sub(key).to_string())};
    }
  }
};

auto as_checked_object(
    json::value const& jv, location const& loc,
    std::invocable<object_reader&> auto const& f)
    -> decltype(f(std::declval<object_reader&>()))
{
  auto r = object_reader{jv, loc};
  auto&& v = f(r);
  r.check_unused();
  return std::forward<decltype(f(r))>(v);
}

auto tag_invoke(
    json::value_to_tag<rwgps> const&, json::value const& jv,
    location const& loc) -> rwgps
{
  return as_checked_object(
      jv, loc,
      [](object_reader& r) -> rwgps
      {
        return {
          .api_key_filename = r.expect_at<std::string>("api_key_filename"),
          .auth_token_filename =
              r.expect_at<std::string>("auth_token_filename"),
        };
      });
}

auto tag_invoke(
    json::value_to_tag<situations> const&, json::value const& jv,
    location const& loc) -> situations
{
  return as_checked_object(
      jv, loc,
      [](object_reader& r) -> situations
      {
        return {
          .datex2_filename = r.expect_at<std::string>("datex2_filename"),
        };
      });
}

auto tag_invoke(
    json::value_to_tag<database> const&, json::value const& jv,
    location const& loc) -> database
{
  return as_checked_object(
      jv, loc,
      [](object_reader& r) -> database
      {
        return {
          .sqlite3_filename = r.expect_at<std::string>("sqlite3_filename"),
        };
      });
}

auto tag_invoke(
    json::value_to_tag<http_server> const&, json::value const& jv,
    location const& loc) -> http_server
{
  return as_checked_object(
      jv, loc,
      [](object_reader& r) -> http_server
      {
        return {
          .allow_origins =
              r.expect_at<std::vector<std::string>>("allow_origins"),
        };
      });
}

auto tag_invoke(
    json::value_to_tag<logger> const&, json::value const& jv,
    location const& loc) -> logger
{
  return as_checked_object(
      jv, loc,
      [obj_loc = loc](object_reader& r) -> logger
      {
        auto const level_str = r.expect_at<std::string>("level");
        auto level = log::level{};
        if (level_str == "debug")
          level = log::level::debug;
        else if (level_str == "info")
          level = log::level::info;
        else if (level_str == "warn")
          level = log::level::warn;
        else if (level_str == "error")
          level = log::level::error;
        else
          throw std::runtime_error{std::format(
              "unable to parse log level {:?} at {}: expected one "
              "of {{debug, info, warn, error}}",
              level_str, obj_loc.sub("level").to_string())};
        return logger{level};
      });
}

auto json_value_to_app(json::value const& jv) -> app
{
  return as_checked_object(
      jv, location{},
      [](object_reader& r) -> app
      {
        return {
          .rwgps = r.allow_at<rwgps>("rwgps"),
          .situations = r.expect_at<situations>("situations"),
          .database = r.expect_at<database>("database"),
          .http_server = r.expect_at<http_server>("http_server"),
          .logger = r.expect_at<logger>("logger"),
        };
      });
}

auto load_file(std::string const& filename) -> app
{
  // TODO: migrate away from json::value_to w/ tag_invoke.
  // Boost.JSON does not properly propagate custom exceptions accross
  // json::value_to calls when certain containers are involved
  // (std::{optional,variant,vector}).

  auto f = std::ifstream{filename, std::ios::binary};
  if (!f.is_open())
    throw std::runtime_error{std::format("failed to open {}", filename)};
  auto jv = json::value{};
  try
  {
    jv = json::parse(f);
  }
  catch (boost::system::system_error const& e)
  {
    throw std::runtime_error{std::format(
        "failed to parse: {}", e.code().message())};
  }
  return json_value_to_app(jv);
}

} // namespace routemon::config