diff options
36 files changed, 1945 insertions, 567 deletions
diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index fad973f..b8fd37a 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt | |||
| @@ -7,6 +7,7 @@ add_compile_options( | |||
| 7 | -O2 | 7 | -O2 |
| 8 | -fno-omit-frame-pointer | 8 | -fno-omit-frame-pointer |
| 9 | -Wall -Wextra -Wformat -Wformat=2 -Wconversion -Wimplicit-fallthrough | 9 | -Wall -Wextra -Wformat -Wformat=2 -Wconversion -Wimplicit-fallthrough |
| 10 | -Wconsumed | ||
| 10 | -Werror=format-security | 11 | -Werror=format-security |
| 11 | -U_FORTIFY_SOURCE # -D_FORTIFY_SOURCE=3 (unfortunately breaks the std module, see https://github.com/llvm/llvm-project/issues/121709) | 12 | -U_FORTIFY_SOURCE # -D_FORTIFY_SOURCE=3 (unfortunately breaks the std module, see https://github.com/llvm/llvm-project/issues/121709) |
| 12 | -D_GLIBCXX_ASSERTIONS | 13 | -D_GLIBCXX_ASSERTIONS |
| @@ -46,11 +47,13 @@ target_sources(routemon_lib | |||
| 46 | src/locale.cpp | 47 | src/locale.cpp |
| 47 | src/log.cppm | 48 | src/log.cppm |
| 48 | src/log.cpp | 49 | src/log.cpp |
| 50 | src/migrate.cppm | ||
| 49 | src/problem.cppm | 51 | src/problem.cppm |
| 50 | src/problem.cpp | 52 | src/problem.cpp |
| 51 | src/routemon.cppm | 53 | src/routemon.cppm |
| 52 | src/rwgps.cppm | 54 | src/rwgps.cppm |
| 53 | src/rwgps.cpp | 55 | src/rwgps.cpp |
| 56 | src/rwgps_webhook.cppm | ||
| 54 | src/sqlite3.cppm | 57 | src/sqlite3.cppm |
| 55 | src/sqlite3.cpp | 58 | src/sqlite3.cpp |
| 56 | src/srv.cppm | 59 | src/srv.cppm |
diff --git a/server/migrations/1_init_up.sql b/server/migrations/1_init_up.sql index 7edb398..8400f8d 100644 --- a/server/migrations/1_init_up.sql +++ b/server/migrations/1_init_up.sql | |||
| @@ -1,7 +1,8 @@ | |||
| 1 | BEGIN; | 1 | CREATE TABLE migration ( |
| 2 | at_most_one_row INTEGER UNIQUE DEFAULT 1, | ||
| 3 | version INTEGER NOT NULL, | ||
| 4 | -- This table should have at most one row. | ||
| 5 | CHECK (at_most_one_row = 1) | ||
| 6 | ) STRICT; | ||
| 2 | 7 | ||
| 3 | CREATE TABLE migration (version); | 8 | INSERT INTO migration (version) VALUES (0); |
| 4 | |||
| 5 | INSERT INTO migration VALUES (1); | ||
| 6 | |||
| 7 | COMMIT; | ||
diff --git a/server/migrations/2_kaas_up.sql b/server/migrations/2_kaas_up.sql deleted file mode 100644 index 0c7837a..0000000 --- a/server/migrations/2_kaas_up.sql +++ /dev/null | |||
| @@ -1,23 +0,0 @@ | |||
| 1 | BEGIN; | ||
| 2 | |||
| 3 | -- TODO enable strict mode so that primary key is automatically enforced to not be NULL | ||
| 4 | CREATE TABLE received_route ( | ||
| 5 | id INTEGER PRIMARY KEY, | ||
| 6 | |||
| 7 | received_route_source route_source NOT NULL, | ||
| 8 | recieved_route_strava_id TEXT, | ||
| 9 | |||
| 10 | -- ON DELETE what? | ||
| 11 | FOREIGN KEY (received_route_source_id) REFERENCES received_route_source (id), | ||
| 12 | CHECK (received_route_source IN ('gpx_upload', 'strava', 'rwgps')), | ||
| 13 | CHECK ((received_route_source = 'strava') = (received_route_strava_id IS NULL)) | ||
| 14 | ); | ||
| 15 | |||
| 16 | CREATE TABLE received_route_linestring ( | ||
| 17 | received_route_id INT NOT NULL, | ||
| 18 | linestring BLOB NOT NULL, | ||
| 19 | |||
| 20 | FOREIGN KEY (received_route_id) REFERENCES received_route (id) | ||
| 21 | ); | ||
| 22 | |||
| 23 | COMMIT; | ||
diff --git a/server/migrations/2_rwgps_up.sql b/server/migrations/2_rwgps_up.sql new file mode 100644 index 0000000..569479b --- /dev/null +++ b/server/migrations/2_rwgps_up.sql | |||
| @@ -0,0 +1,22 @@ | |||
| 1 | CREATE TABLE rwgps_notification ( | ||
| 2 | id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 3 | rwgps_timestamp TEXT NOT NULL, | ||
| 4 | user_id INTEGER NOT NULL, | ||
| 5 | item_type TEXT, -- NULL if unknown | ||
| 6 | item_id INTEGER, | ||
| 7 | item_user_id INTEGER, | ||
| 8 | item_url TEXT, | ||
| 9 | action_ TEXT, -- NULL if unknown | ||
| 10 | CHECK (rwgps_timestamp IS strftime('%FT%TZ', rwgps_timestamp)), | ||
| 11 | CHECK (item_type IN ('trip', 'route', 'event', 'event_participant', 'club_member', 'authorization')), | ||
| 12 | CHECK (action_ IN ('created', 'updated', 'deleted', 'added', 'removed')) | ||
| 13 | ) STRICT; | ||
| 14 | |||
| 15 | CREATE TABLE rwgps_notification_target_collection ( | ||
| 16 | notification_id INTEGER PRIMARY KEY, | ||
| 17 | id INTEGER NOT NULL, | ||
| 18 | type_ TEXT, -- NULL if unknown | ||
| 19 | url TEXT, | ||
| 20 | CHECK (type_ IN ('pinned')), | ||
| 21 | FOREIGN KEY (notification_id) REFERENCES rwgps_notification (id) | ||
| 22 | ) STRICT; | ||
diff --git a/server/src/api.cpp b/server/src/api.cpp index 9a51690..8a986d4 100644 --- a/server/src/api.cpp +++ b/server/src/api.cpp | |||
| @@ -99,8 +99,10 @@ auto tag_invoke(json::value_from_tag, json::value& jv, sysinfo const& info) | |||
| 99 | }; | 99 | }; |
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | handler::handler(log::logger const& l, datex2::situation_publication pub) | 102 | handler::handler( |
| 103 | : l_{l.sub("handler")}, pub_{std::move(pub)} | 103 | log::logger const& l, std::shared_ptr<database::connection> dbc, |
| 104 | datex2::situation_publication pub) | ||
| 105 | : l_{l.sub("handler")}, dbc_{std::move(dbc)}, pub_{std::move(pub)} | ||
| 104 | { | 106 | { |
| 105 | auto const nsit = pub_.situations.size(); | 107 | auto const nsit = pub_.situations.size(); |
| 106 | auto progress_percent = | 108 | auto progress_percent = |
| @@ -145,7 +147,8 @@ handler::handler(log::logger const& l, datex2::situation_publication pub) | |||
| 145 | } | 147 | } |
| 146 | 148 | ||
| 147 | auto handler::process_gpx( | 149 | auto handler::process_gpx( |
| 148 | trace::id trace_id, gpx::file&& gpx_file, time::period_seq check_periods) | 150 | trace::id trace_id, gpx::file&& gpx_file, |
| 151 | time::period_seq<std::chrono::minutes> const& check_periods) | ||
| 149 | -> std::optional<process_gpx_result> | 152 | -> std::optional<process_gpx_result> |
| 150 | { | 153 | { |
| 151 | auto l = l_.with("trace_id", trace_id.as_string()); | 154 | auto l = l_.with("trace_id", trace_id.as_string()); |
| @@ -282,4 +285,99 @@ auto handler::sysinfo() -> struct sysinfo | |||
| 282 | }; | 285 | }; |
| 283 | } | 286 | } |
| 284 | 287 | ||
| 288 | auto rwgps_notification_cause_to_db(rwgps::notification_cause c) -> database::schema::rwgps_notification_cause | ||
| 289 | { | ||
| 290 | switch (c) | ||
| 291 | { | ||
| 292 | case rwgps::notification_cause::unknown: | ||
| 293 | return database::schema::rwgps_notification_cause::unknown; | ||
| 294 | case rwgps::notification_cause::created: | ||
| 295 | return database::schema::rwgps_notification_cause::created; | ||
| 296 | case rwgps::notification_cause::updated: | ||
| 297 | return database::schema::rwgps_notification_cause::updated; | ||
| 298 | case rwgps::notification_cause::deleted: | ||
| 299 | return database::schema::rwgps_notification_cause::deleted; | ||
| 300 | case rwgps::notification_cause::added: | ||
| 301 | return database::schema::rwgps_notification_cause::added; | ||
| 302 | case rwgps::notification_cause::removed: | ||
| 303 | return database::schema::rwgps_notification_cause::removed; | ||
| 304 | } | ||
| 305 | } | ||
| 306 | |||
| 307 | auto rwgps_notification_item_type_to_db(rwgps::notification_item_type t) | ||
| 308 | -> database::schema::rwgps_notification_item_type | ||
| 309 | { | ||
| 310 | switch (t) | ||
| 311 | { | ||
| 312 | case rwgps::notification_item_type::unknown: | ||
| 313 | return database::schema::rwgps_notification_item_type::unknown; | ||
| 314 | case rwgps::notification_item_type::trip: | ||
| 315 | return database::schema::rwgps_notification_item_type::trip; | ||
| 316 | case rwgps::notification_item_type::route: | ||
| 317 | return database::schema::rwgps_notification_item_type::route; | ||
| 318 | case rwgps::notification_item_type::event: | ||
| 319 | return database::schema::rwgps_notification_item_type::event; | ||
| 320 | case rwgps::notification_item_type::event_participant: | ||
| 321 | return database::schema::rwgps_notification_item_type::event_participant; | ||
| 322 | case rwgps::notification_item_type::club_member: | ||
| 323 | return database::schema::rwgps_notification_item_type::club_member; | ||
| 324 | case rwgps::notification_item_type::authorization: | ||
| 325 | return database::schema::rwgps_notification_item_type::authorization; | ||
| 326 | } | ||
| 327 | } | ||
| 328 | |||
| 329 | auto rwgps_notification_target_collection_type_to_db( | ||
| 330 | rwgps::notification_target_collection_type t) | ||
| 331 | -> database::schema::rwgps_notification_target_collection_type | ||
| 332 | { | ||
| 333 | switch (t) | ||
| 334 | { | ||
| 335 | case rwgps::notification_target_collection_type::unknown: | ||
| 336 | return database::schema::rwgps_notification_target_collection_type::unknown; | ||
| 337 | case rwgps::notification_target_collection_type::pinned: | ||
| 338 | return database::schema::rwgps_notification_target_collection_type::pinned; | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 342 | auto handler::rwgps_webhook( | ||
| 343 | time::timestamp<std::chrono::seconds> rwgps_ts, rwgps::webhook_request req) | ||
| 344 | -> void | ||
| 345 | { | ||
| 346 | l_.info("Handling (valid) RWGPS webhook request"); | ||
| 347 | |||
| 348 | auto notifs = std::vector<std::pair< | ||
| 349 | database::schema::rwgps_notification, | ||
| 350 | std::optional<database::schema::rwgps_notification_target_collection> | ||
| 351 | >>{}; | ||
| 352 | |||
| 353 | for (auto const& notif : req.notifications) | ||
| 354 | { | ||
| 355 | auto db_notif = database::schema::rwgps_notification{ | ||
| 356 | .rwgps_timestamp = rwgps_ts, | ||
| 357 | .user_id = notif.user_id, | ||
| 358 | .item_type = rwgps_notification_item_type_to_db(notif.item_type), | ||
| 359 | .item_id = notif.item_id, | ||
| 360 | .item_user_id = notif.item_user_id, | ||
| 361 | .item_url = notif.item_url, | ||
| 362 | .action = rwgps_notification_cause_to_db(notif.action), | ||
| 363 | }; | ||
| 364 | |||
| 365 | auto mdb_collection = notif.collection.transform( | ||
| 366 | [](auto const& collection) | ||
| 367 | -> database::schema::rwgps_notification_target_collection | ||
| 368 | { | ||
| 369 | return { | ||
| 370 | .id = collection.id, | ||
| 371 | .type = rwgps_notification_target_collection_type_to_db( | ||
| 372 | collection.type), | ||
| 373 | .url = collection.url, | ||
| 374 | }; | ||
| 375 | }); | ||
| 376 | |||
| 377 | notifs.emplace_back(db_notif, mdb_collection); | ||
| 378 | } | ||
| 379 | |||
| 380 | dbc_->insert_rwgps_notifications(notifs); | ||
| 381 | } | ||
| 382 | |||
| 285 | } // namespace routemon::api | 383 | } // namespace routemon::api |
diff --git a/server/src/api.cppm b/server/src/api.cppm index b14bbcf..7e71413 100644 --- a/server/src/api.cppm +++ b/server/src/api.cppm | |||
| @@ -6,74 +6,71 @@ module; | |||
| 6 | export module routemon:api; | 6 | export module routemon:api; |
| 7 | 7 | ||
| 8 | import std; | 8 | import std; |
| 9 | import :database; | ||
| 9 | import :datex2; | 10 | import :datex2; |
| 10 | import :geo.wgs84; | 11 | import :geo.wgs84; |
| 11 | import :geo.utm.multizonal; | 12 | import :geo.utm.multizonal; |
| 12 | import :gpx; | 13 | import :gpx; |
| 13 | import :log; | 14 | import :log; |
| 14 | import :time; | 15 | import :time; |
| 16 | import :rwgps; | ||
| 15 | import :trace; | 17 | import :trace; |
| 16 | 18 | ||
| 17 | namespace { | ||
| 18 | |||
| 19 | namespace chrono = std::chrono; | ||
| 20 | namespace json = boost::json; | ||
| 21 | namespace views = std::views; | ||
| 22 | |||
| 23 | } // namespace | ||
| 24 | |||
| 25 | export namespace routemon::api { | 19 | export namespace routemon::api { |
| 26 | 20 | ||
| 27 | struct relevant_road_closure | 21 | struct relevant_road_closure |
| 28 | { | 22 | { |
| 29 | std::vector<geo::utm::zonable_wgs84_linestring> relevant_lss; | 23 | std::vector<geo::utm::zonable_wgs84_linestring> relevant_lss = {}; |
| 30 | }; | 24 | }; |
| 31 | 25 | ||
| 32 | struct relevant_situation | 26 | struct relevant_situation |
| 33 | { | 27 | { |
| 34 | std::string id; | 28 | std::string id = {}; |
| 35 | std::optional<geo::utm::zonable_wgs84_point> location; | 29 | std::optional<geo::utm::zonable_wgs84_point> location = {}; |
| 36 | std::vector<std::string> comments; | 30 | std::vector<std::string> comments = {}; |
| 37 | std::vector<relevant_road_closure> relevant_road_closures; | 31 | std::vector<relevant_road_closure> relevant_road_closures = {}; |
| 38 | }; | 32 | }; |
| 39 | 33 | ||
| 40 | struct track_segment | 34 | struct track_segment |
| 41 | { | 35 | { |
| 42 | geo::utm::zonable_wgs84_linestring points; | 36 | geo::utm::zonable_wgs84_linestring points = {}; |
| 43 | }; | 37 | }; |
| 44 | 38 | ||
| 45 | struct track | 39 | struct track |
| 46 | { | 40 | { |
| 47 | std::vector<track_segment> segments; | 41 | std::vector<track_segment> segments = {}; |
| 48 | }; | 42 | }; |
| 49 | 43 | ||
| 50 | struct process_gpx_result | 44 | struct process_gpx_result |
| 51 | { | 45 | { |
| 52 | std::vector<track> tracks; | 46 | std::vector<track> tracks = {}; |
| 53 | std::vector<relevant_situation> relevant_situations; | 47 | std::vector<relevant_situation> relevant_situations = {}; |
| 54 | }; | 48 | }; |
| 55 | 49 | ||
| 56 | struct sysinfo | 50 | struct sysinfo |
| 57 | { | 51 | { |
| 58 | time::timestamp using_publication_of; | 52 | time::timestamp<> using_publication_of = {}; |
| 59 | std::size_t blse_index_size; | 53 | std::size_t blse_index_size = 0uz; |
| 60 | std::size_t bpe_index_size; | 54 | std::size_t bpe_index_size = 0uz; |
| 61 | }; | 55 | }; |
| 62 | 56 | ||
| 63 | auto tag_invoke( | 57 | auto tag_invoke( |
| 64 | json::value_from_tag, json::value& jv, relevant_road_closure const& clo) | 58 | boost::json::value_from_tag, boost::json::value& jv, |
| 65 | -> void; | 59 | relevant_road_closure const& clo) -> void; |
| 66 | auto tag_invoke( | 60 | auto tag_invoke( |
| 67 | json::value_from_tag, json::value& jv, relevant_situation const& sit) | 61 | boost::json::value_from_tag, boost::json::value& jv, |
| 68 | -> void; | 62 | relevant_situation const& sit) -> void; |
| 69 | auto tag_invoke(json::value_from_tag, json::value& jv, track_segment const& seg) | 63 | auto tag_invoke( |
| 70 | -> void; | 64 | boost::json::value_from_tag, boost::json::value& jv, |
| 71 | auto tag_invoke(json::value_from_tag, json::value& jv, track const& track) | 65 | track_segment const& seg) -> void; |
| 72 | -> void; | ||
| 73 | auto tag_invoke( | 66 | auto tag_invoke( |
| 74 | json::value_from_tag, json::value& jv, process_gpx_result const& res) | 67 | boost::json::value_from_tag, boost::json::value& jv, track const& track) |
| 75 | -> void; | 68 | -> void; |
| 76 | auto tag_invoke(json::value_from_tag, json::value& jv, sysinfo const& info) | 69 | auto tag_invoke( |
| 70 | boost::json::value_from_tag, boost::json::value& jv, | ||
| 71 | process_gpx_result const& res) -> void; | ||
| 72 | auto tag_invoke( | ||
| 73 | boost::json::value_from_tag, boost::json::value& jv, sysinfo const& info) | ||
| 77 | -> void; | 74 | -> void; |
| 78 | 75 | ||
| 79 | class handler | 76 | class handler |
| @@ -86,17 +83,24 @@ class handler | |||
| 86 | using bpe_index = geo::utm::multizonal::point_rtree<bpe_index_value>; | 83 | using bpe_index = geo::utm::multizonal::point_rtree<bpe_index_value>; |
| 87 | 84 | ||
| 88 | log::logger l_; | 85 | log::logger l_; |
| 86 | std::shared_ptr<database::connection> dbc_; | ||
| 89 | datex2::situation_publication pub_; | 87 | datex2::situation_publication pub_; |
| 90 | blse_index blse_index_; | 88 | blse_index blse_index_; |
| 91 | bpe_index bpe_index_; | 89 | bpe_index bpe_index_; |
| 92 | 90 | ||
| 93 | public: | 91 | public: |
| 94 | explicit handler(log::logger const& l, datex2::situation_publication pub); | 92 | explicit handler( |
| 93 | log::logger const& l, std::shared_ptr<database::connection> dbc, | ||
| 94 | datex2::situation_publication pub); | ||
| 95 | 95 | ||
| 96 | auto process_gpx( | 96 | auto process_gpx( |
| 97 | trace::id trace_id, gpx::file&& gpx_file, time::period_seq check_periods) | 97 | trace::id trace_id, gpx::file&& gpx_file, |
| 98 | time::period_seq<std::chrono::minutes> const& check_periods) | ||
| 98 | -> std::optional<process_gpx_result>; | 99 | -> std::optional<process_gpx_result>; |
| 99 | auto sysinfo() -> sysinfo; | 100 | auto sysinfo() -> sysinfo; |
| 101 | auto rwgps_webhook( | ||
| 102 | time::timestamp<std::chrono::seconds> rwgps_ts, | ||
| 103 | rwgps::webhook_request req) -> void; | ||
| 100 | }; | 104 | }; |
| 101 | 105 | ||
| 102 | } // namespace routemon::api | 106 | } // namespace routemon::api |
diff --git a/server/src/config.cpp b/server/src/config.cpp index 200b873..9231232 100644 --- a/server/src/config.cpp +++ b/server/src/config.cpp | |||
| @@ -139,6 +139,8 @@ auto tag_invoke( | |||
| 139 | { | 139 | { |
| 140 | return { | 140 | return { |
| 141 | .api_key_filename = r.expect_at<std::string>("api_key_filename"), | 141 | .api_key_filename = r.expect_at<std::string>("api_key_filename"), |
| 142 | .api_secret_filename = | ||
| 143 | r.expect_at<std::string>("api_secret_filename"), | ||
| 142 | .auth_token_filename = | 144 | .auth_token_filename = |
| 143 | r.expect_at<std::string>("auth_token_filename"), | 145 | r.expect_at<std::string>("auth_token_filename"), |
| 144 | }; | 146 | }; |
| @@ -222,7 +224,7 @@ auto json_value_to_app(json::value const& jv) -> app | |||
| 222 | [](object_reader& r) -> app | 224 | [](object_reader& r) -> app |
| 223 | { | 225 | { |
| 224 | return { | 226 | return { |
| 225 | .rwgps = r.allow_at<rwgps>("rwgps"), | 227 | .rwgps = r.expect_at<rwgps>("rwgps"), |
| 226 | .situations = r.expect_at<situations>("situations"), | 228 | .situations = r.expect_at<situations>("situations"), |
| 227 | .database = r.expect_at<database>("database"), | 229 | .database = r.expect_at<database>("database"), |
| 228 | .http_server = r.expect_at<http_server>("http_server"), | 230 | .http_server = r.expect_at<http_server>("http_server"), |
diff --git a/server/src/config.cppm b/server/src/config.cppm index ab9b137..01e1055 100644 --- a/server/src/config.cppm +++ b/server/src/config.cppm | |||
| @@ -7,37 +7,38 @@ namespace routemon::config { | |||
| 7 | 7 | ||
| 8 | export struct rwgps | 8 | export struct rwgps |
| 9 | { | 9 | { |
| 10 | std::string api_key_filename; | 10 | std::string api_key_filename = {}; |
| 11 | std::string auth_token_filename; | 11 | std::string api_secret_filename = {}; |
| 12 | std::string auth_token_filename = {}; | ||
| 12 | }; | 13 | }; |
| 13 | 14 | ||
| 14 | export struct situations | 15 | export struct situations |
| 15 | { | 16 | { |
| 16 | std::string datex2_filename; | 17 | std::string datex2_filename = {}; |
| 17 | }; | 18 | }; |
| 18 | 19 | ||
| 19 | export struct database | 20 | export struct database |
| 20 | { | 21 | { |
| 21 | std::string sqlite3_filename; | 22 | std::string sqlite3_filename = {}; |
| 22 | }; | 23 | }; |
| 23 | 24 | ||
| 24 | export struct http_server | 25 | export struct http_server |
| 25 | { | 26 | { |
| 26 | std::vector<std::string> allow_origins; | 27 | std::vector<std::string> allow_origins = {}; |
| 27 | }; | 28 | }; |
| 28 | 29 | ||
| 29 | export struct logger | 30 | export struct logger |
| 30 | { | 31 | { |
| 31 | log::level level; | 32 | log::level level = log::level::debug; |
| 32 | }; | 33 | }; |
| 33 | 34 | ||
| 34 | export struct app | 35 | export struct app |
| 35 | { | 36 | { |
| 36 | std::optional<rwgps> rwgps; | 37 | rwgps rwgps = {}; |
| 37 | situations situations; | 38 | situations situations = {}; |
| 38 | database database; | 39 | database database = {}; |
| 39 | http_server http_server; | 40 | http_server http_server = {}; |
| 40 | logger logger; | 41 | logger logger = {}; |
| 41 | }; | 42 | }; |
| 42 | 43 | ||
| 43 | export auto load_file(std::string const& filename) -> app; | 44 | export auto load_file(std::string const& filename) -> app; |
diff --git a/server/src/database.cpp b/server/src/database.cpp index 54e5f34..c1f9ab2 100644 --- a/server/src/database.cpp +++ b/server/src/database.cpp | |||
| @@ -4,23 +4,125 @@ import :database; | |||
| 4 | 4 | ||
| 5 | namespace routemon::database { | 5 | namespace routemon::database { |
| 6 | 6 | ||
| 7 | constexpr std::int64_t expected_database_version = 1; | 7 | namespace schema { |
| 8 | 8 | ||
| 9 | auto open(std::string const& filename) -> std::shared_ptr<connection> | 9 | constexpr std::int64_t expected_version = 2; |
| 10 | |||
| 11 | auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string> | ||
| 12 | { | ||
| 13 | switch (c) | ||
| 14 | { | ||
| 15 | case rwgps_notification_cause::unknown: | ||
| 16 | return std::nullopt; | ||
| 17 | case rwgps_notification_cause::created: | ||
| 18 | return "created"; | ||
| 19 | case rwgps_notification_cause::updated: | ||
| 20 | return "updated"; | ||
| 21 | case rwgps_notification_cause::deleted: | ||
| 22 | return "deleted"; | ||
| 23 | case rwgps_notification_cause::added: | ||
| 24 | return "added"; | ||
| 25 | case rwgps_notification_cause::removed: | ||
| 26 | return "removed"; | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | auto try_to_string(rwgps_notification_item_type t) -> std::optional<std::string> | ||
| 31 | { | ||
| 32 | switch (t) | ||
| 33 | { | ||
| 34 | case rwgps_notification_item_type::unknown: | ||
| 35 | return std::nullopt; | ||
| 36 | case rwgps_notification_item_type::trip: | ||
| 37 | return "trip"; | ||
| 38 | case rwgps_notification_item_type::route: | ||
| 39 | return "route"; | ||
| 40 | case rwgps_notification_item_type::event: | ||
| 41 | return "event"; | ||
| 42 | case rwgps_notification_item_type::event_participant: | ||
| 43 | return "event_participant"; | ||
| 44 | case rwgps_notification_item_type::club_member: | ||
| 45 | return "club_member"; | ||
| 46 | case rwgps_notification_item_type::authorization: | ||
| 47 | return "authorization"; | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | auto try_to_string(rwgps_notification_target_collection_type t) | ||
| 52 | -> std::optional<std::string> | ||
| 53 | { | ||
| 54 | switch (t) | ||
| 55 | { | ||
| 56 | case rwgps_notification_target_collection_type::unknown: | ||
| 57 | return std::nullopt; | ||
| 58 | case rwgps_notification_target_collection_type::pinned: | ||
| 59 | return "pinned"; | ||
| 60 | } | ||
| 61 | }; | ||
| 62 | |||
| 63 | } // namespace schema | ||
| 64 | |||
| 65 | auto connection::insert_rwgps_notifications( | ||
| 66 | std::vector<std::pair< | ||
| 67 | schema::rwgps_notification, | ||
| 68 | std::optional<schema::rwgps_notification_target_collection> | ||
| 69 | >>& notifs) -> void | ||
| 70 | { | ||
| 71 | auto tx = sqlite3::tx{dbc_}; | ||
| 72 | for (auto& [notif, mtarget_collection] : notifs) | ||
| 73 | { | ||
| 74 | tx.query( | ||
| 75 | "INSERT INTO rwgps_notification " | ||
| 76 | " (rwgps_timestamp, user_id, item_type, item_id, " | ||
| 77 | " item_user_id, item_url, action_) " | ||
| 78 | "VALUES (:rwgps_timestamp, :user_id, :item_type, :item_id, " | ||
| 79 | " :item_user_id, :item_url, :action) " | ||
| 80 | "RETURNING id", | ||
| 81 | [¬if](auto& s) | ||
| 82 | { | ||
| 83 | auto const ts = time::iso8601_secs(notif.rwgps_timestamp); | ||
| 84 | s.bind(":rwgps_timestamp", std::string_view{ts}); | ||
| 85 | s.bind(":user_id", notif.user_id); | ||
| 86 | s.bind(":item_type", try_to_string(notif.item_type)); | ||
| 87 | s.bind(":item_id", notif.item_id); | ||
| 88 | s.bind(":item_user_id", notif.item_user_id); | ||
| 89 | s.bind(":item_url", notif.item_url); | ||
| 90 | s.bind(":action", try_to_string(notif.action)); | ||
| 91 | }) | ||
| 92 | .scan_row_max1(notif.id); | ||
| 93 | |||
| 94 | if (mtarget_collection) | ||
| 95 | { | ||
| 96 | tx.exec( | ||
| 97 | "INSERT INTO rwgps_notification_target_collection " | ||
| 98 | " (notification_id, id, type_, url) " | ||
| 99 | "VALUES (:notification_id, :id, :type, :url)", | ||
| 100 | [¬if, &mtarget_collection](auto& s) | ||
| 101 | { | ||
| 102 | s.bind(":notification_id", notif.id); | ||
| 103 | s.bind(":id", mtarget_collection->id); | ||
| 104 | s.bind(":type", try_to_string(mtarget_collection->type)); | ||
| 105 | s.bind(":url", mtarget_collection->url); | ||
| 106 | }); | ||
| 107 | } | ||
| 108 | } | ||
| 109 | } | ||
| 110 | |||
| 111 | auto open(util::zstring_view filename) -> std::shared_ptr<connection> | ||
| 10 | { | 112 | { |
| 11 | auto dbc = sqlite3::open(filename); | 113 | auto dbc = sqlite3::open(filename); |
| 12 | try | 114 | try |
| 13 | { | 115 | { |
| 14 | auto version = std::optional<std::int64_t>{}; | 116 | auto mversion = std::optional<std::int64_t>{}; |
| 15 | dbc.query("SELECT version FROM migration;").scan_single(version); | 117 | dbc.query("SELECT version FROM migration;").scan_row_max1(mversion); |
| 16 | if (!version) | 118 | if (!mversion) |
| 17 | throw std::runtime_error{"failed to fetch database migration version"}; | 119 | throw std::runtime_error{"failed to fetch database migration version"}; |
| 18 | if (version != expected_database_version) | 120 | if (mversion != schema::expected_version) |
| 19 | { | 121 | { |
| 20 | throw std::runtime_error{std::format( | 122 | throw std::runtime_error{std::format( |
| 21 | "database migration version ({}) does not match expected " | 123 | "database migration version ({}) does not match expected " |
| 22 | "version ({}), consider running migrations", | 124 | "version ({}), consider running migrations", |
| 23 | *version, expected_database_version)}; | 125 | *mversion, schema::expected_version)}; |
| 24 | } | 126 | } |
| 25 | } | 127 | } |
| 26 | catch (std::exception const& e) | 128 | catch (std::exception const& e) |
diff --git a/server/src/database.cppm b/server/src/database.cppm index ff5cae4..83616d2 100644 --- a/server/src/database.cppm +++ b/server/src/database.cppm | |||
| @@ -2,21 +2,79 @@ export module routemon:database; | |||
| 2 | 2 | ||
| 3 | import std; | 3 | import std; |
| 4 | import :sqlite3; | 4 | import :sqlite3; |
| 5 | import :time; | ||
| 5 | 6 | ||
| 6 | namespace routemon::database { | 7 | namespace routemon::database { |
| 7 | 8 | ||
| 9 | namespace schema { | ||
| 10 | |||
| 11 | enum class rwgps_notification_cause | ||
| 12 | { | ||
| 13 | unknown, | ||
| 14 | created, | ||
| 15 | updated, | ||
| 16 | deleted, | ||
| 17 | added, | ||
| 18 | removed, | ||
| 19 | }; | ||
| 20 | |||
| 21 | enum class rwgps_notification_item_type | ||
| 22 | { | ||
| 23 | unknown, | ||
| 24 | trip, | ||
| 25 | route, | ||
| 26 | event, | ||
| 27 | event_participant, | ||
| 28 | club_member, | ||
| 29 | authorization, | ||
| 30 | }; | ||
| 31 | |||
| 32 | enum rwgps_notification_target_collection_type | ||
| 33 | { | ||
| 34 | unknown, | ||
| 35 | pinned, | ||
| 36 | }; | ||
| 37 | |||
| 38 | struct rwgps_notification_target_collection | ||
| 39 | { | ||
| 40 | std::int64_t notification_id = 0; | ||
| 41 | std::int64_t id; | ||
| 42 | rwgps_notification_target_collection_type type; | ||
| 43 | std::optional<std::string> url; | ||
| 44 | }; | ||
| 45 | |||
| 46 | struct rwgps_notification | ||
| 47 | { | ||
| 48 | std::int64_t id = 0; | ||
| 49 | time::timestamp<std::chrono::seconds> rwgps_timestamp; | ||
| 50 | // User that took the action | ||
| 51 | std::int64_t user_id; | ||
| 52 | rwgps_notification_item_type item_type; | ||
| 53 | std::optional<std::int64_t> item_id; | ||
| 54 | // User that owns the item | ||
| 55 | std::optional<std::int64_t> item_user_id; | ||
| 56 | std::optional<std::string> item_url; | ||
| 57 | rwgps_notification_cause action; | ||
| 58 | }; | ||
| 59 | |||
| 60 | } // namespace schema | ||
| 61 | |||
| 8 | export class connection | 62 | export class connection |
| 9 | { | 63 | { |
| 10 | sqlite3::connection dbc_; | 64 | sqlite3::connection dbc_; |
| 11 | 65 | ||
| 12 | explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} | 66 | explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} |
| 13 | 67 | ||
| 14 | friend auto open(std::string const& filename) -> std::shared_ptr<connection>; | 68 | friend auto open(util::zstring_view filename) -> std::shared_ptr<connection>; |
| 15 | 69 | ||
| 16 | public: | 70 | public: |
| 17 | // Nothing here yet | 71 | auto insert_rwgps_notifications( |
| 72 | std::vector<std::pair< | ||
| 73 | schema::rwgps_notification, | ||
| 74 | std::optional<schema::rwgps_notification_target_collection> | ||
| 75 | >>& notifs) -> void; | ||
| 18 | }; | 76 | }; |
| 19 | 77 | ||
| 20 | export auto open(std::string const& filename) -> std::shared_ptr<connection>; | 78 | export auto open(util::zstring_view filename) -> std::shared_ptr<connection>; |
| 21 | 79 | ||
| 22 | } // namespace routemon::database | 80 | } // namespace routemon::database |
diff --git a/server/src/datex2.cpp b/server/src/datex2.cpp index 70c5f94..ab49fd9 100644 --- a/server/src/datex2.cpp +++ b/server/src/datex2.cpp | |||
| @@ -14,11 +14,11 @@ using namespace std::literals::string_view_literals; | |||
| 14 | 14 | ||
| 15 | namespace routemon::datex2 { | 15 | namespace routemon::datex2 { |
| 16 | 16 | ||
| 17 | auto parse_timestamp(char const* in) -> std::optional<time::timestamp> | 17 | auto parse_timestamp_secs(char const* in) -> std::optional<time::timestamp<>> |
| 18 | { | 18 | { |
| 19 | auto res = time::timestamp{}; | 19 | auto res = time::timestamp<>{}; |
| 20 | auto is = std::istringstream{in}; | 20 | auto is = std::istringstream{in}; |
| 21 | is >> std::chrono::parse("%Y-%m-%dT%H:%M:%SZ", res); | 21 | is >> std::chrono::parse("%FT%TZ", res); |
| 22 | return is.fail() ? std::nullopt : std::make_optional(res); | 22 | return is.fail() ? std::nullopt : std::make_optional(res); |
| 23 | } | 23 | } |
| 24 | 24 | ||
| @@ -178,7 +178,7 @@ auto loader::handle_road_or_carriageway_or_lane_management( | |||
| 178 | 178 | ||
| 179 | //---- Check if within the defined validity period | 179 | //---- Check if within the defined validity period |
| 180 | 180 | ||
| 181 | auto validity = std::optional<time::period_seq>{}; | 181 | auto validity = std::optional<time::period_seq<std::chrono::minutes>>{}; |
| 182 | auto const& validity_xml = record_xml.child("sit:validity"); | 182 | auto const& validity_xml = record_xml.child("sit:validity"); |
| 183 | if (validity_xml | 183 | if (validity_xml |
| 184 | && validity_xml.child_value("com:validityStatus") | 184 | && validity_xml.child_value("com:validityStatus") |
| @@ -187,52 +187,67 @@ auto loader::handle_road_or_carriageway_or_lane_management( | |||
| 187 | auto const& validity_spec_xml = | 187 | auto const& validity_spec_xml = |
| 188 | validity_xml.child("com:validityTimeSpecification"); | 188 | validity_xml.child("com:validityTimeSpecification"); |
| 189 | 189 | ||
| 190 | auto valid_periods = std::vector<time::period>{}; | 190 | auto valid_periods = std::vector<time::period<std::chrono::minutes>>{}; |
| 191 | auto exception_periods = std::vector<time::period>{}; | 191 | auto exception_periods = std::vector<time::period<std::chrono::minutes>>{}; |
| 192 | 192 | ||
| 193 | // TODO: com:overallEndTime may be missing (according to the DATEX | 193 | // TODO: com:overallEndTime may be missing (according to the DATEX |
| 194 | // II v3 data model) | 194 | // II v3 data model) |
| 195 | auto const overall_start_time = | 195 | auto const overall_start_time = parse_timestamp_secs( |
| 196 | parse_timestamp(validity_spec_xml.child_value("com:overallStartTime")); | 196 | validity_spec_xml.child_value("com:overallStartTime")); |
| 197 | auto const overall_end_time = | 197 | auto const overall_end_time = parse_timestamp_secs( |
| 198 | parse_timestamp(validity_spec_xml.child_value("com:overallEndTime")); | 198 | validity_spec_xml.child_value("com:overallEndTime")); |
| 199 | if (overall_start_time && overall_end_time | 199 | if (overall_start_time && overall_end_time |
| 200 | && *overall_start_time < *overall_end_time) | 200 | && *overall_start_time < *overall_end_time) |
| 201 | { | 201 | { |
| 202 | valid_periods.emplace_back(*overall_start_time, *overall_end_time); | 202 | valid_periods.emplace_back( |
| 203 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 204 | *overall_start_time), | ||
| 205 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 206 | *overall_end_time)); | ||
| 203 | 207 | ||
| 204 | for (auto const valid_period_xml : | 208 | for (auto const valid_period_xml : |
| 205 | validity_xml.children("com:validPeriod")) | 209 | validity_xml.children("com:validPeriod")) |
| 206 | { | 210 | { |
| 207 | auto const start_of_period = | 211 | auto const start_of_period = parse_timestamp_secs( |
| 208 | parse_timestamp(valid_period_xml.child_value("com:startOfPeriod")); | 212 | valid_period_xml.child_value("com:startOfPeriod")); |
| 209 | auto const end_of_period = | 213 | auto const end_of_period = parse_timestamp_secs( |
| 210 | parse_timestamp(valid_period_xml.child_value("com:endOfPeriod")); | 214 | valid_period_xml.child_value("com:endOfPeriod")); |
| 211 | if (start_of_period && end_of_period | 215 | if (start_of_period && end_of_period |
| 212 | && *start_of_period < *end_of_period) | 216 | && *start_of_period < *end_of_period) |
| 213 | { | 217 | { |
| 214 | valid_periods.emplace_back(*start_of_period, *end_of_period); | 218 | valid_periods.emplace_back( |
| 219 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 220 | *start_of_period), | ||
| 221 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 222 | *end_of_period)); | ||
| 215 | } | 223 | } |
| 216 | } | 224 | } |
| 217 | for (auto const exception_period_xml : | 225 | for (auto const exception_period_xml : |
| 218 | validity_xml.children("com:exceptionPeriod")) | 226 | validity_xml.children("com:exceptionPeriod")) |
| 219 | { | 227 | { |
| 220 | auto const start_of_period = parse_timestamp( | 228 | auto const start_of_period = parse_timestamp_secs( |
| 221 | exception_period_xml.child_value("com:startOfPeriod")); | 229 | exception_period_xml.child_value("com:startOfPeriod")); |
| 222 | auto const end_of_period = parse_timestamp( | 230 | auto const end_of_period = parse_timestamp_secs( |
| 223 | exception_period_xml.child_value("com:endOfPeriod")); | 231 | exception_period_xml.child_value("com:endOfPeriod")); |
| 224 | if (start_of_period && end_of_period | 232 | if (start_of_period && end_of_period |
| 225 | && *start_of_period < *end_of_period) | 233 | && *start_of_period < *end_of_period) |
| 226 | { | 234 | { |
| 227 | exception_periods.emplace_back(*start_of_period, *end_of_period); | 235 | exception_periods.emplace_back( |
| 236 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 237 | *start_of_period), | ||
| 238 | std::chrono::time_point_cast<std::chrono::minutes>( | ||
| 239 | *end_of_period)); | ||
| 228 | } | 240 | } |
| 229 | } | 241 | } |
| 230 | 242 | ||
| 231 | validity = | 243 | validity = |
| 232 | time::period_seq{valid_periods.begin(), valid_periods.end()}.except( | 244 | time::period_seq<std::chrono::minutes>{ |
| 233 | time::period_seq{ | 245 | valid_periods.begin(), valid_periods.end() |
| 234 | exception_periods.begin(), exception_periods.end() | 246 | } |
| 235 | }); | 247 | .except( |
| 248 | time::period_seq<std::chrono::minutes>{ | ||
| 249 | exception_periods.begin(), exception_periods.end() | ||
| 250 | }); | ||
| 236 | } | 251 | } |
| 237 | else | 252 | else |
| 238 | { | 253 | { |
| @@ -263,7 +278,7 @@ auto loader::load_situation_publication(std::string const& filename) | |||
| 263 | } | 278 | } |
| 264 | auto payload_xml = doc.child("mc:messageContainer").child("mc:payload"); | 279 | auto payload_xml = doc.child("mc:messageContainer").child("mc:payload"); |
| 265 | auto mpublication_time = | 280 | auto mpublication_time = |
| 266 | parse_timestamp(payload_xml.child_value("com:publicationTime")); | 281 | parse_timestamp_secs(payload_xml.child_value("com:publicationTime")); |
| 267 | if (!mpublication_time) | 282 | if (!mpublication_time) |
| 268 | throw std::runtime_error{ | 283 | throw std::runtime_error{ |
| 269 | "provided publication does not name publication time" | 284 | "provided publication does not name publication time" |
diff --git a/server/src/datex2.cppm b/server/src/datex2.cppm index ae66631..421d29c 100644 --- a/server/src/datex2.cppm +++ b/server/src/datex2.cppm | |||
| @@ -20,8 +20,8 @@ export struct situation; | |||
| 20 | 20 | ||
| 21 | export struct road_closure | 21 | export struct road_closure |
| 22 | { | 22 | { |
| 23 | std::weak_ptr<situation> parent; | 23 | std::weak_ptr<situation> parent = {}; |
| 24 | std::optional<time::period_seq> validity; | 24 | std::optional<time::period_seq<std::chrono::minutes>> validity = std::nullopt; |
| 25 | std::vector<geo::utm::zonable_wgs84_point> relevant_points = {}; | 25 | std::vector<geo::utm::zonable_wgs84_point> relevant_points = {}; |
| 26 | std::vector<std::shared_ptr<geo::utm::zonable_wgs84_linestring>> | 26 | std::vector<std::shared_ptr<geo::utm::zonable_wgs84_linestring>> |
| 27 | relevant_line_strings = {}; | 27 | relevant_line_strings = {}; |
| @@ -29,7 +29,7 @@ export struct road_closure | |||
| 29 | 29 | ||
| 30 | export struct situation | 30 | export struct situation |
| 31 | { | 31 | { |
| 32 | std::string id; | 32 | std::string id = {}; |
| 33 | std::optional<geo::utm::zonable_wgs84_point> location = | 33 | std::optional<geo::utm::zonable_wgs84_point> location = |
| 34 | std::nullopt; // as shown on the map, not used for querying | 34 | std::nullopt; // as shown on the map, not used for querying |
| 35 | std::vector<std::string> comments = {}; | 35 | std::vector<std::string> comments = {}; |
| @@ -38,8 +38,8 @@ export struct situation | |||
| 38 | 38 | ||
| 39 | export struct situation_publication | 39 | export struct situation_publication |
| 40 | { | 40 | { |
| 41 | time::timestamp publication_time; | 41 | time::timestamp<> publication_time = {}; |
| 42 | std::vector<std::shared_ptr<situation>> situations; | 42 | std::vector<std::shared_ptr<situation>> situations = {}; |
| 43 | }; | 43 | }; |
| 44 | 44 | ||
| 45 | export class loader | 45 | export class loader |
diff --git a/server/src/geo/utm_multizonal.cppm b/server/src/geo/utm_multizonal.cppm index 540e309..56c6481 100644 --- a/server/src/geo/utm_multizonal.cppm +++ b/server/src/geo/utm_multizonal.cppm | |||
| @@ -61,7 +61,7 @@ class from_wgs84_transforms : public multi_zone<from_wgs84_transform> | |||
| 61 | } | 61 | } |
| 62 | 62 | ||
| 63 | public: | 63 | public: |
| 64 | static from_wgs84_transforms const& instance() | 64 | static auto instance() -> from_wgs84_transforms const& |
| 65 | { | 65 | { |
| 66 | static from_wgs84_transforms inst; | 66 | static from_wgs84_transforms inst; |
| 67 | return inst; | 67 | return inst; |
| @@ -214,8 +214,7 @@ private: | |||
| 214 | local_rtrees_; | 214 | local_rtrees_; |
| 215 | 215 | ||
| 216 | public: | 216 | public: |
| 217 | template <std::convertible_to<T> U> | 217 | auto insert(utm::zonable_wgs84_linestring const& ls, T arg) -> void |
| 218 | auto insert(utm::zonable_wgs84_linestring const& ls, U&& arg) -> void | ||
| 219 | { | 218 | { |
| 220 | auto zone_segments = distribute_linestring_over_zones(ls); | 219 | auto zone_segments = distribute_linestring_over_zones(ls); |
| 221 | for (auto z = utm::zone::min(); z != utm::zone::max(); z = z.next()) | 220 | for (auto z = utm::zone::min(); z != utm::zone::max(); z = z.next()) |
| @@ -225,8 +224,7 @@ public: | |||
| 225 | auto blse = bgeo::return_buffer<utm::zone_local::prim::box>( | 224 | auto blse = bgeo::return_buffer<utm::zone_local::prim::box>( |
| 226 | bgeo::return_envelope<utm::zone_local::prim::box>(ls), | 225 | bgeo::return_envelope<utm::zone_local::prim::box>(ls), |
| 227 | 30.0 /* m */); | 226 | 30.0 /* m */); |
| 228 | local_rtrees_[z].insert( | 227 | local_rtrees_[z].insert(index_value{blse, std::move(ls), arg}); |
| 229 | index_value{blse, std::move(ls), std::forward<U>(arg)}); | ||
| 230 | } | 228 | } |
| 231 | } | 229 | } |
| 232 | } | 230 | } |
| @@ -279,8 +277,7 @@ private: | |||
| 279 | local_rtrees_; | 277 | local_rtrees_; |
| 280 | 278 | ||
| 281 | public: | 279 | public: |
| 282 | template <std::convertible_to<T> U> | 280 | auto insert(utm::zonable_wgs84_point const& p, T arg) -> void |
| 283 | auto insert(utm::zonable_wgs84_point const& p, U&& arg) -> void | ||
| 284 | { | 281 | { |
| 285 | auto to_utm = from_wgs84_transforms::instance(); | 282 | auto to_utm = from_wgs84_transforms::instance(); |
| 286 | 283 | ||
diff --git a/server/src/gpx.cpp b/server/src/gpx.cpp index 2193e6a..c43b380 100644 --- a/server/src/gpx.cpp +++ b/server/src/gpx.cpp | |||
| @@ -51,7 +51,7 @@ auto parse_wpt(xml::executor_ref e, xml::attribute_view attrs) | |||
| 51 | co_return *mp; | 51 | co_return *mp; |
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | auto parse_trkseg(xml::executor_ref e, xml::attribute_view) | 54 | auto parse_trkseg(xml::executor_ref e, xml::attribute_view /* attrs */) |
| 55 | -> xml::parser<track_segment> | 55 | -> xml::parser<track_segment> |
| 56 | { | 56 | { |
| 57 | auto s = track_segment{}; | 57 | auto s = track_segment{}; |
| @@ -61,7 +61,8 @@ auto parse_trkseg(xml::executor_ref e, xml::attribute_view) | |||
| 61 | co_return std::move(s); | 61 | co_return std::move(s); |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | auto parse_trk(xml::executor_ref e, xml::attribute_view) -> xml::parser<track> | 64 | auto parse_trk(xml::executor_ref e, xml::attribute_view /* attrs */) |
| 65 | -> xml::parser<track> | ||
| 65 | { | 66 | { |
| 66 | auto t = track{}; | 67 | auto t = track{}; |
| 67 | t.name = co_await allow_element( | 68 | t.name = co_await allow_element( |
| @@ -112,7 +113,7 @@ auto qname(std::string_view local) -> xml::qname_view | |||
| 112 | return {.ns_uri = xmlns, .local = local}; | 113 | return {.ns_uri = xmlns, .local = local}; |
| 113 | } | 114 | } |
| 114 | 115 | ||
| 115 | auto parse_metadata(xml::executor_ref e, xml::attribute_view) | 116 | auto parse_metadata(xml::executor_ref e, xml::attribute_view /* attrs */) |
| 116 | -> xml::parser<metadata> | 117 | -> xml::parser<metadata> |
| 117 | { | 118 | { |
| 118 | auto meta = metadata{}; | 119 | auto meta = metadata{}; |
| @@ -154,7 +155,7 @@ auto parse_wpt(xml::executor_ref e, xml::attribute_view attrs) | |||
| 154 | co_return *mp; | 155 | co_return *mp; |
| 155 | } | 156 | } |
| 156 | 157 | ||
| 157 | auto parse_trkseg(xml::executor_ref e, xml::attribute_view) | 158 | auto parse_trkseg(xml::executor_ref e, xml::attribute_view /* attrs */) |
| 158 | -> xml::parser<track_segment> | 159 | -> xml::parser<track_segment> |
| 159 | { | 160 | { |
| 160 | auto s = track_segment{}; | 161 | auto s = track_segment{}; |
| @@ -166,7 +167,8 @@ auto parse_trkseg(xml::executor_ref e, xml::attribute_view) | |||
| 166 | co_return std::move(s); | 167 | co_return std::move(s); |
| 167 | } | 168 | } |
| 168 | 169 | ||
| 169 | auto parse_trk(xml::executor_ref e, xml::attribute_view) -> xml::parser<track> | 170 | auto parse_trk(xml::executor_ref e, xml::attribute_view /* attrs */) |
| 171 | -> xml::parser<track> | ||
| 170 | { | 172 | { |
| 171 | auto t = track{}; | 173 | auto t = track{}; |
| 172 | t.name = co_await allow_element( | 174 | t.name = co_await allow_element( |
diff --git a/server/src/gpx.cppm b/server/src/gpx.cppm index 6267443..ab1b0a1 100644 --- a/server/src/gpx.cppm +++ b/server/src/gpx.cppm | |||
| @@ -9,27 +9,27 @@ namespace routemon::gpx { | |||
| 9 | 9 | ||
| 10 | struct metadata | 10 | struct metadata |
| 11 | { | 11 | { |
| 12 | std::optional<std::string> name; | 12 | std::optional<std::string> name = std::nullopt; |
| 13 | std::optional<std::string> desc; | 13 | std::optional<std::string> desc = std::nullopt; |
| 14 | }; | 14 | }; |
| 15 | 15 | ||
| 16 | struct track_segment | 16 | struct track_segment |
| 17 | { | 17 | { |
| 18 | geo::utm::zonable_wgs84_linestring waypoints; | 18 | geo::utm::zonable_wgs84_linestring waypoints = {}; |
| 19 | }; | 19 | }; |
| 20 | 20 | ||
| 21 | struct track | 21 | struct track |
| 22 | { | 22 | { |
| 23 | std::optional<std::string> name; | 23 | std::optional<std::string> name = std::nullopt; |
| 24 | std::optional<std::string> desc; | 24 | std::optional<std::string> desc = std::nullopt; |
| 25 | std::vector<track_segment> segments; | 25 | std::vector<track_segment> segments = {}; |
| 26 | }; | 26 | }; |
| 27 | 27 | ||
| 28 | struct file | 28 | struct file |
| 29 | { | 29 | { |
| 30 | std::string creator; | 30 | std::string creator = {}; |
| 31 | metadata meta; | 31 | metadata meta = {}; |
| 32 | std::vector<track> tracks; | 32 | std::vector<track> tracks = {}; |
| 33 | }; | 33 | }; |
| 34 | 34 | ||
| 35 | class reader | 35 | class reader |
diff --git a/server/src/http/ext/hmac_openssl.cppm b/server/src/http/ext/hmac_openssl.cppm new file mode 100644 index 0000000..52ccb86 --- /dev/null +++ b/server/src/http/ext/hmac_openssl.cppm | |||
| @@ -0,0 +1,10 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <openssl/evp.h> | ||
| 4 | #include <openssl/params.h> | ||
| 5 | |||
| 6 | export module routemon:hmac_openssl; | ||
| 7 | |||
| 8 | namespace routemon::hmac_openssl { | ||
| 9 | |||
| 10 | } | ||
diff --git a/server/src/http/ext/json.cppm b/server/src/http/ext/json.cppm new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/server/src/http/ext/json.cppm | |||
diff --git a/server/src/http_client.cppm b/server/src/http_client.cppm index 2047b01..accd5c0 100644 --- a/server/src/http_client.cppm +++ b/server/src/http_client.cppm | |||
| @@ -37,8 +37,9 @@ public: | |||
| 37 | auto host = std::string{req.at(bhttp::field::host)}; | 37 | auto host = std::string{req.at(bhttp::field::host)}; |
| 38 | if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) | 38 | if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) |
| 39 | { | 39 | { |
| 40 | throw beast::system_error( | 40 | throw beast::system_error{ |
| 41 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()); | 41 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() |
| 42 | }; | ||
| 42 | } | 43 | } |
| 43 | stream.set_verify_callback(ssl::host_name_verification(host)); | 44 | stream.set_verify_callback(ssl::host_name_verification(host)); |
| 44 | auto const results = resolver_.resolve(host, "443"); | 45 | auto const results = resolver_.resolve(host, "443"); |
diff --git a/server/src/http_server.cppm b/server/src/http_server.cppm index c111118..b75ada3 100644 --- a/server/src/http_server.cppm +++ b/server/src/http_server.cppm | |||
| @@ -264,12 +264,13 @@ auto make_preflight_rsp(preflight_response res, keep_alive ka) | |||
| 264 | // Using base_ctx instead of a template here since that saves you | 264 | // Using base_ctx instead of a template here since that saves you |
| 265 | // typing on invocation (and we do not care about the context type | 265 | // typing on invocation (and we do not care about the context type |
| 266 | // anyway, but all context types should derive from base_ctx). | 266 | // anyway, but all context types should derive from base_ctx). |
| 267 | template <bhttp::concepts::body_reader Body> | 267 | template <bhttp::concepts::body_reader Body, typename... Args> |
| 268 | auto read_request(base_ctx const& ctx, readable_request&& r) | 268 | auto read_request(base_ctx const& ctx, readable_request&& r, Args&&... args) |
| 269 | -> net::awaitable<bhttp::request<Body>> | 269 | -> net::awaitable<bhttp::request<Body>> |
| 270 | { | 270 | { |
| 271 | std::ignore = ctx; | 271 | std::ignore = ctx; |
| 272 | auto p = bhttp::request_parser<Body>{std::move(*r.p)}; | 272 | auto p = |
| 273 | bhttp::request_parser<Body>{std::move(*r.p), std::forward<Args>(args)...}; | ||
| 273 | co_await bhttp::async_read(*r.strm, *r.buf, p); | 274 | co_await bhttp::async_read(*r.strm, *r.buf, p); |
| 274 | co_return std::move(p.release()); | 275 | co_return std::move(p.release()); |
| 275 | } | 276 | } |
diff --git a/server/src/locale.cpp b/server/src/locale.cpp index 92bc33b..a964d5e 100644 --- a/server/src/locale.cpp +++ b/server/src/locale.cpp | |||
| @@ -206,7 +206,7 @@ constexpr auto messages_path = std::string_view{LOCALEDIR_AUX_XSTR(LOCALEDIR)}; | |||
| 206 | constexpr auto messages_path = std::string_view{"locale/dev"}; | 206 | constexpr auto messages_path = std::string_view{"locale/dev"}; |
| 207 | #endif // ifdef LOCALEDIR | 207 | #endif // ifdef LOCALEDIR |
| 208 | 208 | ||
| 209 | export auto make_generator() -> std::shared_ptr<blocale::generator const> | 209 | auto make_generator() -> std::shared_ptr<blocale::generator const> |
| 210 | { | 210 | { |
| 211 | auto lgen = std::make_shared<blocale::generator>(); | 211 | auto lgen = std::make_shared<blocale::generator>(); |
| 212 | lgen->add_messages_path(std::string{messages_path}); | 212 | lgen->add_messages_path(std::string{messages_path}); |
diff --git a/server/src/log.cppm b/server/src/log.cppm index 87382f6..10c2d7a 100644 --- a/server/src/log.cppm +++ b/server/src/log.cppm | |||
| @@ -4,7 +4,8 @@ import std; | |||
| 4 | 4 | ||
| 5 | namespace routemon::log { | 5 | namespace routemon::log { |
| 6 | 6 | ||
| 7 | export enum class level : std::uint8_t { | 7 | export enum class level : std::uint8_t |
| 8 | { | ||
| 8 | debug, | 9 | debug, |
| 9 | info, | 10 | info, |
| 10 | warn, | 11 | warn, |
diff --git a/server/src/main.cpp b/server/src/main.cpp index 3ef45c6..df750d9 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp | |||
| @@ -1,5 +1,6 @@ | |||
| 1 | #include <boost/asio.hpp> | 1 | #include <boost/asio.hpp> |
| 2 | #include <malloc.h> // for malloc_trim(3) | 2 | #include <malloc.h> // for malloc_trim(3) |
| 3 | #include <openssl/crypto.h> | ||
| 3 | 4 | ||
| 4 | import std; | 5 | import std; |
| 5 | import routemon; | 6 | import routemon; |
| @@ -7,27 +8,79 @@ import routemon; | |||
| 7 | namespace chrono = std::chrono; | 8 | namespace chrono = std::chrono; |
| 8 | namespace net = boost::asio; | 9 | namespace net = boost::asio; |
| 9 | 10 | ||
| 11 | using namespace std::literals::string_view_literals; | ||
| 12 | |||
| 10 | enum class exit_status | 13 | enum class exit_status |
| 11 | { | 14 | { |
| 15 | success, | ||
| 12 | failure, | 16 | failure, |
| 13 | bad_usage, | 17 | bad_usage, |
| 14 | }; | 18 | }; |
| 15 | 19 | ||
| 16 | auto real_main(std::span<char const*> args) -> exit_status | 20 | struct secure_buf |
| 17 | { | 21 | { |
| 18 | auto sink = routemon::log::make_sink(routemon::log::level::info); | 22 | void* p; |
| 19 | auto l = routemon::log::logger{sink}; | 23 | std::size_t size = 0; |
| 20 | 24 | ||
| 21 | if (args.size() != 2) | 25 | secure_buf(secure_buf const&) = delete; |
| 26 | secure_buf(secure_buf&&) = delete; | ||
| 27 | |||
| 28 | auto operator=(secure_buf const&) -> secure_buf& = delete; | ||
| 29 | auto operator=(secure_buf&&) -> secure_buf& = delete; | ||
| 30 | |||
| 31 | secure_buf(std::size_t size) : p{OPENSSL_malloc(size)} | ||
| 22 | { | 32 | { |
| 23 | l.error( | 33 | if (!this->p) |
| 24 | "Fatal: expected exactly one argument (the configuration file " | 34 | throw std::bad_alloc{}; |
| 25 | "location), got {}", | ||
| 26 | args.size() - 1); | ||
| 27 | return exit_status::bad_usage; | ||
| 28 | } | 35 | } |
| 29 | auto const* config_filename = args[1]; | ||
| 30 | 36 | ||
| 37 | ~secure_buf() { OPENSSL_clear_free(this->p, this->size); } | ||
| 38 | }; | ||
| 39 | |||
| 40 | auto ltrim_ws(std::string_view s) -> std::string_view | ||
| 41 | { | ||
| 42 | if (auto i = s.find_first_not_of(" \t\r\n"); i != std::string_view::npos) | ||
| 43 | s.remove_prefix(i); | ||
| 44 | return s; | ||
| 45 | } | ||
| 46 | auto rtrim_ws(std::string_view s) -> std::string_view | ||
| 47 | { | ||
| 48 | if (auto i = s.find_last_not_of(" \t\r\n"); i != std::string_view::npos) | ||
| 49 | return s.substr(0, i + 1); | ||
| 50 | return s; | ||
| 51 | } | ||
| 52 | auto trim_ws(std::string_view s) -> std::string_view | ||
| 53 | { | ||
| 54 | return rtrim_ws(ltrim_ws(s)); | ||
| 55 | } | ||
| 56 | |||
| 57 | // TODO: make own secure string type using the OpenSSL primitives | ||
| 58 | template <std::size_t max_size> | ||
| 59 | auto read_secret_to_string(std::string const& filename) -> std::string | ||
| 60 | { | ||
| 61 | static_assert(max_size <= 65536); // sounds reasonable enough? | ||
| 62 | |||
| 63 | auto f = std::ifstream{filename, std::ios::binary}; | ||
| 64 | if (!f) | ||
| 65 | throw std::system_error{ | ||
| 66 | errno, std::generic_category(), | ||
| 67 | std::format("opening secret located at {}", filename) | ||
| 68 | }; | ||
| 69 | auto buf_cap = max_size; | ||
| 70 | auto buf = secure_buf{max_size}; | ||
| 71 | f.read(static_cast<char*>(buf.p), static_cast<std::streamsize>(buf_cap)); | ||
| 72 | buf.size = static_cast<std::size_t>(f.gcount()); | ||
| 73 | f.seekg(0, std::ios::end); | ||
| 74 | if (f.peek() != std::ifstream::traits_type::eof()) | ||
| 75 | throw std::runtime_error{"secret is bigger than allowed"}; | ||
| 76 | |||
| 77 | return std::string{trim_ws( | ||
| 78 | std::string_view{static_cast<char const*>(buf.p), buf.size})}; | ||
| 79 | } | ||
| 80 | |||
| 81 | auto server_main(routemon::log::logger& l, routemon::config::app config) | ||
| 82 | -> exit_status | ||
| 83 | { | ||
| 31 | auto lgen = routemon::locale::make_generator(); | 84 | auto lgen = routemon::locale::make_generator(); |
| 32 | auto default_locale = lgen->generate("en_US.UTF-8"); | 85 | auto default_locale = lgen->generate("en_US.UTF-8"); |
| 33 | auto locales = { | 86 | auto locales = { |
| @@ -39,28 +92,32 @@ auto real_main(std::span<char const*> args) -> exit_status | |||
| 39 | 92 | ||
| 40 | auto ioc = net::io_context{1 /* concurrency hint */}; | 93 | auto ioc = net::io_context{1 /* concurrency hint */}; |
| 41 | 94 | ||
| 42 | auto config = routemon::config::app{}; | 95 | auto dbc = std::shared_ptr<routemon::database::connection>{}; |
| 43 | try | 96 | try |
| 44 | { | 97 | { |
| 45 | config = routemon::config::load_file(config_filename); | 98 | dbc = routemon::database::open(config.database.sqlite3_filename); |
| 46 | } | 99 | } |
| 47 | catch (std::exception const& e) | 100 | catch (std::exception const& e) |
| 48 | { | 101 | { |
| 49 | l.with("filename", std::string_view{config_filename}) | 102 | l.with("filename", config.database.sqlite3_filename) |
| 50 | .error("Failed to load configuration: {}", e.what()); | 103 | .error("Failed to open database: {}", e.what()); |
| 51 | return exit_status::failure; | 104 | return exit_status::failure; |
| 52 | } | 105 | } |
| 53 | sink->set_level(config.logger.level); | ||
| 54 | 106 | ||
| 55 | auto dbc = std::shared_ptr<routemon::database::connection>{}; | 107 | auto rwgps_creds = std::shared_ptr<routemon::rwgps::credentials>{}; |
| 56 | try | 108 | try |
| 57 | { | 109 | { |
| 58 | dbc = routemon::database::open(config.database.sqlite3_filename); | 110 | rwgps_creds.reset(new routemon::rwgps::credentials{ |
| 111 | // TODO: bad secrets handling. Too little information for proper error | ||
| 112 | // reporting. | ||
| 113 | read_secret_to_string<4096>(config.rwgps.api_key_filename), | ||
| 114 | read_secret_to_string<4096>(config.rwgps.api_secret_filename), | ||
| 115 | read_secret_to_string<4096>(config.rwgps.auth_token_filename), | ||
| 116 | }); | ||
| 59 | } | 117 | } |
| 60 | catch (std::exception const& e) | 118 | catch (std::exception const& e) |
| 61 | { | 119 | { |
| 62 | l.with("filename", config.database.sqlite3_filename) | 120 | l.error("Failed to read RWGPS credentials: {}", e.what()); |
| 63 | .error("Failed to open database: {}", e.what()); | ||
| 64 | return exit_status::failure; | 121 | return exit_status::failure; |
| 65 | } | 122 | } |
| 66 | 123 | ||
| @@ -94,7 +151,7 @@ auto real_main(std::span<char const*> args) -> exit_status | |||
| 94 | } | 151 | } |
| 95 | } | 152 | } |
| 96 | // Processing the feed is by far the most memory-intensive operation | 153 | // Processing the feed is by far the most memory-intensive operation |
| 97 | // during the run time of this application (at the moment), the | 154 | // during the run time of this application (at the moment); the |
| 98 | // resident set will likely never be this big again. So we ask libc | 155 | // resident set will likely never be this big again. So we ask libc |
| 99 | // to return as much memory as possible to the OS. | 156 | // to return as much memory as possible to the OS. |
| 100 | malloc_trim(0); | 157 | malloc_trim(0); |
| @@ -103,9 +160,9 @@ auto real_main(std::span<char const*> args) -> exit_status | |||
| 103 | chrono::duration_cast<chrono::milliseconds>(after_load - before_load); | 160 | chrono::duration_cast<chrono::milliseconds>(after_load - before_load); |
| 104 | l.info("Loading situations finished in {}", dur_load); | 161 | l.info("Loading situations finished in {}", dur_load); |
| 105 | 162 | ||
| 106 | auto handler = routemon::api::handler{l, std::move(pub)}; | 163 | auto handler = routemon::api::handler{l, dbc, std::move(pub)}; |
| 107 | auto http_server = routemon::srv::server{ | 164 | auto http_server = routemon::srv::server{ |
| 108 | l, config.http_server, std::move(lsel), std::move(handler) | 165 | l, config.http_server, rwgps_creds, std::move(lsel), std::move(handler), |
| 109 | }; | 166 | }; |
| 110 | http_server.spawn(ioc); | 167 | http_server.spawn(ioc); |
| 111 | ioc.run(); | 168 | ioc.run(); |
| @@ -114,19 +171,131 @@ auto real_main(std::span<char const*> args) -> exit_status | |||
| 114 | return exit_status::failure; | 171 | return exit_status::failure; |
| 115 | } | 172 | } |
| 116 | 173 | ||
| 174 | auto migrate_main( | ||
| 175 | routemon::log::logger& l, routemon::config::app config, | ||
| 176 | std::int64_t target_db_version) -> exit_status | ||
| 177 | { | ||
| 178 | auto m = std::unique_ptr<routemon::migrate::migrator>{}; | ||
| 179 | try | ||
| 180 | { | ||
| 181 | m.reset( | ||
| 182 | new routemon::migrate::migrator{l, config.database.sqlite3_filename}); | ||
| 183 | } | ||
| 184 | catch (std::exception const& e) | ||
| 185 | { | ||
| 186 | l.with("filename", config.database.sqlite3_filename) | ||
| 187 | .error("Failed to open database: {}", e.what()); | ||
| 188 | return exit_status::failure; | ||
| 189 | } | ||
| 190 | |||
| 191 | try | ||
| 192 | { | ||
| 193 | m->migrate_to(target_db_version); | ||
| 194 | } | ||
| 195 | catch (std::exception const& e) | ||
| 196 | { | ||
| 197 | l.error("Failed to migrate database: {}", e.what()); | ||
| 198 | return exit_status::failure; | ||
| 199 | } | ||
| 200 | |||
| 201 | return exit_status::success; | ||
| 202 | } | ||
| 203 | |||
| 204 | // Arguments not including own name (so argv[1..]). | ||
| 205 | auto real_main(std::span<char const*> args) -> exit_status | ||
| 206 | { | ||
| 207 | auto const sink = routemon::log::make_sink(routemon::log::level::info); | ||
| 208 | auto l = routemon::log::logger{sink}; | ||
| 209 | |||
| 210 | auto load_config = [&](char const* config_filename) | ||
| 211 | -> std::expected<routemon::config::app, exit_status> | ||
| 212 | { | ||
| 213 | try | ||
| 214 | { | ||
| 215 | auto const config = routemon::config::load_file(config_filename); | ||
| 216 | sink->set_level(config.logger.level); | ||
| 217 | return config; | ||
| 218 | } | ||
| 219 | catch (std::exception const& e) | ||
| 220 | { | ||
| 221 | l.with("filename", std::string_view{config_filename}) | ||
| 222 | .error("Failed to load configuration: {}", e.what()); | ||
| 223 | return std::unexpected{exit_status::failure}; | ||
| 224 | } | ||
| 225 | }; | ||
| 226 | |||
| 227 | if (args.size() <= 0) | ||
| 228 | { | ||
| 229 | l.error( | ||
| 230 | "Fatal: expected at least a subcommand argument (∈ {{migrate, " | ||
| 231 | "server}}), got {} arguments", | ||
| 232 | args.size()); | ||
| 233 | return exit_status::bad_usage; | ||
| 234 | } | ||
| 235 | |||
| 236 | if (args[0] == "server"sv) | ||
| 237 | { | ||
| 238 | args = args.subspan<1>(); | ||
| 239 | if (args.size() != 1) | ||
| 240 | { | ||
| 241 | l.error( | ||
| 242 | "Fatal: expected exactly one argument (the configuration file " | ||
| 243 | "location), got {}", | ||
| 244 | args.size()); | ||
| 245 | return exit_status::bad_usage; | ||
| 246 | } | ||
| 247 | auto mconfig = load_config(args[0]); | ||
| 248 | if (!mconfig) | ||
| 249 | return mconfig.error(); | ||
| 250 | return server_main(l, std::move(*mconfig)); | ||
| 251 | } | ||
| 252 | else if (args[0] == "migrate"sv) | ||
| 253 | { | ||
| 254 | args = args.subspan<1>(); | ||
| 255 | if (args.size() != 2) | ||
| 256 | { | ||
| 257 | l.error( | ||
| 258 | "Fatal: expected exactly two arguments (the configuration file " | ||
| 259 | "location and database version to migrate to), got {}", | ||
| 260 | args.size()); | ||
| 261 | return exit_status::bad_usage; | ||
| 262 | } | ||
| 263 | auto mconfig = load_config(args[0]); | ||
| 264 | if (!mconfig) | ||
| 265 | return mconfig.error(); | ||
| 266 | auto mtarget_db_version = routemon::util::parse_int<std::int64_t>(args[1]); | ||
| 267 | if (!mtarget_db_version || *mtarget_db_version < 0) | ||
| 268 | { | ||
| 269 | l.error( | ||
| 270 | "Fatal: could not parse target database version ({}) as a " | ||
| 271 | "non-negative integer", | ||
| 272 | args[1]); | ||
| 273 | return exit_status::bad_usage; | ||
| 274 | } | ||
| 275 | return migrate_main(l, std::move(*mconfig), *mtarget_db_version); | ||
| 276 | } | ||
| 277 | else | ||
| 278 | { | ||
| 279 | l.error("Fatal: unrecognized subcommand {}", args[0]); | ||
| 280 | return exit_status::bad_usage; | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 117 | auto main(int argc, char* argv[]) -> int | 284 | auto main(int argc, char* argv[]) -> int |
| 118 | { | 285 | { |
| 119 | if (argc < 0) | 286 | if (argc < 1) |
| 120 | { | 287 | { |
| 121 | std::cout << "Fatal: argument count below zero" << std::endl; | 288 | std::cout << "Fatal: argument count below one" << std::endl; |
| 122 | return EXIT_FAILURE; | 289 | return EXIT_FAILURE; |
| 123 | } | 290 | } |
| 124 | auto res = real_main( | 291 | auto res = real_main( |
| 125 | std::span{ | 292 | std::span{ |
| 126 | const_cast<char const**>(argv), static_cast<std::size_t>(argc) | 293 | const_cast<char const**>(argv + 1), static_cast<std::size_t>(argc - 1) |
| 127 | }); | 294 | }); |
| 128 | switch (res) | 295 | switch (res) |
| 129 | { | 296 | { |
| 297 | case exit_status::success: | ||
| 298 | return EXIT_SUCCESS; | ||
| 130 | case exit_status::failure: | 299 | case exit_status::failure: |
| 131 | return EXIT_FAILURE; | 300 | return EXIT_FAILURE; |
| 132 | case exit_status::bad_usage: | 301 | case exit_status::bad_usage: |
diff --git a/server/src/migrate.cppm b/server/src/migrate.cppm new file mode 100644 index 0000000..e5cd52a --- /dev/null +++ b/server/src/migrate.cppm | |||
| @@ -0,0 +1,126 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <cassert> | ||
| 4 | |||
| 5 | export module routemon:migrate; | ||
| 6 | |||
| 7 | import :log; | ||
| 8 | import :sqlite3; | ||
| 9 | |||
| 10 | namespace routemon::migrate { | ||
| 11 | |||
| 12 | auto load_migrations(std::int64_t current_version, std::int64_t target_version) | ||
| 13 | -> std::vector<std::string> | ||
| 14 | { | ||
| 15 | if (current_version < 0 || target_version < 0) | ||
| 16 | throw std::invalid_argument{"database versions must be nonnegative"}; | ||
| 17 | if (target_version < current_version) | ||
| 18 | throw std::runtime_error{"migrating down is not supported yet"}; | ||
| 19 | if (current_version == target_version) | ||
| 20 | return {}; | ||
| 21 | assert(current_version < target_version); | ||
| 22 | |||
| 23 | // TODO: narrow_cast or something like that | ||
| 24 | auto migration_sqls = | ||
| 25 | std::vector<std::optional<std::pair<std::filesystem::path, std::string>>>{ | ||
| 26 | static_cast<std::size_t>(target_version - current_version) | ||
| 27 | }; | ||
| 28 | for (auto const& entry : std::filesystem::directory_iterator{"migrations"}) | ||
| 29 | { | ||
| 30 | if (!std::filesystem::is_regular_file(entry.status())) | ||
| 31 | continue; | ||
| 32 | auto const filename = std::string{entry.path().filename()}; | ||
| 33 | if (!filename.ends_with("_up.sql")) | ||
| 34 | continue; | ||
| 35 | auto const [no_str, mrest] = util::split_on(filename, '_'); | ||
| 36 | if (!mrest) | ||
| 37 | continue; | ||
| 38 | auto const mno = util::parse_int<std::int64_t>(no_str); | ||
| 39 | if (!mno || *mno < 1) | ||
| 40 | continue; | ||
| 41 | if (*mno <= current_version || target_version < *mno) | ||
| 42 | continue; | ||
| 43 | auto const i = static_cast<std::size_t>(*mno - current_version - 1); | ||
| 44 | |||
| 45 | if (migration_sqls[i]) | ||
| 46 | throw std::runtime_error{std::format( | ||
| 47 | "found more than one (up) migration file for version {}", *mno)}; | ||
| 48 | |||
| 49 | auto f = std::ifstream{entry.path(), std::ios::binary}; | ||
| 50 | auto contents = std::string{ | ||
| 51 | std::istreambuf_iterator<char>{f}, | ||
| 52 | std::istreambuf_iterator<char>{}, | ||
| 53 | }; | ||
| 54 | |||
| 55 | migration_sqls[i] = {entry.path(), contents}; | ||
| 56 | } | ||
| 57 | |||
| 58 | return migration_sqls | std::views::enumerate | ||
| 59 | | std::views::transform( | ||
| 60 | [current_version](auto&& pair) -> std::string | ||
| 61 | { | ||
| 62 | auto&& [i, mentry] = pair; | ||
| 63 | if (!mentry) | ||
| 64 | throw std::runtime_error{std::format( | ||
| 65 | "no migration found to version {}", | ||
| 66 | current_version + i + 1)}; | ||
| 67 | return std::move(mentry->second); | ||
| 68 | }) | ||
| 69 | | std::ranges::to<std::vector<std::string>>(); | ||
| 70 | } | ||
| 71 | |||
| 72 | export class migrator | ||
| 73 | { | ||
| 74 | log::logger l_; | ||
| 75 | sqlite3::connection dbc_; | ||
| 76 | |||
| 77 | auto current_version() -> std::int64_t | ||
| 78 | { | ||
| 79 | if (auto const [has_migrations_table] = | ||
| 80 | dbc_.query( | ||
| 81 | "SELECT COUNT(*) FROM sqlite_schema WHERE " | ||
| 82 | "type IS 'table' AND " | ||
| 83 | "name IS 'migration'") | ||
| 84 | .scan_row_max1<std::int64_t>(); | ||
| 85 | has_migrations_table) | ||
| 86 | return std::get<0>(dbc_.query("SELECT version FROM migration") | ||
| 87 | .scan_row_max1<std::int64_t>()); | ||
| 88 | return 0; | ||
| 89 | } | ||
| 90 | |||
| 91 | public: | ||
| 92 | explicit migrator(log::logger const& l, std::string const& filename) | ||
| 93 | : l_{l.sub("migrator")}, dbc_{sqlite3::open(filename)} | ||
| 94 | { | ||
| 95 | } | ||
| 96 | |||
| 97 | auto migrate_to(std::int64_t target_version) -> void | ||
| 98 | { | ||
| 99 | // Part of function contract. Consider throwing instead? | ||
| 100 | if (target_version < 0) | ||
| 101 | throw std::invalid_argument{ | ||
| 102 | "target database version must be nonnegative" | ||
| 103 | }; | ||
| 104 | |||
| 105 | auto current = current_version(); | ||
| 106 | auto const migration_sqls = load_migrations(current, target_version); | ||
| 107 | |||
| 108 | for (auto const& sql : migration_sqls) | ||
| 109 | { | ||
| 110 | l_.info("Migrating from schema version {} to {}", current, current + 1); | ||
| 111 | migrate_step(++current, sql); | ||
| 112 | } | ||
| 113 | } | ||
| 114 | |||
| 115 | auto migrate_step(std::int64_t target_version, util::zstring_view sql) -> void | ||
| 116 | { | ||
| 117 | auto tx = sqlite3::tx{dbc_}; | ||
| 118 | while (!sql.empty()) | ||
| 119 | tx.exec_first(sql); | ||
| 120 | tx.exec( | ||
| 121 | "UPDATE migration SET version = :version", | ||
| 122 | [target_version](auto& s) { s.bind(":version", target_version); }); | ||
| 123 | } | ||
| 124 | }; | ||
| 125 | |||
| 126 | } // namespace routemon::migrate | ||
diff --git a/server/src/routemon.cppm b/server/src/routemon.cppm index 62db02a..8946cf5 100644 --- a/server/src/routemon.cppm +++ b/server/src/routemon.cppm | |||
| @@ -6,6 +6,7 @@ export import :datex2; | |||
| 6 | export import :gpx; | 6 | export import :gpx; |
| 7 | export import :locale; | 7 | export import :locale; |
| 8 | export import :log; | 8 | export import :log; |
| 9 | export import :migrate; | ||
| 9 | export import :srv; | 10 | export import :srv; |
| 10 | export import :rwgps; | 11 | export import :rwgps; |
| 11 | export import :util; | 12 | export import :util; |
diff --git a/server/src/rwgps.cpp b/server/src/rwgps.cpp index b8ebf11..21584a8 100644 --- a/server/src/rwgps.cpp +++ b/server/src/rwgps.cpp | |||
| @@ -4,6 +4,8 @@ module; | |||
| 4 | #include <boost/beast/http.hpp> | 4 | #include <boost/beast/http.hpp> |
| 5 | #include <boost/json.hpp> | 5 | #include <boost/json.hpp> |
| 6 | 6 | ||
| 7 | #include <openssl/crypto.h> | ||
| 8 | |||
| 7 | module routemon:rwgps$impl; | 9 | module routemon:rwgps$impl; |
| 8 | 10 | ||
| 9 | import :rwgps; | 11 | import :rwgps; |
| @@ -14,34 +16,6 @@ namespace json = boost::json; | |||
| 14 | 16 | ||
| 15 | namespace routemon::rwgps { | 17 | namespace routemon::rwgps { |
| 16 | 18 | ||
| 17 | export struct route_summary | ||
| 18 | { | ||
| 19 | std::int64_t id; | ||
| 20 | std::int64_t user_id; | ||
| 21 | std::string url; | ||
| 22 | std::string name; | ||
| 23 | std::string description; | ||
| 24 | }; | ||
| 25 | |||
| 26 | struct pagination | ||
| 27 | { | ||
| 28 | std::size_t record_count; | ||
| 29 | std::size_t page_count; | ||
| 30 | std::size_t page_size; | ||
| 31 | std::optional<std::string> next_page_url; | ||
| 32 | }; | ||
| 33 | |||
| 34 | struct get_routes_meta | ||
| 35 | { | ||
| 36 | pagination pagination; | ||
| 37 | }; | ||
| 38 | |||
| 39 | struct get_routes_response | ||
| 40 | { | ||
| 41 | std::vector<route_summary> routes; | ||
| 42 | get_routes_meta meta; | ||
| 43 | }; | ||
| 44 | |||
| 45 | auto tag_invoke(json::value_to_tag<route_summary> const&, json::value const& jv) | 19 | auto tag_invoke(json::value_to_tag<route_summary> const&, json::value const& jv) |
| 46 | -> route_summary | 20 | -> route_summary |
| 47 | { | 21 | { |
| @@ -91,6 +65,133 @@ auto json_value_to_get_routes_response(json::value const& jv) | |||
| 91 | return json::value_to<get_routes_response>(jv); | 65 | return json::value_to<get_routes_response>(jv); |
| 92 | } | 66 | } |
| 93 | 67 | ||
| 68 | static json::value const json_null = json::value{}; | ||
| 69 | |||
| 70 | auto at_or_null(json::value const& v, std::string_view key) | ||
| 71 | -> json::value const& | ||
| 72 | { | ||
| 73 | if (v.is_null()) | ||
| 74 | return json_null; | ||
| 75 | auto const* obj = v.if_object(); | ||
| 76 | if (!obj) | ||
| 77 | throw std::system_error{make_error_code(json::error::not_object)}; | ||
| 78 | if (auto it = obj->find(key); it != obj->end()) | ||
| 79 | return it->value(); | ||
| 80 | return json_null; | ||
| 81 | } | ||
| 82 | |||
| 83 | auto tag_invoke( | ||
| 84 | json::value_to_tag<notification_cause> const&, json::value const& jv) | ||
| 85 | -> notification_cause | ||
| 86 | { | ||
| 87 | if (jv == "created") | ||
| 88 | return notification_cause::created; | ||
| 89 | if (jv == "updated") | ||
| 90 | return notification_cause::updated; | ||
| 91 | if (jv == "deleted") | ||
| 92 | return notification_cause::deleted; | ||
| 93 | if (jv == "added") | ||
| 94 | return notification_cause::added; | ||
| 95 | if (jv == "removed") | ||
| 96 | return notification_cause::removed; | ||
| 97 | return notification_cause::unknown; | ||
| 98 | } | ||
| 99 | |||
| 100 | auto tag_invoke( | ||
| 101 | json::value_to_tag<notification_item_type> const&, json::value const& jv) | ||
| 102 | -> notification_item_type | ||
| 103 | { | ||
| 104 | if (jv == "trip") | ||
| 105 | return notification_item_type::trip; | ||
| 106 | if (jv == "route") | ||
| 107 | return notification_item_type::route; | ||
| 108 | if (jv == "event") | ||
| 109 | return notification_item_type::event; | ||
| 110 | if (jv == "event_participant") | ||
| 111 | return notification_item_type::event_participant; | ||
| 112 | if (jv == "club_member") | ||
| 113 | return notification_item_type::club_member; | ||
| 114 | if (jv == "authorization") | ||
| 115 | return notification_item_type::authorization; | ||
| 116 | return notification_item_type::unknown; | ||
| 117 | } | ||
| 118 | |||
| 119 | auto tag_invoke( | ||
| 120 | json::value_to_tag<notification_target_collection_type> const&, | ||
| 121 | json::value const& jv) -> notification_target_collection_type | ||
| 122 | { | ||
| 123 | if (jv == "pinned") | ||
| 124 | return notification_target_collection_type::pinned; | ||
| 125 | return notification_target_collection_type::unknown; | ||
| 126 | } | ||
| 127 | |||
| 128 | auto tag_invoke( | ||
| 129 | json::value_to_tag<notification_target_collection> const&, | ||
| 130 | json::value const& jv) -> notification_target_collection | ||
| 131 | { | ||
| 132 | return { | ||
| 133 | .id = json::value_to<std::int64_t>(at_or_null(jv, "id")), | ||
| 134 | .type = json::value_to<notification_target_collection_type>( | ||
| 135 | at_or_null(jv, "type")), | ||
| 136 | .url = json::value_to<std::optional<std::string>>(at_or_null(jv, "url")), | ||
| 137 | }; | ||
| 138 | } | ||
| 139 | |||
| 140 | auto tag_invoke(json::value_to_tag<notification> const&, json::value const& jv) | ||
| 141 | -> notification | ||
| 142 | { | ||
| 143 | return { | ||
| 144 | .user_id = json::value_to<std::int64_t>(at_or_null(jv, "user_id")), | ||
| 145 | .item_type = | ||
| 146 | json::value_to<notification_item_type>(at_or_null(jv, "item_type")), | ||
| 147 | .item_id = | ||
| 148 | json::value_to<std::optional<std::int64_t>>(at_or_null(jv, "item_id")), | ||
| 149 | .item_user_id = json::value_to<std::optional<std::int64_t>>( | ||
| 150 | at_or_null(jv, "item_user_id")), | ||
| 151 | .item_url = | ||
| 152 | json::value_to<std::optional<std::string>>(at_or_null(jv, "item_url")), | ||
| 153 | .action = json::value_to<notification_cause>(at_or_null(jv, "action")), | ||
| 154 | .collection = json::value_to<std::optional<notification_target_collection>>( | ||
| 155 | at_or_null(jv, "collection")), | ||
| 156 | }; | ||
| 157 | } | ||
| 158 | |||
| 159 | auto tag_invoke( | ||
| 160 | json::value_to_tag<webhook_request> const&, json::value const& jv) | ||
| 161 | -> webhook_request | ||
| 162 | { | ||
| 163 | return { | ||
| 164 | .notifications = json::value_to<std::vector<notification>>( | ||
| 165 | at_or_null(jv, "notifications")), | ||
| 166 | }; | ||
| 167 | } | ||
| 168 | |||
| 169 | credentials::credentials( | ||
| 170 | std::string&& api_key, std::string&& api_secret, std::string&& auth_token) | ||
| 171 | : api_key_{std::move(api_key)}, api_secret_{std::move(api_secret)}, | ||
| 172 | auth_token_{std::move(auth_token)} | ||
| 173 | { | ||
| 174 | } | ||
| 175 | |||
| 176 | credentials::~credentials() | ||
| 177 | { | ||
| 178 | OPENSSL_cleanse(api_key_.data(), api_key_.capacity()); | ||
| 179 | OPENSSL_cleanse(api_secret_.data(), api_secret_.capacity()); | ||
| 180 | OPENSSL_cleanse(auth_token_.data(), auth_token_.capacity()); | ||
| 181 | } | ||
| 182 | |||
| 183 | auto credentials::api_key() const -> std::string const& { return api_key_; } | ||
| 184 | |||
| 185 | auto credentials::api_secret() const -> std::string const& | ||
| 186 | { | ||
| 187 | return api_secret_; | ||
| 188 | } | ||
| 189 | |||
| 190 | auto credentials::auth_token() const -> std::string const& | ||
| 191 | { | ||
| 192 | return auth_token_; | ||
| 193 | } | ||
| 194 | |||
| 94 | constexpr std::string host = "ridewithgps.com"; | 195 | constexpr std::string host = "ridewithgps.com"; |
| 95 | 196 | ||
| 96 | // TODO: handle failure appropriately | 197 | // TODO: handle failure appropriately |
| @@ -102,8 +203,8 @@ auto client::get_routes_page(std::size_t page) -> get_routes_response | |||
| 102 | 11, // HTTP 1.1 | 203 | 11, // HTTP 1.1 |
| 103 | }; | 204 | }; |
| 104 | req.set(bhttp::field::host, host); | 205 | req.set(bhttp::field::host, host); |
| 105 | req.set("x-rwgps-api-key", api_key_); | 206 | req.set("x-rwgps-api-key", creds_->api_key()); |
| 106 | req.set("x-rwgps-auth-token", auth_token_); | 207 | req.set("x-rwgps-auth-token", creds_->auth_token()); |
| 107 | 208 | ||
| 108 | auto rsp = hc_.do_request(req); | 209 | auto rsp = hc_.do_request(req); |
| 109 | auto p = json::stream_parser{}; | 210 | auto p = json::stream_parser{}; |
| @@ -114,10 +215,9 @@ auto client::get_routes_page(std::size_t page) -> get_routes_response | |||
| 114 | } | 215 | } |
| 115 | 216 | ||
| 116 | client::client( | 217 | client::client( |
| 117 | net::io_context& ioc, log::logger const& l, std::string api_key, | 218 | net::io_context& ioc, log::logger const& l, |
| 118 | std::string auth_token) | 219 | std::shared_ptr<credentials> creds) |
| 119 | : l_{l.sub("rwgps-client")}, hc_{ioc}, api_key_{std::move(api_key)}, | 220 | : l_{l.sub("rwgps-client")}, hc_{ioc}, creds_{std::move(creds)} |
| 120 | auth_token_{std::move(auth_token)} | ||
| 121 | { | 221 | { |
| 122 | } | 222 | } |
| 123 | 223 | ||
diff --git a/server/src/rwgps.cppm b/server/src/rwgps.cppm index 2ed124e..880ea3a 100644 --- a/server/src/rwgps.cppm +++ b/server/src/rwgps.cppm | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | module; | 1 | module; |
| 2 | 2 | ||
| 3 | #include <boost/asio/io_context.hpp> | 3 | #include <boost/asio/io_context.hpp> |
| 4 | #include <boost/json/conversion.hpp> | ||
| 4 | 5 | ||
| 5 | export module routemon:rwgps; | 6 | export module routemon:rwgps; |
| 6 | 7 | ||
| @@ -9,6 +10,7 @@ import :http.client; | |||
| 9 | import :log; | 10 | import :log; |
| 10 | 11 | ||
| 11 | namespace net = boost::asio; | 12 | namespace net = boost::asio; |
| 13 | namespace json = boost::json; | ||
| 12 | 14 | ||
| 13 | namespace routemon::rwgps { | 15 | namespace routemon::rwgps { |
| 14 | 16 | ||
| @@ -21,6 +23,62 @@ export struct route_summary | |||
| 21 | std::string description; | 23 | std::string description; |
| 22 | }; | 24 | }; |
| 23 | 25 | ||
| 26 | enum class notification_cause | ||
| 27 | { | ||
| 28 | unknown, | ||
| 29 | created, | ||
| 30 | updated, | ||
| 31 | deleted, | ||
| 32 | added, | ||
| 33 | removed, | ||
| 34 | }; | ||
| 35 | |||
| 36 | enum class notification_item_type | ||
| 37 | { | ||
| 38 | unknown, | ||
| 39 | trip, | ||
| 40 | route, | ||
| 41 | event, | ||
| 42 | event_participant, | ||
| 43 | club_member, | ||
| 44 | authorization, | ||
| 45 | }; | ||
| 46 | |||
| 47 | enum notification_target_collection_type | ||
| 48 | { | ||
| 49 | unknown, | ||
| 50 | pinned, | ||
| 51 | }; | ||
| 52 | |||
| 53 | struct notification_target_collection | ||
| 54 | { | ||
| 55 | std::int64_t id; | ||
| 56 | notification_target_collection_type type; | ||
| 57 | std::optional<std::string> url; | ||
| 58 | }; | ||
| 59 | |||
| 60 | struct notification | ||
| 61 | { | ||
| 62 | // User that took the action | ||
| 63 | std::int64_t user_id; | ||
| 64 | notification_item_type item_type; | ||
| 65 | std::optional<std::int64_t> item_id; | ||
| 66 | // User that owns the item | ||
| 67 | std::optional<std::int64_t> item_user_id; | ||
| 68 | std::optional<std::string> item_url; | ||
| 69 | notification_cause action; | ||
| 70 | std::optional<notification_target_collection> collection; | ||
| 71 | }; | ||
| 72 | |||
| 73 | struct webhook_request | ||
| 74 | { | ||
| 75 | std::vector<notification> notifications = {}; | ||
| 76 | }; | ||
| 77 | |||
| 78 | auto tag_invoke( | ||
| 79 | json::value_to_tag<webhook_request> const&, json::value const& jv) | ||
| 80 | -> webhook_request; | ||
| 81 | |||
| 24 | struct pagination | 82 | struct pagination |
| 25 | { | 83 | { |
| 26 | std::size_t record_count; | 84 | std::size_t record_count; |
| @@ -40,19 +98,35 @@ struct get_routes_response | |||
| 40 | get_routes_meta meta; | 98 | get_routes_meta meta; |
| 41 | }; | 99 | }; |
| 42 | 100 | ||
| 101 | export class credentials | ||
| 102 | { | ||
| 103 | std::string api_key_; | ||
| 104 | std::string api_secret_; | ||
| 105 | std::string auth_token_; | ||
| 106 | |||
| 107 | public: | ||
| 108 | credentials( | ||
| 109 | std::string&& api_key, std::string&& api_secret, | ||
| 110 | std::string&& auth_token); | ||
| 111 | ~credentials(); | ||
| 112 | |||
| 113 | auto api_key() const -> std::string const&; | ||
| 114 | auto api_secret() const -> std::string const&; | ||
| 115 | auto auth_token() const -> std::string const&; | ||
| 116 | }; | ||
| 117 | |||
| 43 | export class client | 118 | export class client |
| 44 | { | 119 | { |
| 45 | log::logger l_; | 120 | log::logger l_; |
| 46 | http::client hc_; | 121 | http::client hc_; |
| 47 | std::string api_key_; | 122 | std::shared_ptr<credentials> creds_; |
| 48 | std::string auth_token_; | ||
| 49 | 123 | ||
| 50 | auto get_routes_page(std::size_t page) -> get_routes_response; | 124 | auto get_routes_page(std::size_t page) -> get_routes_response; |
| 51 | 125 | ||
| 52 | public: | 126 | public: |
| 53 | explicit client( | 127 | explicit client( |
| 54 | net::io_context& ioc, log::logger const& l, std::string api_key, | 128 | net::io_context& ioc, log::logger const& l, |
| 55 | std::string auth_token); | 129 | std::shared_ptr<credentials> creds); |
| 56 | 130 | ||
| 57 | auto get_all_routes() -> std::vector<route_summary>; | 131 | auto get_all_routes() -> std::vector<route_summary>; |
| 58 | }; | 132 | }; |
diff --git a/server/src/rwgps_webhook.cppm b/server/src/rwgps_webhook.cppm new file mode 100644 index 0000000..5a1df37 --- /dev/null +++ b/server/src/rwgps_webhook.cppm | |||
| @@ -0,0 +1,237 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | #include <boost/asio/ssl/error.hpp> | ||
| 4 | #include <boost/beast/core.hpp> | ||
| 5 | #include <boost/beast/http.hpp> | ||
| 6 | #include <boost/json/stream_parser.hpp> | ||
| 7 | |||
| 8 | #include <openssl/err.h> | ||
| 9 | #include <openssl/evp.h> | ||
| 10 | #include <openssl/params.h> | ||
| 11 | |||
| 12 | export module routemon:rwgps.webhook; | ||
| 13 | |||
| 14 | import :http.common; | ||
| 15 | import :util; | ||
| 16 | import std; | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | namespace net = boost::asio; | ||
| 21 | namespace json = boost::json; | ||
| 22 | |||
| 23 | } // namespace | ||
| 24 | |||
| 25 | namespace routemon::rwgps::webhook { | ||
| 26 | |||
| 27 | // TODO: constrain T? What are appropriate constraints? | ||
| 28 | template <typename T> | ||
| 29 | class hmac_readable | ||
| 30 | { | ||
| 31 | std::string_view key_; | ||
| 32 | std::optional<std::array<std::uint8_t, 32>> mac_; | ||
| 33 | T res_; | ||
| 34 | |||
| 35 | template <bhttp::concepts::body_reader Sub> | ||
| 36 | friend struct hmac_body_reader; | ||
| 37 | |||
| 38 | public: | ||
| 39 | template <typename... Args> | ||
| 40 | explicit hmac_readable(std::string_view key, Args&&... args) | ||
| 41 | : key_{key}, res_{std::forward<Args>(args)...} | ||
| 42 | { | ||
| 43 | } | ||
| 44 | |||
| 45 | template <class Self> | ||
| 46 | constexpr auto get(this Self&& self) -> auto&& | ||
| 47 | { | ||
| 48 | return std::forward<Self>(self).res_; | ||
| 49 | } | ||
| 50 | |||
| 51 | auto mac() const -> std::optional<std::array<std::uint8_t, 32>> | ||
| 52 | { | ||
| 53 | return mac_; | ||
| 54 | } | ||
| 55 | }; | ||
| 56 | |||
| 57 | template <bhttp::concepts::body_reader Sub> | ||
| 58 | class hmac_body_reader | ||
| 59 | { | ||
| 60 | EVP_MAC* mac_ = nullptr; | ||
| 61 | EVP_MAC_CTX* ctx_ = nullptr; | ||
| 62 | |||
| 63 | util::not_null<hmac_readable<typename Sub::value_type>*> v_; | ||
| 64 | Sub::reader subr_; | ||
| 65 | beast::error_code ec_; | ||
| 66 | |||
| 67 | public: | ||
| 68 | template <bool isRequest, bhttp::concepts::fields Fields> | ||
| 69 | explicit hmac_body_reader( | ||
| 70 | bhttp::header<isRequest, Fields>& h, | ||
| 71 | hmac_readable<typename Sub::value_type>& v) | ||
| 72 | : v_{util::not_null{&v}}, | ||
| 73 | subr_{h, v.get()} // we are not supposed to use v yet, but this just | ||
| 74 | // computes an address, so it should be fine | ||
| 75 | { | ||
| 76 | } | ||
| 77 | |||
| 78 | ~hmac_body_reader() | ||
| 79 | { | ||
| 80 | ::EVP_MAC_CTX_free(ctx_); | ||
| 81 | ::EVP_MAC_free(mac_); | ||
| 82 | } | ||
| 83 | |||
| 84 | // TODO: move to impl. unit. | ||
| 85 | auto init(boost::optional<std::uint64_t> n, beast::error_code& ec) noexcept | ||
| 86 | -> void | ||
| 87 | { | ||
| 88 | // https://docs.openssl.org/master/man3/EVP_MAC/#examples | ||
| 89 | mac_ = ::EVP_MAC_fetch(nullptr, "HMAC", nullptr); | ||
| 90 | if (!mac_) | ||
| 91 | { | ||
| 92 | ec_ = ec = make_error_code(std::errc::not_enough_memory); | ||
| 93 | return; | ||
| 94 | } | ||
| 95 | |||
| 96 | ctx_ = ::EVP_MAC_CTX_new(mac_); | ||
| 97 | if (!ctx_) | ||
| 98 | { | ||
| 99 | ec_ = ec = make_error_code(std::errc::not_enough_memory); | ||
| 100 | return; | ||
| 101 | } | ||
| 102 | |||
| 103 | char sha256[] = "SHA256"; | ||
| 104 | ::OSSL_PARAM const params[] = { | ||
| 105 | OSSL_PARAM_utf8_string("digest", sha256, sizeof(sha256) - 1), | ||
| 106 | OSSL_PARAM_END | ||
| 107 | }; | ||
| 108 | if (!::EVP_MAC_init( | ||
| 109 | ctx_, reinterpret_cast<unsigned char const*>(v_->key_.data()), | ||
| 110 | v_->key_.size(), params)) | ||
| 111 | { | ||
| 112 | ec_ = ec = beast::error_code{ | ||
| 113 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() | ||
| 114 | }; | ||
| 115 | return; | ||
| 116 | } | ||
| 117 | |||
| 118 | subr_.init(n, ec); | ||
| 119 | } | ||
| 120 | |||
| 121 | auto | ||
| 122 | put(beast::concepts::const_buffer_sequence auto b, | ||
| 123 | beast::error_code& ec) noexcept -> std::size_t | ||
| 124 | { | ||
| 125 | if ((ec = ec_)) | ||
| 126 | return 0uz; | ||
| 127 | |||
| 128 | auto const total_read = subr_.put(b, ec); | ||
| 129 | if (total_read > 0) | ||
| 130 | { | ||
| 131 | auto remaining = total_read; | ||
| 132 | for (auto const buf : beast::buffers_range(b)) | ||
| 133 | { | ||
| 134 | auto const to_hash_from_this_buf = std::min(remaining, buf.size()); | ||
| 135 | if (!::EVP_MAC_update( | ||
| 136 | ctx_, static_cast<unsigned char const*>(buf.data()), | ||
| 137 | to_hash_from_this_buf)) | ||
| 138 | { | ||
| 139 | ec_ = ec = beast::error_code{ | ||
| 140 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() | ||
| 141 | }; | ||
| 142 | return total_read; | ||
| 143 | } | ||
| 144 | remaining -= to_hash_from_this_buf; | ||
| 145 | } | ||
| 146 | } | ||
| 147 | return total_read; | ||
| 148 | } | ||
| 149 | |||
| 150 | auto finish(beast::error_code& ec) noexcept | ||
| 151 | { | ||
| 152 | auto got_mac_len = 0uz; | ||
| 153 | auto got_mac = std::array<std::uint8_t, 32>{}; | ||
| 154 | if (!::EVP_MAC_final(ctx_, got_mac.data(), &got_mac_len, got_mac.size())) | ||
| 155 | { | ||
| 156 | ec = beast::error_code{ | ||
| 157 | static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() | ||
| 158 | }; | ||
| 159 | return; | ||
| 160 | } | ||
| 161 | assert(got_mac_len == got_mac.size()); | ||
| 162 | v_->mac_ = got_mac; | ||
| 163 | subr_.finish(ec); | ||
| 164 | } | ||
| 165 | }; | ||
| 166 | |||
| 167 | template <bhttp::concepts::body Sub> | ||
| 168 | struct hmac_body | ||
| 169 | { | ||
| 170 | using value_type = hmac_readable<typename Sub::value_type>; | ||
| 171 | }; | ||
| 172 | |||
| 173 | template <bhttp::concepts::body Sub> | ||
| 174 | requires bhttp::concepts::body_reader<Sub> | ||
| 175 | struct hmac_body<Sub> | ||
| 176 | { | ||
| 177 | using value_type = hmac_readable<typename Sub::value_type>; | ||
| 178 | |||
| 179 | using reader = hmac_body_reader<Sub>; | ||
| 180 | }; | ||
| 181 | |||
| 182 | struct json_body | ||
| 183 | { | ||
| 184 | using value_type = json::value; | ||
| 185 | |||
| 186 | class reader | ||
| 187 | { | ||
| 188 | json::stream_parser p_; | ||
| 189 | util::not_null<value_type*> v_; | ||
| 190 | |||
| 191 | public: | ||
| 192 | template <bool isRequest, bhttp::concepts::fields Fields> | ||
| 193 | explicit reader(bhttp::header<isRequest, Fields>&, value_type& v) | ||
| 194 | : v_{util::not_null{&v}} | ||
| 195 | { | ||
| 196 | } | ||
| 197 | |||
| 198 | // TODO: move to impl. unit. | ||
| 199 | auto | ||
| 200 | init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept | ||
| 201 | -> void | ||
| 202 | { | ||
| 203 | p_.reset(); | ||
| 204 | ec = {}; | ||
| 205 | } | ||
| 206 | |||
| 207 | auto | ||
| 208 | put(beast::concepts::const_buffer_sequence auto b, | ||
| 209 | beast::error_code& ec) noexcept -> std::size_t | ||
| 210 | { | ||
| 211 | ec = {}; | ||
| 212 | |||
| 213 | auto wrote = 0uz; | ||
| 214 | for (auto const buf : beast::buffers_range(b)) | ||
| 215 | { | ||
| 216 | p_.write(static_cast<char const*>(buf.data()), buf.size(), ec); | ||
| 217 | wrote += buf.size(); | ||
| 218 | if (ec) | ||
| 219 | break; | ||
| 220 | } | ||
| 221 | return wrote; | ||
| 222 | } | ||
| 223 | |||
| 224 | auto finish(beast::error_code& ec) noexcept | ||
| 225 | { | ||
| 226 | p_.finish(ec); | ||
| 227 | if (ec) | ||
| 228 | return; | ||
| 229 | *v_ = p_.release(); | ||
| 230 | } | ||
| 231 | }; | ||
| 232 | }; | ||
| 233 | |||
| 234 | static_assert(bhttp::concepts::body<hmac_body<json_body>>); | ||
| 235 | static_assert(bhttp::concepts::body_reader<hmac_body<json_body>>); | ||
| 236 | |||
| 237 | } // namespace routemon::rwgps::webhook | ||
diff --git a/server/src/sqlite3.cpp b/server/src/sqlite3.cpp index 3e0d64a..243cf41 100644 --- a/server/src/sqlite3.cpp +++ b/server/src/sqlite3.cpp | |||
| @@ -8,23 +8,28 @@ import :sqlite3; | |||
| 8 | 8 | ||
| 9 | namespace routemon::sqlite3 { | 9 | namespace routemon::sqlite3 { |
| 10 | 10 | ||
| 11 | mutex_guard::mutex_guard(::sqlite3_mutex* mut) noexcept : mut_{mut} {} | 11 | mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc} |
| 12 | |||
| 13 | mutex_guard::~mutex_guard() { ::sqlite3_mutex_leave(mut_); } | ||
| 14 | |||
| 15 | auto do_guarded(::sqlite3_mutex* mut, std::invocable<mutex_guard const&> auto f) | ||
| 16 | -> decltype(f(std::declval<mutex_guard const&>())) | ||
| 17 | { | 12 | { |
| 18 | return f(mutex_guard{mut}); | 13 | ::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_)); |
| 19 | } | 14 | } |
| 20 | 15 | ||
| 21 | auto do_guarded(::sqlite3* dbc, std::invocable<mutex_guard const&> auto f) | 16 | mutex_guard::~mutex_guard() |
| 22 | -> decltype(f(std::declval<mutex_guard const&>())) | ||
| 23 | { | 17 | { |
| 24 | return do_guarded(::sqlite3_db_mutex(dbc), f); | 18 | if (dbc_) |
| 19 | ::sqlite3_mutex_leave(::sqlite3_db_mutex(dbc_)); | ||
| 25 | } | 20 | } |
| 26 | 21 | ||
| 27 | error::error(mutex_guard const&, int code, ::sqlite3* dbc) | 22 | // auto do_guarded(::sqlite3* dbc, std::invocable<mutex_guard const&> auto f, |
| 23 | // std::optional<mutex_guard const&> malready_locked = std::nullopt) | ||
| 24 | // -> decltype(f(std::declval<mutex_guard const&>())) | ||
| 25 | // { | ||
| 26 | // if (auto const mguard = malready_locked) | ||
| 27 | // return f(*mguard); | ||
| 28 | // else | ||
| 29 | // return f(mutex_guard{dbc}); | ||
| 30 | // } | ||
| 31 | |||
| 32 | error::error(int code, ::sqlite3* dbc) | ||
| 28 | : code_{code}, message_{::sqlite3_errmsg(dbc)} | 33 | : code_{code}, message_{::sqlite3_errmsg(dbc)} |
| 29 | { | 34 | { |
| 30 | } | 35 | } |
| @@ -38,161 +43,234 @@ error::error(int code) : code_{code}, message_{::sqlite3_errstr(code)} {} | |||
| 38 | 43 | ||
| 39 | [[nodiscard]] auto error::code() const noexcept -> int { return code_; } | 44 | [[nodiscard]] auto error::code() const noexcept -> int { return code_; } |
| 40 | 45 | ||
| 41 | statement::statement(::sqlite3_stmt* stmt) : stmt_{stmt} {} | 46 | locked_statement::locked_statement( |
| 42 | statement::statement(statement&& s) noexcept | 47 | ::sqlite3_stmt* stmt, std::shared_ptr<mutex_guard> dbc_locked) |
| 48 | : stmt_{stmt}, guard_{std::move(dbc_locked)} | ||
| 49 | { | ||
| 50 | if (!guard_) | ||
| 51 | throw std::invalid_argument{"mutex guard may not be null"}; | ||
| 52 | if (!guard_->for_db(::sqlite3_db_handle(stmt_))) | ||
| 53 | throw std::invalid_argument{ | ||
| 54 | "provided mutex guard does not apply to statement's database" | ||
| 55 | }; | ||
| 56 | } | ||
| 57 | locked_statement::locked_statement(locked_statement&& rhs) noexcept | ||
| 58 | : stmt_{std::exchange(rhs.stmt_, nullptr)}, guard_{std::move(rhs.guard_)} | ||
| 43 | { | 59 | { |
| 44 | stmt_ = s.stmt_; | ||
| 45 | s.stmt_ = nullptr; | ||
| 46 | } | 60 | } |
| 47 | statement::~statement() { ::sqlite3_finalize(stmt_); } | 61 | locked_statement::~locked_statement() |
| 48 | auto statement::get() -> ::sqlite3_stmt* { return stmt_; } | 62 | { |
| 63 | if (stmt_) | ||
| 64 | ::sqlite3_finalize(stmt_); | ||
| 65 | } | ||
| 49 | 66 | ||
| 50 | row_reader::row_reader(statement stmt) : stmt_{std::move(stmt)} {} | 67 | row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {} |
| 51 | 68 | ||
| 52 | auto row_reader::is_null(int col) -> bool | 69 | auto row_reader::is_null(int col) -> bool |
| 53 | { | 70 | { |
| 54 | return ::sqlite3_column_type(stmt_.get(), col) == SQLITE_NULL; | 71 | return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL; |
| 55 | } | 72 | } |
| 56 | 73 | ||
| 57 | auto row_reader::ncols() -> std::size_t | 74 | auto row_reader::ncols() -> std::size_t |
| 58 | { | 75 | { |
| 59 | auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.get())); | 76 | auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.stmt_)); |
| 60 | if (!mncols.has_value()) | 77 | if (!mncols.has_value()) |
| 61 | throw std::logic_error{"got unexpected negative amount of columns"}; | 78 | throw std::logic_error{"got unexpected negative amount of columns"}; |
| 62 | return *mncols; | 79 | return *mncols; |
| 63 | } | 80 | } |
| 64 | 81 | ||
| 65 | auto row_reader::scan(int col, std::string& s) -> void | 82 | auto row_reader::scan_col(int col, std::string& s) -> void |
| 66 | { | 83 | { |
| 67 | if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_TEXT) | 84 | if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_TEXT) |
| 68 | throw std::invalid_argument{"invalid type for scan"}; | 85 | throw std::invalid_argument{"invalid type for scan"}; |
| 69 | unsigned char const* chs = ::sqlite3_column_text(stmt_.get(), col); | 86 | unsigned char const* chs = ::sqlite3_column_text(stmt_.stmt_, col); |
| 70 | auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.get(), col)); | 87 | auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.stmt_, col)); |
| 71 | if (!size.has_value()) | 88 | if (!size.has_value()) |
| 72 | throw std::logic_error{"unexpected negative amount of bytes in column"}; | 89 | throw std::logic_error{"unexpected negative amount of bytes in column"}; |
| 73 | s = std::string{reinterpret_cast<char const*>(chs), *size}; | 90 | s = std::string{reinterpret_cast<char const*>(chs), *size}; |
| 74 | } | 91 | } |
| 75 | 92 | ||
| 76 | auto row_reader::scan(int col, double& v) -> void | 93 | auto row_reader::scan_col(int col, double& v) -> void |
| 77 | { | 94 | { |
| 78 | if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_FLOAT) | 95 | if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_FLOAT) |
| 79 | throw std::invalid_argument{"invalid type for scan"}; | 96 | throw std::invalid_argument{"invalid type for scan"}; |
| 80 | v = ::sqlite3_column_double(stmt_.get(), col); | 97 | v = ::sqlite3_column_double(stmt_.stmt_, col); |
| 81 | } | 98 | } |
| 82 | 99 | ||
| 83 | auto row_reader::scan(int col, std::int64_t& v) -> void | 100 | auto row_reader::scan_col(int col, std::int64_t& v) -> void |
| 84 | { | 101 | { |
| 85 | if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_INTEGER) | 102 | if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_INTEGER) |
| 86 | throw std::invalid_argument{"invalid type for scan"}; | 103 | throw std::invalid_argument{"invalid type for scan"}; |
| 87 | v = ::sqlite3_column_int64(stmt_.get(), col); | 104 | v = ::sqlite3_column_int64(stmt_.stmt_, col); |
| 88 | } | 105 | } |
| 89 | 106 | ||
| 90 | auto row_reader::next() -> bool | 107 | auto row_reader::next() -> bool |
| 91 | { | 108 | { |
| 92 | ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.get()); | 109 | ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.stmt_); |
| 93 | return do_guarded( | 110 | auto const s = ::sqlite3_step(stmt_.stmt_); |
| 94 | dbc, | 111 | if (s == SQLITE_ROW) |
| 95 | [&](auto const& guard) -> bool | 112 | return true; |
| 96 | { | 113 | if (s == SQLITE_DONE) |
| 97 | auto const s = ::sqlite3_step(stmt_.get()); | 114 | return false; |
| 98 | if (s == SQLITE_ROW) | 115 | throw error{s, dbc}; |
| 99 | return true; | ||
| 100 | if (s == SQLITE_DONE) | ||
| 101 | return false; | ||
| 102 | throw error{guard, s, dbc}; | ||
| 103 | }); | ||
| 104 | } | 116 | } |
| 105 | 117 | ||
| 106 | binder::binder(statement& stmt) : stmt_{stmt} {} | 118 | statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {} |
| 107 | 119 | ||
| 108 | auto binder::text(std::string const& param_name, std::string_view str) -> void | 120 | auto statement::param_idx(util::zstring_view name) -> int |
| 109 | { | 121 | { |
| 110 | int const i = ::sqlite3_bind_parameter_index(stmt_.get(), param_name.c_str()); | 122 | int const i = ::sqlite3_bind_parameter_index(stmt_.stmt_, name.c_str()); |
| 111 | if (i == 0) | 123 | if (i == 0) |
| 112 | throw std::invalid_argument{std::format( | 124 | throw std::invalid_argument{std::format( |
| 113 | "bind: no parameter with name {} found", param_name)}; | 125 | "bind: no parameter with name {} found", name)}; |
| 126 | return i; | ||
| 127 | } | ||
| 128 | |||
| 129 | auto statement::bind_null(util::zstring_view param_name) -> statement& | ||
| 130 | { | ||
| 131 | if (auto s = ::sqlite3_bind_null(stmt_.stmt_, param_idx(param_name)); | ||
| 132 | s != SQLITE_OK) | ||
| 133 | throw error{s}; | ||
| 134 | return *this; | ||
| 135 | } | ||
| 136 | |||
| 137 | auto statement::bind(util::zstring_view param_name, std::string_view str) | ||
| 138 | -> statement& | ||
| 139 | { | ||
| 114 | auto str_size = util::int_from_size(str.size()); | 140 | auto str_size = util::int_from_size(str.size()); |
| 115 | if (!str_size.has_value()) | 141 | if (!str_size.has_value()) |
| 116 | throw std::invalid_argument{"bind: provided text is too long"}; | 142 | throw std::invalid_argument{"bind: provided text is too long"}; |
| 117 | if (auto s = ::sqlite3_bind_text( | 143 | if (auto s = ::sqlite3_bind_text( |
| 118 | stmt_.get(), i, str.data(), *str_size, SQLITE_TRANSIENT); | 144 | stmt_.stmt_, param_idx(param_name), str.data(), *str_size, |
| 145 | SQLITE_TRANSIENT); | ||
| 119 | s != SQLITE_OK) | 146 | s != SQLITE_OK) |
| 120 | { | ||
| 121 | throw error{s}; | 147 | throw error{s}; |
| 122 | } | 148 | return *this; |
| 123 | } | 149 | } |
| 124 | 150 | ||
| 125 | auto binder::noop(binder&) -> void {} | 151 | auto statement::bind(util::zstring_view param_name, std::int64_t x) |
| 152 | -> statement& | ||
| 153 | { | ||
| 154 | if (auto s = ::sqlite3_bind_int64(stmt_.stmt_, param_idx(param_name), x); | ||
| 155 | s != SQLITE_OK) | ||
| 156 | throw error{s}; | ||
| 157 | return *this; | ||
| 158 | } | ||
| 159 | |||
| 160 | auto statement::bind( | ||
| 161 | util::zstring_view param_name, std::optional<std::string_view> mstr) | ||
| 162 | -> statement& | ||
| 163 | { | ||
| 164 | if (mstr) | ||
| 165 | return bind(param_name, *mstr); | ||
| 166 | else | ||
| 167 | return bind_null(param_name); | ||
| 168 | } | ||
| 169 | |||
| 170 | auto statement::bind( | ||
| 171 | util::zstring_view param_name, std::optional<std::int64_t> mx) -> statement& | ||
| 172 | { | ||
| 173 | if (mx) | ||
| 174 | return bind(param_name, *mx); | ||
| 175 | else | ||
| 176 | return bind_null(param_name); | ||
| 177 | } | ||
| 126 | 178 | ||
| 127 | connection::connection(::sqlite3* dbc) | 179 | auto statement::into_reader() && -> row_reader |
| 128 | : dbc_{dbc}, mut_{::sqlite3_db_mutex(dbc)} | ||
| 129 | { | 180 | { |
| 181 | return row_reader{std::move(stmt_)}; | ||
| 130 | } | 182 | } |
| 131 | 183 | ||
| 132 | connection::connection(connection const&) = delete; | 184 | auto noop_binder(statement&) -> void {} |
| 185 | |||
| 186 | connection::connection(::sqlite3* dbc) : dbc_{dbc} {} | ||
| 187 | |||
| 133 | connection::connection(connection&& c) noexcept | 188 | connection::connection(connection&& c) noexcept |
| 134 | { | 189 | { |
| 135 | dbc_ = c.dbc_; | 190 | dbc_ = c.dbc_; |
| 136 | mut_ = c.mut_; | ||
| 137 | c.dbc_ = nullptr; | 191 | c.dbc_ = nullptr; |
| 138 | c.mut_ = nullptr; | ||
| 139 | } | 192 | } |
| 140 | 193 | ||
| 141 | auto connection::query( | 194 | auto prepare( |
| 142 | std::string const& sql, std::function<void(binder&)> const& bf) | 195 | ::sqlite3* dbc, util::zstring_view& sql, |
| 143 | -> row_reader | 196 | std::shared_ptr<mutex_guard> guard = nullptr) -> std::optional<statement> |
| 144 | { | 197 | { |
| 198 | if (guard && !guard->for_db(dbc)) | ||
| 199 | throw std::invalid_argument{ | ||
| 200 | "provided mutex guard does not apply to provided database" | ||
| 201 | }; | ||
| 202 | if (!guard) | ||
| 203 | guard.reset(new mutex_guard{dbc}); | ||
| 145 | ::sqlite3_stmt* pstmt = nullptr; | 204 | ::sqlite3_stmt* pstmt = nullptr; |
| 146 | char const* sql_tail = nullptr; | 205 | char const* sql_tail = nullptr; |
| 147 | auto sql_size = util::int_from_size(sql.size()); | 206 | auto sql_len = util::int_from_size(sql.length()); |
| 148 | if (!sql_size.has_value() || *sql_size >= std::numeric_limits<int>::max() - 1) | 207 | if (!sql_len.has_value() || *sql_len >= std::numeric_limits<int>::max() - 1) |
| 149 | throw std::invalid_argument{"provided input text too large"}; | 208 | throw std::invalid_argument{"provided input text too large"}; |
| 150 | do_guarded( | 209 | if (auto s = ::sqlite3_prepare_v2( |
| 151 | mut_, | 210 | dbc, sql.c_str(), *sql_len + 1, &pstmt, &sql_tail); |
| 152 | [&](auto const& guard) -> void | 211 | s != SQLITE_OK) |
| 153 | { | 212 | { |
| 154 | if (auto s = ::sqlite3_prepare_v2( | 213 | if (pstmt) |
| 155 | dbc_, sql.data(), *sql_size + 1, &pstmt, &sql_tail); | 214 | { |
| 156 | s != SQLITE_OK) | 215 | // Use contract_assert when having a compiler with |
| 157 | { | 216 | // contracts available |
| 158 | if (pstmt != nullptr) | 217 | ::sqlite3_finalize(pstmt); |
| 159 | { | 218 | throw std::logic_error{ |
| 160 | // Use contract_assert when having a compiler with | 219 | "expected stmt to be null after failed preparation" |
| 161 | // contracts available | 220 | }; |
| 162 | ::sqlite3_finalize(pstmt); | 221 | } |
| 163 | throw std::logic_error{ | 222 | throw error{s, dbc}; |
| 164 | "expected stmt to be null after failed preparation" | 223 | } |
| 165 | }; | ||
| 166 | } | ||
| 167 | throw error{guard, s, dbc_}; | ||
| 168 | } | ||
| 169 | }); | ||
| 170 | if (!pstmt) | 224 | if (!pstmt) |
| 225 | return std::nullopt; | ||
| 226 | if (sql_tail < sql || sql_tail > sql + sql.length()) | ||
| 227 | throw std::runtime_error{"expected SQL tail to be non-null"}; | ||
| 228 | sql = util::zstring_view{ | ||
| 229 | sql_tail, sql.length() - static_cast<std::size_t>(sql_tail - sql.c_str()) | ||
| 230 | }; | ||
| 231 | return statement{locked_statement{pstmt, std::move(guard)}}; | ||
| 232 | } | ||
| 233 | |||
| 234 | auto do_query( | ||
| 235 | ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf, | ||
| 236 | std::shared_ptr<mutex_guard> guard = nullptr) -> row_reader | ||
| 237 | { | ||
| 238 | auto mstmt = prepare(dbc, sql, std::move(guard)); | ||
| 239 | if (!mstmt) | ||
| 171 | throw std::invalid_argument{"provided input text contains no SQL"}; | 240 | throw std::invalid_argument{"provided input text contains no SQL"}; |
| 172 | auto stmt = statement{pstmt}; | 241 | if (sql.length() > 0) // what remains after querying |
| 173 | if (sql_tail && std::strlen(sql_tail) > 0) | ||
| 174 | throw std::invalid_argument{ | 242 | throw std::invalid_argument{ |
| 175 | "provided input text contains more than one SQL statement" | 243 | "provided input text contains more than one SQL statement" |
| 176 | }; | 244 | }; |
| 177 | auto b = binder{stmt}; | 245 | bf(*mstmt); |
| 178 | bf(b); | 246 | return std::move(*mstmt).into_reader(); |
| 179 | return row_reader{std::move(stmt)}; | ||
| 180 | } | 247 | } |
| 181 | 248 | ||
| 182 | auto connection::exec( | 249 | auto do_exec( |
| 183 | std::string const& sql, std::function<void(binder&)> const& bf) -> void | 250 | ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf, |
| 251 | std::shared_ptr<mutex_guard> guard = nullptr) -> void | ||
| 184 | { | 252 | { |
| 185 | auto reader = query(sql, bf); | 253 | auto reader = do_query(dbc, sql, bf, std::move(guard)); |
| 186 | while (reader.next()) | 254 | while (reader.next()) |
| 187 | ; | 255 | ; |
| 188 | } | 256 | } |
| 189 | 257 | ||
| 258 | auto connection::query(util::zstring_view sql, bindfn const& bf) -> row_reader | ||
| 259 | { | ||
| 260 | return do_query(dbc_, sql, bf); | ||
| 261 | } | ||
| 262 | |||
| 263 | auto connection::exec(util::zstring_view sql, bindfn const& bf) -> void | ||
| 264 | { | ||
| 265 | return do_exec(dbc_, sql, bf); | ||
| 266 | } | ||
| 267 | |||
| 190 | connection::~connection() | 268 | connection::~connection() |
| 191 | { | 269 | { |
| 192 | std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); | 270 | std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); |
| 193 | } | 271 | } |
| 194 | 272 | ||
| 195 | auto open(std::string const& filename) -> connection | 273 | auto open(util::zstring_view filename) -> connection |
| 196 | { | 274 | { |
| 197 | ::sqlite3* dbc = nullptr; | 275 | ::sqlite3* dbc = nullptr; |
| 198 | auto s = ::sqlite3_open_v2( | 276 | auto s = ::sqlite3_open_v2( |
| @@ -204,15 +282,71 @@ auto open(std::string const& filename) -> connection | |||
| 204 | { | 282 | { |
| 205 | if (dbc) | 283 | if (dbc) |
| 206 | { | 284 | { |
| 207 | do_guarded( | 285 | throw error{s, dbc}; |
| 208 | dbc, [&](auto const& guard) -> void { throw error{guard, s, dbc}; }); | ||
| 209 | } | 286 | } |
| 210 | else | 287 | else |
| 211 | { | 288 | { |
| 212 | throw error{s}; | 289 | throw error{s}; |
| 213 | } | 290 | } |
| 214 | } | 291 | } |
| 215 | return connection{dbc}; | 292 | auto w = connection{dbc}; |
| 293 | w.exec("PRAGMA foreign_keys = ON"); | ||
| 294 | return w; | ||
| 295 | } | ||
| 296 | |||
| 297 | tx::tx(connection& dbc) | ||
| 298 | : dbc_{util::not_null{&dbc}}, | ||
| 299 | guard_{std::make_shared<mutex_guard>(dbc_->dbc_)} | ||
| 300 | { | ||
| 301 | exec("BEGIN"); | ||
| 302 | } | ||
| 303 | |||
| 304 | [[nodiscard]] auto tx::query(util::zstring_view sql, bindfn const& bf) | ||
| 305 | -> row_reader | ||
| 306 | { | ||
| 307 | try | ||
| 308 | { | ||
| 309 | return do_query(dbc_->dbc_, sql, bf, guard_); | ||
| 310 | } | ||
| 311 | catch (std::exception const&) | ||
| 312 | { | ||
| 313 | commit_ = false; | ||
| 314 | throw; | ||
| 315 | } | ||
| 316 | } | ||
| 317 | |||
| 318 | auto tx::exec(util::zstring_view sql, bindfn const& bf) -> void | ||
| 319 | { | ||
| 320 | try | ||
| 321 | { | ||
| 322 | do_exec(dbc_->dbc_, sql, bf, guard_); | ||
| 323 | } | ||
| 324 | catch (std::exception const&) | ||
| 325 | { | ||
| 326 | commit_ = false; | ||
| 327 | throw; | ||
| 328 | } | ||
| 329 | } | ||
| 330 | |||
| 331 | auto tx::exec_first(util::zstring_view& sql) -> void | ||
| 332 | { | ||
| 333 | try | ||
| 334 | { | ||
| 335 | auto mstmt = prepare(dbc_->dbc_, sql, guard_); | ||
| 336 | if (!mstmt) | ||
| 337 | { | ||
| 338 | sql = util::zstring_view{sql.c_str() + sql.length(), 0}; | ||
| 339 | return; | ||
| 340 | } | ||
| 341 | auto reader = std::move(*mstmt).into_reader(); | ||
| 342 | while (reader.next()) | ||
| 343 | ; | ||
| 344 | } | ||
| 345 | catch (std::exception const&) | ||
| 346 | { | ||
| 347 | commit_ = false; | ||
| 348 | throw; | ||
| 349 | } | ||
| 216 | } | 350 | } |
| 217 | 351 | ||
| 218 | } // namespace routemon::sqlite3 | 352 | } // namespace routemon::sqlite3 |
diff --git a/server/src/sqlite3.cppm b/server/src/sqlite3.cppm index b771c49..3348b0b 100644 --- a/server/src/sqlite3.cppm +++ b/server/src/sqlite3.cppm | |||
| @@ -28,18 +28,17 @@ concept scannable = scannable_prim<T> || optional_of<T, scannable_prim>; | |||
| 28 | 28 | ||
| 29 | class mutex_guard | 29 | class mutex_guard |
| 30 | { | 30 | { |
| 31 | explicit mutex_guard(::sqlite3_mutex* mut) noexcept; | 31 | ::sqlite3* dbc_; |
| 32 | |||
| 33 | friend auto | ||
| 34 | do_guarded(::sqlite3_mutex* mut, std::invocable<mutex_guard const&> auto f) | ||
| 35 | -> decltype(f(std::declval<mutex_guard const&>())); | ||
| 36 | 32 | ||
| 37 | public: | 33 | public: |
| 34 | explicit mutex_guard(::sqlite3* dbc) noexcept; | ||
| 38 | mutex_guard(mutex_guard const&) = delete; | 35 | mutex_guard(mutex_guard const&) = delete; |
| 36 | mutex_guard(mutex_guard&& rhs) = delete; | ||
| 37 | auto operator=(mutex_guard const&) -> mutex_guard& = delete; | ||
| 38 | auto operator=(mutex_guard&& rhs) -> mutex_guard& = delete; | ||
| 39 | ~mutex_guard(); | 39 | ~mutex_guard(); |
| 40 | 40 | ||
| 41 | private: | 41 | auto for_db(::sqlite3 const* dbc) const -> bool { return dbc_ == dbc; } |
| 42 | ::sqlite3_mutex* mut_; | ||
| 43 | }; | 42 | }; |
| 44 | 43 | ||
| 45 | class error : public std::exception | 44 | class error : public std::exception |
| @@ -48,40 +47,68 @@ class error : public std::exception | |||
| 48 | std::string message_; | 47 | std::string message_; |
| 49 | 48 | ||
| 50 | public: | 49 | public: |
| 51 | explicit error(mutex_guard const&, int code, ::sqlite3* dbc); | 50 | explicit error(int code, ::sqlite3* dbc); |
| 52 | explicit error(int code); | 51 | explicit error(int code); |
| 53 | 52 | ||
| 54 | [[nodiscard]] auto what() const noexcept -> char const* override; | 53 | [[nodiscard]] auto what() const noexcept -> char const* override; |
| 55 | [[nodiscard]] auto code() const noexcept -> int; | 54 | [[nodiscard]] auto code() const noexcept -> int; |
| 56 | }; | 55 | }; |
| 57 | 56 | ||
| 58 | class statement | 57 | class statement; |
| 58 | class row_reader; | ||
| 59 | |||
| 60 | // TODO: make consumable and mark release_guard only callable when unconsumed? | ||
| 61 | // Same might have to for release_guard in row_reader. | ||
| 62 | class locked_statement | ||
| 59 | { | 63 | { |
| 60 | ::sqlite3_stmt* stmt_; | 64 | ::sqlite3_stmt* stmt_; |
| 65 | std::shared_ptr<mutex_guard> guard_; | ||
| 66 | |||
| 67 | friend class statement; | ||
| 68 | friend class row_reader; | ||
| 69 | |||
| 70 | public: | ||
| 71 | explicit locked_statement( | ||
| 72 | ::sqlite3_stmt* stmt, std::shared_ptr<mutex_guard> dbc_locked); | ||
| 73 | locked_statement(locked_statement const&) = delete; | ||
| 74 | locked_statement(locked_statement&& s) noexcept; | ||
| 75 | ~locked_statement(); | ||
| 76 | }; | ||
| 77 | |||
| 78 | class statement | ||
| 79 | { | ||
| 80 | locked_statement stmt_; | ||
| 81 | |||
| 82 | auto param_idx(util::zstring_view name) -> int; | ||
| 83 | auto bind_null(util::zstring_view param_name) -> statement&; | ||
| 61 | 84 | ||
| 62 | public: | 85 | public: |
| 63 | explicit statement(::sqlite3_stmt* stmt); | 86 | explicit statement(locked_statement&& stmt); |
| 64 | statement(statement const&) = delete; | 87 | |
| 65 | statement(statement&& s) noexcept; | 88 | auto bind(util::zstring_view param_name, std::string_view str) -> statement&; |
| 66 | ~statement(); | 89 | auto bind(util::zstring_view param_name, std::int64_t x) -> statement&; |
| 67 | auto get() -> ::sqlite3_stmt*; | 90 | auto bind(util::zstring_view param_name, std::optional<std::string_view> str) |
| 91 | -> statement&; | ||
| 92 | auto bind(util::zstring_view param_name, std::optional<std::int64_t> x) | ||
| 93 | -> statement&; | ||
| 94 | auto into_reader() && -> row_reader; | ||
| 68 | }; | 95 | }; |
| 69 | 96 | ||
| 70 | class row_reader | 97 | class row_reader |
| 71 | { | 98 | { |
| 72 | statement stmt_; | 99 | locked_statement stmt_; |
| 73 | 100 | ||
| 74 | explicit row_reader(statement stmt); | 101 | friend class statement; |
| 75 | 102 | ||
| 76 | friend class connection; | 103 | explicit row_reader(locked_statement&& stmt); |
| 77 | 104 | ||
| 78 | auto is_null(int col) -> bool; | 105 | auto is_null(int col) -> bool; |
| 79 | auto ncols() -> std::size_t; | 106 | auto ncols() -> std::size_t; |
| 80 | 107 | ||
| 81 | auto scan(int col, std::string& s) -> void; | 108 | auto scan_col(int col, std::string& s) -> void; |
| 82 | auto scan(int col, double& v) -> void; | 109 | auto scan_col(int col, double& v) -> void; |
| 83 | auto scan(int col, std::int64_t& v) -> void; | 110 | auto scan_col(int col, std::int64_t& v) -> void; |
| 84 | auto scan(int col, optional_of<scannable> auto& v) -> void | 111 | auto scan_col(int col, optional_of<scannable_prim> auto& v) -> void |
| 85 | { | 112 | { |
| 86 | if (is_null(col)) | 113 | if (is_null(col)) |
| 87 | { | 114 | { |
| @@ -90,7 +117,7 @@ class row_reader | |||
| 90 | else | 117 | else |
| 91 | { | 118 | { |
| 92 | typename std::remove_cvref_t<decltype(v)>::value_type tmp; | 119 | typename std::remove_cvref_t<decltype(v)>::value_type tmp; |
| 93 | scan(col, tmp); | 120 | scan_col(col, tmp); |
| 94 | v = std::move(tmp); | 121 | v = std::move(tmp); |
| 95 | } | 122 | } |
| 96 | } | 123 | } |
| @@ -105,10 +132,19 @@ public: | |||
| 105 | "more scanning arguments provided than columns in result set" | 132 | "more scanning arguments provided than columns in result set" |
| 106 | }; | 133 | }; |
| 107 | auto col = 0; | 134 | auto col = 0; |
| 108 | (..., scan(col++, args)); | 135 | (..., scan_col(col++, args)); |
| 109 | } | 136 | } |
| 110 | 137 | ||
| 111 | auto scan_single(scannable auto&... args) -> void | 138 | template <scannable... args> |
| 139 | auto scan() -> std::tuple<args...> | ||
| 140 | { | ||
| 141 | std::tuple<args...> res; | ||
| 142 | auto& [... elems] = res; | ||
| 143 | scan(elems...); | ||
| 144 | return res; | ||
| 145 | } | ||
| 146 | |||
| 147 | auto scan_row_max1(scannable auto&... args) -> void | ||
| 112 | { | 148 | { |
| 113 | if (!next()) | 149 | if (!next()) |
| 114 | throw std::logic_error{"no row in result set"}; | 150 | throw std::logic_error{"no row in result set"}; |
| @@ -118,46 +154,69 @@ public: | |||
| 118 | throw std::logic_error{"more than one row in result set"}; | 154 | throw std::logic_error{"more than one row in result set"}; |
| 119 | } | 155 | } |
| 120 | } | 156 | } |
| 121 | }; | ||
| 122 | |||
| 123 | class binder | ||
| 124 | { | ||
| 125 | statement& stmt_; | ||
| 126 | 157 | ||
| 127 | explicit binder(statement& stmt); | 158 | template <scannable... args> |
| 159 | auto scan_row_max1() -> std::tuple<args...> | ||
| 160 | { | ||
| 161 | std::tuple<args...> res; | ||
| 162 | auto& [... elems] = res; | ||
| 163 | scan_row_max1(elems...); | ||
| 164 | return res; | ||
| 165 | } | ||
| 166 | }; | ||
| 128 | 167 | ||
| 129 | friend class connection; | 168 | // TODO: consider making this a concept instead. |
| 169 | using bindfn = std::function<auto(statement&)->void>; | ||
| 130 | 170 | ||
| 131 | public: | 171 | auto noop_binder(statement&) -> void; |
| 132 | auto text(std::string const& param_name, std::string_view str) -> void; | ||
| 133 | |||
| 134 | static auto noop(binder&) -> void; | ||
| 135 | }; | ||
| 136 | 172 | ||
| 137 | export class connection | 173 | export class connection |
| 138 | { | 174 | { |
| 139 | ::sqlite3* dbc_; | 175 | ::sqlite3* dbc_; |
| 140 | ::sqlite3_mutex* mut_; | ||
| 141 | 176 | ||
| 142 | explicit connection(::sqlite3* dbc); | 177 | explicit connection(::sqlite3* dbc); |
| 143 | 178 | ||
| 144 | friend auto open(std::string const& filename) -> connection; | 179 | friend auto open(util::zstring_view filename) -> connection; |
| 180 | friend class tx; | ||
| 145 | 181 | ||
| 146 | public: | 182 | public: |
| 147 | connection(connection const&) = delete; | 183 | connection(connection const&) = delete; |
| 148 | connection(connection&& c) noexcept; | 184 | connection(connection&& c) noexcept; |
| 149 | 185 | ||
| 150 | [[nodiscard]] auto query( | 186 | [[nodiscard]] auto |
| 151 | std::string const& sql, | 187 | query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; |
| 152 | std::function<void(binder&)> const& bf = binder::noop) -> row_reader; | ||
| 153 | 188 | ||
| 154 | auto exec( | 189 | auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; |
| 155 | std::string const& sql, | ||
| 156 | std::function<void(binder&)> const& bf = binder::noop) -> void; | ||
| 157 | 190 | ||
| 158 | ~connection(); | 191 | ~connection(); |
| 159 | }; | 192 | }; |
| 160 | 193 | ||
| 161 | export auto open(std::string const& filename) -> connection; | 194 | // TODO: define behavior when user issues queries that affect the |
| 195 | // transaction itself. | ||
| 196 | export class tx | ||
| 197 | { | ||
| 198 | bool commit_ = true; | ||
| 199 | util::not_null<connection*> dbc_; | ||
| 200 | std::shared_ptr<mutex_guard> guard_; | ||
| 201 | |||
| 202 | public: | ||
| 203 | explicit tx(connection& dbc); | ||
| 204 | |||
| 205 | ~tx() | ||
| 206 | { | ||
| 207 | if (commit_) | ||
| 208 | exec("COMMIT"); | ||
| 209 | else | ||
| 210 | exec("ROLLBACK"); | ||
| 211 | } | ||
| 212 | |||
| 213 | [[nodiscard]] auto | ||
| 214 | query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; | ||
| 215 | |||
| 216 | auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; | ||
| 217 | auto exec_first(util::zstring_view& sql) -> void; | ||
| 218 | }; | ||
| 219 | |||
| 220 | export auto open(util::zstring_view filename) -> connection; | ||
| 162 | 221 | ||
| 163 | } // namespace routemon::sqlite3 | 222 | } // namespace routemon::sqlite3 |
diff --git a/server/src/srv.cpp b/server/src/srv.cpp index 5de0fc5..287f838 100644 --- a/server/src/srv.cpp +++ b/server/src/srv.cpp | |||
| @@ -13,11 +13,14 @@ module; | |||
| 13 | 13 | ||
| 14 | #include <expat.h> | 14 | #include <expat.h> |
| 15 | 15 | ||
| 16 | #include <openssl/crypto.h> | ||
| 17 | |||
| 16 | module routemon:srv$impl; | 18 | module routemon:srv$impl; |
| 17 | 19 | ||
| 18 | import std; | 20 | import std; |
| 19 | import :gpx; | 21 | import :gpx; |
| 20 | import :srv; | 22 | import :srv; |
| 23 | import :rwgps.webhook; | ||
| 21 | 24 | ||
| 22 | namespace beast = boost::beast; | 25 | namespace beast = boost::beast; |
| 23 | namespace chrono = std::chrono; | 26 | namespace chrono = std::chrono; |
| @@ -330,9 +333,10 @@ struct raw_deflate_body | |||
| 330 | }; | 333 | }; |
| 331 | }; | 334 | }; |
| 332 | 335 | ||
| 333 | auto parse_timestamp(std::string_view in) -> std::optional<time::timestamp> | 336 | auto parse_timestamp_mins(std::string_view in) |
| 337 | -> std::optional<time::timestamp<std::chrono::minutes>> | ||
| 334 | { | 338 | { |
| 335 | auto res = time::timestamp{}; | 339 | auto res = time::timestamp<std::chrono::minutes>{}; |
| 336 | auto is = std::istringstream{in}; | 340 | auto is = std::istringstream{in}; |
| 337 | is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res); | 341 | is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res); |
| 338 | return is.fail() ? std::nullopt : std::make_optional(res); | 342 | return is.fail() ? std::nullopt : std::make_optional(res); |
| @@ -344,13 +348,13 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) | |||
| 344 | auto l = | 348 | auto l = |
| 345 | l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string()); | 349 | l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string()); |
| 346 | 350 | ||
| 347 | auto cp_begin = time::timestamp{}; | 351 | auto cp_begin = time::timestamp<std::chrono::minutes>{}; |
| 348 | auto cp_end = time::timestamp{}; | 352 | auto cp_end = time::timestamp<std::chrono::minutes>{}; |
| 349 | 353 | ||
| 350 | auto const params = ctx.target.params(); | 354 | auto const params = ctx.target.params(); |
| 351 | if (auto it = params.find("cpbegin"); it != params.end()) | 355 | if (auto it = params.find("cpbegin"); it != params.end()) |
| 352 | { | 356 | { |
| 353 | auto mts = parse_timestamp((*it).value); | 357 | auto mts = parse_timestamp_mins((*it).value); |
| 354 | if (!mts) | 358 | if (!mts) |
| 355 | { | 359 | { |
| 356 | auto tpl = problem::tpl{ | 360 | auto tpl = problem::tpl{ |
| @@ -390,7 +394,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) | |||
| 390 | } | 394 | } |
| 391 | if (auto it = params.find("cpend"); it != params.end()) | 395 | if (auto it = params.find("cpend"); it != params.end()) |
| 392 | { | 396 | { |
| 393 | auto mts = parse_timestamp((*it).value); | 397 | auto mts = parse_timestamp_mins((*it).value); |
| 394 | if (!mts) | 398 | if (!mts) |
| 395 | { | 399 | { |
| 396 | auto tpl = problem::tpl{ | 400 | auto tpl = problem::tpl{ |
| @@ -442,7 +446,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) | |||
| 442 | "Begin of check period must be before end of check period")), | 446 | "Begin of check period must be before end of check period")), |
| 443 | http::keep_alive{false}); | 447 | http::keep_alive{false}); |
| 444 | } | 448 | } |
| 445 | auto cp = time::period{cp_begin, cp_end}; | 449 | auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end}; |
| 446 | 450 | ||
| 447 | auto gpx_file = gpx::file{}; | 451 | auto gpx_file = gpx::file{}; |
| 448 | try | 452 | try |
| @@ -487,7 +491,8 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) | |||
| 487 | // TODO: catch handler exceptions and return 500 when raised? | 491 | // TODO: catch handler exceptions and return 500 when raised? |
| 488 | // (keep-alive depends on whether whole request was read) | 492 | // (keep-alive depends on whether whole request was read) |
| 489 | auto mres = inner_.process_gpx( | 493 | auto mres = inner_.process_gpx( |
| 490 | ctx.trace_id, std::move(gpx_file), time::period_seq{cp}); | 494 | ctx.trace_id, std::move(gpx_file), |
| 495 | time::period_seq<std::chrono::minutes>{cp}); | ||
| 491 | if (!mres) | 496 | if (!mres) |
| 492 | { | 497 | { |
| 493 | auto tpl = problem::tpl{ | 498 | auto tpl = problem::tpl{ |
| @@ -521,8 +526,109 @@ auto handler::handle_sysinfo(l0_ctx ctx, http::readable_request r) | |||
| 521 | co_return rsp; | 526 | co_return rsp; |
| 522 | } | 527 | } |
| 523 | 528 | ||
| 524 | handler::handler(log::logger const& l, api::handler&& inner) | 529 | auto decode_hexnib(char c) -> std::optional<std::uint8_t> |
| 525 | : l_{l.sub("handler")}, inner_{std::move(inner)} | 530 | { |
| 531 | if ('a' <= c && c <= 'f') | ||
| 532 | return c - 'a' + 10; | ||
| 533 | if ('A' <= c && c <= 'F') | ||
| 534 | return c - 'A' + 10; | ||
| 535 | if ('0' <= c && c <= '9') | ||
| 536 | return c - '0'; | ||
| 537 | return std::nullopt; | ||
| 538 | } | ||
| 539 | |||
| 540 | auto parse_timestamp_secs(std::string_view in) | ||
| 541 | -> std::optional<time::timestamp<std::chrono::seconds>> | ||
| 542 | { | ||
| 543 | auto res = time::timestamp<std::chrono::seconds>{}; | ||
| 544 | auto is = std::istringstream{in}; | ||
| 545 | is >> std::chrono::parse("%FT%TZ", res); | ||
| 546 | return is.fail() ? std::nullopt : std::make_optional(res); | ||
| 547 | } | ||
| 548 | |||
| 549 | auto handler::handle_rwgps_webhook(l0_ctx ctx, http::readable_request r) | ||
| 550 | -> net::awaitable<http::presponse> | ||
| 551 | { | ||
| 552 | if (r.p->get()[bhttp::field::content_type] != "application/json") | ||
| 553 | { | ||
| 554 | // TODO: 415 Unsupported Media Type | ||
| 555 | // (respond Accept-Post: application/json) | ||
| 556 | throw std::runtime_error{"unhandled: unsupported media type provided"}; | ||
| 557 | } | ||
| 558 | |||
| 559 | auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]); | ||
| 560 | if (!mrwgps_ts) | ||
| 561 | { | ||
| 562 | // TODO: 400 Bad Request | ||
| 563 | throw std::runtime_error{ | ||
| 564 | "failed to parse ISO 8601 date/time in x-rwgps-datetime header" | ||
| 565 | }; | ||
| 566 | } | ||
| 567 | |||
| 568 | // TODO: better to instead copy the expected API key to a buffer of | ||
| 569 | // (at least) the size of the input API key and to compare those two | ||
| 570 | // buffers? Then this operation should be Ω/Θ(API key provided in | ||
| 571 | // request) | ||
| 572 | auto req_api_key = r.p->get()["x-rwgps-api-key"]; | ||
| 573 | auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X'); | ||
| 574 | std::memcpy( | ||
| 575 | req_api_key_copy.data(), req_api_key.data(), | ||
| 576 | std::min(req_api_key.size(), rwgps_creds_->api_key().size())); | ||
| 577 | |||
| 578 | if (CRYPTO_memcmp( | ||
| 579 | req_api_key_copy.data(), rwgps_creds_->api_key().data(), | ||
| 580 | rwgps_creds_->api_key().size())) | ||
| 581 | { | ||
| 582 | // TODO: Unauthorized | ||
| 583 | // TODO: constant-time comparison | ||
| 584 | throw std::runtime_error{"unhandled: mismatching API key provided"}; | ||
| 585 | } | ||
| 586 | |||
| 587 | auto rwgps_sig = r.p->get()["x-rwgps-signature"]; | ||
| 588 | auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{}; | ||
| 589 | |||
| 590 | if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size()) | ||
| 591 | { | ||
| 592 | // TODO: Bad request | ||
| 593 | throw std::runtime_error{"unhandled: bad signature provided"}; | ||
| 594 | } | ||
| 595 | |||
| 596 | for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate) | ||
| 597 | { | ||
| 598 | auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]); | ||
| 599 | auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]); | ||
| 600 | if (!mhi || !mlo) | ||
| 601 | { | ||
| 602 | throw std::runtime_error{"TODO: INVALID SIGNATURE"}; | ||
| 603 | } | ||
| 604 | static_assert(std::same_as<decltype(b), std::uint8_t&>); | ||
| 605 | b = static_cast<std::uint8_t>((*mhi << 4) | *mlo); | ||
| 606 | } | ||
| 607 | |||
| 608 | auto req = co_await http:: | ||
| 609 | read_request<rwgps::webhook::hmac_body<rwgps::webhook::json_body>>( | ||
| 610 | ctx, std::move(r), rwgps_creds_->api_secret()); | ||
| 611 | |||
| 612 | if (req.body().mac() != rwgps_sig_decoded) | ||
| 613 | { | ||
| 614 | throw std::runtime_error{"unhandled: incorrect signature provided"}; | ||
| 615 | } | ||
| 616 | |||
| 617 | // TODO: handle conversion failure gracefully | ||
| 618 | inner_.rwgps_webhook( | ||
| 619 | *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get())); | ||
| 620 | |||
| 621 | auto rsp = http::make_rsp<bhttp::empty_body>( | ||
| 622 | bhttp::status::ok, http::keep_alive{true}); | ||
| 623 | rsp.prepare_payload(); | ||
| 624 | co_return rsp; | ||
| 625 | } | ||
| 626 | |||
| 627 | handler::handler( | ||
| 628 | log::logger const& l, api::handler&& inner, | ||
| 629 | std::shared_ptr<rwgps::credentials> rwgps_creds) | ||
| 630 | : l_{l.sub("handler")}, inner_{std::move(inner)}, | ||
| 631 | rwgps_creds_{std::move(rwgps_creds)} | ||
| 526 | { | 632 | { |
| 527 | } | 633 | } |
| 528 | 634 | ||
| @@ -536,11 +642,15 @@ auto handler::make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>> | |||
| 536 | .post = handler(&handler::handle_process_gpx), | 642 | .post = handler(&handler::handle_process_gpx), |
| 537 | }} | 643 | }} |
| 538 | .no_subtrees()}, | 644 | .no_subtrees()}, |
| 539 | {"sysinfo", http::dtree<l0_ctx>{ | 645 | {"sysinfo", http::dtree<l0_ctx>{{ |
| 540 | { | 646 | .get = handler(&handler::handle_sysinfo), |
| 541 | .get = handler(&handler::handle_sysinfo), | 647 | }} |
| 542 | } | 648 | .no_subtrees()}, |
| 543 | }.no_subtrees()}, | 649 | {"webhook", http::dtree<l0_ctx>{}.named_subtrees({ |
| 650 | {"rwgps", http::dtree<l0_ctx>{ | ||
| 651 | {.post = handler(&handler::handle_rwgps_webhook)} | ||
| 652 | }.no_subtrees()}, | ||
| 653 | })}, | ||
| 544 | }); | 654 | }); |
| 545 | } | 655 | } |
| 546 | 656 | ||
| @@ -557,8 +667,9 @@ auto server::make_global_middleware(config::http_server const& cfg) | |||
| 557 | 667 | ||
| 558 | server::server( | 668 | server::server( |
| 559 | log::logger const& l, config::http_server const& cfg, | 669 | log::logger const& l, config::http_server const& cfg, |
| 560 | locale::selector&& lsel, api::handler&& inner) | 670 | std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel, |
| 561 | : handler_{l, std::move(inner)}, | 671 | api::handler&& inner) |
| 672 | : handler_{l, std::move(inner), std::move(rwgps_creds)}, | ||
| 562 | srv_{ | 673 | srv_{ |
| 563 | l, | 674 | l, |
| 564 | http::router{ | 675 | http::router{ |
diff --git a/server/src/srv.cppm b/server/src/srv.cppm index b06dc3b..2a389c9 100644 --- a/server/src/srv.cppm +++ b/server/src/srv.cppm | |||
| @@ -6,6 +6,7 @@ export module routemon:srv; | |||
| 6 | 6 | ||
| 7 | import :api; | 7 | import :api; |
| 8 | import :http.server; | 8 | import :http.server; |
| 9 | import :rwgps; | ||
| 9 | 10 | ||
| 10 | namespace routemon::srv { | 11 | namespace routemon::srv { |
| 11 | 12 | ||
| @@ -13,6 +14,7 @@ class handler | |||
| 13 | { | 14 | { |
| 14 | log::logger l_; | 15 | log::logger l_; |
| 15 | api::handler inner_; | 16 | api::handler inner_; |
| 17 | std::shared_ptr<rwgps::credentials> rwgps_creds_; | ||
| 16 | 18 | ||
| 17 | public: | 19 | public: |
| 18 | using outer_ctx = http::base_ctx; | 20 | using outer_ctx = http::base_ctx; |
| @@ -25,8 +27,13 @@ private: | |||
| 25 | auto handle_sysinfo(l0_ctx ctx, http::readable_request r) | 27 | auto handle_sysinfo(l0_ctx ctx, http::readable_request r) |
| 26 | -> net::awaitable<http::presponse>; | 28 | -> net::awaitable<http::presponse>; |
| 27 | 29 | ||
| 30 | auto handle_rwgps_webhook(l0_ctx ctx, http::readable_request r) | ||
| 31 | -> net::awaitable<http::presponse>; | ||
| 32 | |||
| 28 | public: | 33 | public: |
| 29 | handler(log::logger const& l, api::handler&& inner); | 34 | handler( |
| 35 | log::logger const& l, api::handler&& inner, | ||
| 36 | std::shared_ptr<rwgps::credentials> rwgps_creds); | ||
| 30 | 37 | ||
| 31 | auto make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>>; | 38 | auto make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>>; |
| 32 | }; | 39 | }; |
| @@ -42,7 +49,8 @@ export class server | |||
| 42 | public: | 49 | public: |
| 43 | server( | 50 | server( |
| 44 | log::logger const& l, config::http_server const& cfg, | 51 | log::logger const& l, config::http_server const& cfg, |
| 45 | locale::selector&& lsel, api::handler&& inner); | 52 | std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel, |
| 53 | api::handler&& inner); | ||
| 46 | 54 | ||
| 47 | auto spawn(net::io_context& ioc) -> void; | 55 | auto spawn(net::io_context& ioc) -> void; |
| 48 | }; | 56 | }; |
diff --git a/server/src/time.cpp b/server/src/time.cpp index 8f99dd2..9849761 100644 --- a/server/src/time.cpp +++ b/server/src/time.cpp | |||
| @@ -2,172 +2,11 @@ module routemon:time$impl; | |||
| 2 | 2 | ||
| 3 | import :time; | 3 | import :time; |
| 4 | 4 | ||
| 5 | export namespace routemon::time { | 5 | namespace routemon::time { |
| 6 | 6 | ||
| 7 | using timestamp = std::chrono::time_point<std::chrono::utc_clock>; | 7 | auto iso8601_secs(timestamp<std::chrono::seconds> ts) -> std::string |
| 8 | |||
| 9 | period::period(timestamp start, timestamp end) : start_{start}, end_{end} | ||
| 10 | { | ||
| 11 | if (start >= end) | ||
| 12 | { | ||
| 13 | throw std::invalid_argument("period: start should be before end"); | ||
| 14 | } | ||
| 15 | } | ||
| 16 | |||
| 17 | auto period::intersect(period other) const -> std::optional<period> | ||
| 18 | { | ||
| 19 | auto const new_start = start_ < other.start() ? other.start() : start_; | ||
| 20 | auto const new_end = other.end() < end_ ? other.end() : end_; | ||
| 21 | return new_start < new_end ? std::make_optional(period{new_start, new_end}) | ||
| 22 | : std::nullopt; | ||
| 23 | } | ||
| 24 | |||
| 25 | auto period::except(period other) const | ||
| 26 | -> std::pair<std::optional<period>, std::optional<period>> | ||
| 27 | { | ||
| 28 | auto const before_start = start_; | ||
| 29 | auto const before_end = other.start(); | ||
| 30 | auto const after_start = end_; | ||
| 31 | auto const after_end = other.end(); | ||
| 32 | std::optional<period> before, after; | ||
| 33 | if (before_start < before_end) | ||
| 34 | before = period{before_start, before_end}; | ||
| 35 | if (after_start < after_end) | ||
| 36 | after = period{after_end, after_start}; | ||
| 37 | return std::make_pair(before, after); | ||
| 38 | } | ||
| 39 | |||
| 40 | auto period::start() const -> timestamp { return start_; } | ||
| 41 | auto period::end() const -> timestamp { return end_; } | ||
| 42 | |||
| 43 | period_seq::period_seq(std::vector<period> periods) | ||
| 44 | : periods_{std::move(periods)} | ||
| 45 | { | ||
| 46 | for (auto i = 0uz; i < periods_.size(); i++) | ||
| 47 | { | ||
| 48 | if (i + 1 < periods_.size()) | ||
| 49 | { | ||
| 50 | if (periods_[i].end() >= periods_[i + 1].start()) | ||
| 51 | { | ||
| 52 | throw std::logic_error{"period_seq: vector provided to private " | ||
| 53 | "constructor not ordered properly"}; | ||
| 54 | } | ||
| 55 | } | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | period_seq::period_seq(period singleton) : periods_{singleton} {} | ||
| 60 | |||
| 61 | auto period_seq::intersect(period_seq const& other) const -> period_seq | ||
| 62 | { | ||
| 63 | auto it1 = periods_.begin(); | ||
| 64 | auto end1 = periods_.end(); | ||
| 65 | auto it2 = other.periods_.begin(); | ||
| 66 | auto end2 = other.periods_.end(); | ||
| 67 | |||
| 68 | auto res = std::vector<period>{}; | ||
| 69 | while (it1 != end1 && it2 != end2) | ||
| 70 | { | ||
| 71 | auto overlap = it1->intersect(*it2); | ||
| 72 | if (overlap) | ||
| 73 | { | ||
| 74 | res.push_back(*overlap); | ||
| 75 | if (it1->end() < it2->end()) | ||
| 76 | { | ||
| 77 | it1++; | ||
| 78 | } | ||
| 79 | else | ||
| 80 | { | ||
| 81 | it2++; | ||
| 82 | } | ||
| 83 | } | ||
| 84 | else | ||
| 85 | { | ||
| 86 | if (it1->end() < it2->start()) | ||
| 87 | { | ||
| 88 | it1++; | ||
| 89 | } | ||
| 90 | else | ||
| 91 | { | ||
| 92 | it2++; | ||
| 93 | } | ||
| 94 | } | ||
| 95 | } | ||
| 96 | |||
| 97 | return period_seq{res}; | ||
| 98 | } | ||
| 99 | |||
| 100 | auto period_seq::except(period_seq const& other) const -> period_seq | ||
| 101 | { | ||
| 102 | // This code was pretty tricky to write, I wouldn't be surprised if it | ||
| 103 | // has some bugs in it. | ||
| 104 | |||
| 105 | auto it1 = periods_.begin(); | ||
| 106 | auto end1 = periods_.end(); | ||
| 107 | auto it2 = other.periods_.begin(); | ||
| 108 | auto end2 = other.periods_.end(); | ||
| 109 | |||
| 110 | auto res = std::vector<period>{}; | ||
| 111 | if (it1 == end1) | ||
| 112 | return period_seq{res}; | ||
| 113 | if (it2 == end2) | ||
| 114 | return period_seq{periods_}; | ||
| 115 | auto period1 = period{*it1++}; | ||
| 116 | |||
| 117 | while (it1 != end1 && it2 != end2) | ||
| 118 | { | ||
| 119 | if (period1.end() <= it2->start()) | ||
| 120 | { | ||
| 121 | res.push_back(period1); | ||
| 122 | period1 = *it1++; | ||
| 123 | } | ||
| 124 | else if (it2->end() <= period1.start()) | ||
| 125 | { | ||
| 126 | it2++; | ||
| 127 | } | ||
| 128 | else /* period1.begin() < it2->end() && it2->begin() < | ||
| 129 | period1.end() */ | ||
| 130 | { | ||
| 131 | auto const [mbefore, mafter] = period1.except(*it2); | ||
| 132 | if (mbefore) | ||
| 133 | res.push_back(*mbefore); | ||
| 134 | if (mafter) | ||
| 135 | { | ||
| 136 | period1 = *mafter; | ||
| 137 | } | ||
| 138 | else | ||
| 139 | { | ||
| 140 | period1 = *it1++; | ||
| 141 | } | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | return period_seq{res}; | ||
| 146 | } | ||
| 147 | |||
| 148 | auto period_seq::periods() const -> std::vector<period> const& | ||
| 149 | { | ||
| 150 | return periods_; | ||
| 151 | } | ||
| 152 | |||
| 153 | auto operator<<(std::ostream& os, period const& p) -> std::ostream& | ||
| 154 | { | ||
| 155 | return os << "[" << p.start() << ", " << p.end() << ")"; | ||
| 156 | } | ||
| 157 | |||
| 158 | auto operator<<(std::ostream& os, period_seq const& ps) -> std::ostream& | ||
| 159 | { | 8 | { |
| 160 | os << "{"; | 9 | return std::format("{0:%F}T{0:%T}Z", ts); |
| 161 | auto it = ps.periods().begin(); | ||
| 162 | while (it != ps.periods().end()) | ||
| 163 | { | ||
| 164 | os << " " << *it; | ||
| 165 | if (++it != ps.periods().end()) | ||
| 166 | { | ||
| 167 | os << ","; | ||
| 168 | } | ||
| 169 | } | ||
| 170 | return os << " }"; | ||
| 171 | } | 10 | } |
| 172 | 11 | ||
| 173 | } // namespace routemon::time | 12 | } // namespace routemon::time |
diff --git a/server/src/time.cppm b/server/src/time.cppm index 0007839..32df737 100644 --- a/server/src/time.cppm +++ b/server/src/time.cppm | |||
| @@ -4,28 +4,33 @@ import std; | |||
| 4 | 4 | ||
| 5 | export namespace routemon::time { | 5 | export namespace routemon::time { |
| 6 | 6 | ||
| 7 | using timestamp = std::chrono::time_point<std::chrono::utc_clock>; | 7 | template <class Duration = std::chrono::utc_clock::duration> |
| 8 | using timestamp = std::chrono::time_point<std::chrono::utc_clock, Duration>; | ||
| 8 | 9 | ||
| 10 | auto iso8601_secs(timestamp<std::chrono::seconds> ts) -> std::string; | ||
| 11 | |||
| 12 | template <class Duration> | ||
| 9 | class period | 13 | class period |
| 10 | { | 14 | { |
| 11 | // Assuming [start, end). Unfortunately the DATEX II model is not | 15 | // Assuming [start, end). Unfortunately the DATEX II model is not |
| 12 | // clear about this. | 16 | // clear about this. |
| 13 | timestamp start_; | 17 | timestamp<Duration> start_; |
| 14 | timestamp end_; | 18 | timestamp<Duration> end_; |
| 15 | 19 | ||
| 16 | public: | 20 | public: |
| 17 | explicit period(timestamp start, timestamp end); | 21 | explicit period(timestamp<Duration> start, timestamp<Duration> end); |
| 18 | 22 | ||
| 19 | [[nodiscard]] auto intersect(period other) const -> std::optional<period>; | 23 | [[nodiscard]] auto intersect(period other) const -> std::optional<period>; |
| 20 | [[nodiscard]] auto except(period other) const | 24 | [[nodiscard]] auto except(period other) const |
| 21 | -> std::pair<std::optional<period>, std::optional<period>>; | 25 | -> std::pair<std::optional<period>, std::optional<period>>; |
| 22 | [[nodiscard]] auto start() const -> timestamp; | 26 | [[nodiscard]] auto start() const -> timestamp<Duration>; |
| 23 | [[nodiscard]] auto end() const -> timestamp; | 27 | [[nodiscard]] auto end() const -> timestamp<Duration>; |
| 24 | }; | 28 | }; |
| 25 | 29 | ||
| 30 | template <class Duration> | ||
| 26 | class period_seq | 31 | class period_seq |
| 27 | { | 32 | { |
| 28 | std::vector<period> periods_; | 33 | std::vector<period<Duration>> periods_; |
| 29 | 34 | ||
| 30 | // The way lt and ge are ordered makes a difference for how the sorting | 35 | // The way lt and ge are ordered makes a difference for how the sorting |
| 31 | // (insertion based on lower_bound) works. Do not carelessly reorder this. | 36 | // (insertion based on lower_bound) works. Do not carelessly reorder this. |
| @@ -37,11 +42,11 @@ class period_seq | |||
| 37 | 42 | ||
| 38 | // O(n log n) | 43 | // O(n log n) |
| 39 | template <std::input_iterator I, std::sentinel_for<I> S> | 44 | template <std::input_iterator I, std::sentinel_for<I> S> |
| 40 | requires std::same_as<std::iter_value_t<I>, period> | 45 | requires std::same_as<std::iter_value_t<I>, period<Duration>> |
| 41 | static auto consolidate(I begin, S end) -> std::vector<period> | 46 | static auto consolidate(I begin, S end) -> std::vector<period<Duration>> |
| 42 | { | 47 | { |
| 43 | auto periods = std::vector<period>{}; | 48 | auto periods = std::vector<period<Duration>>{}; |
| 44 | auto preds = std::vector<std::pair<timestamp, lt_ge>>{}; | 49 | auto preds = std::vector<std::pair<timestamp<Duration>, lt_ge>>{}; |
| 45 | 50 | ||
| 46 | for (auto it = begin; it != end; it++) | 51 | for (auto it = begin; it != end; it++) |
| 47 | { | 52 | { |
| @@ -89,23 +94,221 @@ class period_seq | |||
| 89 | return periods; | 94 | return periods; |
| 90 | } | 95 | } |
| 91 | 96 | ||
| 92 | explicit period_seq(std::vector<period> periods); | 97 | explicit period_seq(std::vector<period<Duration>> periods); |
| 93 | 98 | ||
| 94 | public: | 99 | public: |
| 95 | template <std::input_iterator I, std::sentinel_for<I> S> | 100 | template <std::input_iterator I, std::sentinel_for<I> S> |
| 96 | requires std::same_as<std::iter_value_t<I>, period> | 101 | requires std::same_as<std::iter_value_t<I>, period<Duration>> |
| 97 | explicit period_seq(I begin, S end) : periods_{consolidate(begin, end)} | 102 | explicit period_seq(I begin, S end) : periods_{consolidate(begin, end)} |
| 98 | { | 103 | { |
| 99 | } | 104 | } |
| 100 | 105 | ||
| 101 | explicit period_seq(period singleton); | 106 | explicit period_seq(period<Duration> singleton); |
| 102 | 107 | ||
| 103 | [[nodiscard]] auto intersect(period_seq const& other) const -> period_seq; | 108 | [[nodiscard]] auto intersect(period_seq const& other) const -> period_seq; |
| 104 | [[nodiscard]] auto except(period_seq const& other) const -> period_seq; | 109 | [[nodiscard]] auto except(period_seq const& other) const -> period_seq; |
| 105 | [[nodiscard]] auto periods() const -> std::vector<period> const&; | 110 | [[nodiscard]] auto periods() const -> std::vector<period<Duration>> const&; |
| 106 | }; | 111 | }; |
| 107 | 112 | ||
| 108 | auto operator<<(std::ostream& os, period const& p) -> std::ostream&; | 113 | template <class Duration> |
| 109 | auto operator<<(std::ostream& os, period_seq const& ps) -> std::ostream&; | 114 | auto operator<<(std::ostream& os, period<Duration> const& p) -> std::ostream&; |
| 115 | |||
| 116 | template <class Duration> | ||
| 117 | auto operator<<(std::ostream& os, period_seq<Duration> const& ps) | ||
| 118 | -> std::ostream&; | ||
| 119 | |||
| 120 | } // namespace routemon::time | ||
| 121 | |||
| 122 | namespace routemon::time { | ||
| 123 | |||
| 124 | template <class Duration> | ||
| 125 | period<Duration>::period(timestamp<Duration> start, timestamp<Duration> end) | ||
| 126 | : start_{start}, end_{end} | ||
| 127 | { | ||
| 128 | if (start >= end) | ||
| 129 | { | ||
| 130 | throw std::invalid_argument{"period: start should be before end"}; | ||
| 131 | } | ||
| 132 | } | ||
| 133 | |||
| 134 | template <class Duration> | ||
| 135 | auto period<Duration>::intersect(period other) const -> std::optional<period> | ||
| 136 | { | ||
| 137 | auto const new_start = start_ < other.start() ? other.start() : start_; | ||
| 138 | auto const new_end = other.end() < end_ ? other.end() : end_; | ||
| 139 | return new_start < new_end ? std::make_optional(period{new_start, new_end}) | ||
| 140 | : std::nullopt; | ||
| 141 | } | ||
| 142 | |||
| 143 | template <class Duration> | ||
| 144 | auto period<Duration>::except(period other) const | ||
| 145 | -> std::pair<std::optional<period>, std::optional<period>> | ||
| 146 | { | ||
| 147 | auto const before_start = start_; | ||
| 148 | auto const before_end = other.start(); | ||
| 149 | auto const after_start = end_; | ||
| 150 | auto const after_end = other.end(); | ||
| 151 | std::optional<period> before, after; | ||
| 152 | if (before_start < before_end) | ||
| 153 | before = period{before_start, before_end}; | ||
| 154 | if (after_start < after_end) | ||
| 155 | after = period{after_end, after_start}; | ||
| 156 | return std::make_pair(before, after); | ||
| 157 | } | ||
| 158 | |||
| 159 | template <class Duration> | ||
| 160 | auto period<Duration>::start() const -> timestamp<Duration> | ||
| 161 | { | ||
| 162 | return start_; | ||
| 163 | } | ||
| 164 | |||
| 165 | template <class Duration> | ||
| 166 | auto period<Duration>::end() const -> timestamp<Duration> | ||
| 167 | { | ||
| 168 | return end_; | ||
| 169 | } | ||
| 170 | |||
| 171 | template <class Duration> | ||
| 172 | period_seq<Duration>::period_seq(std::vector<period<Duration>> periods) | ||
| 173 | : periods_{std::move(periods)} | ||
| 174 | { | ||
| 175 | for (auto i = 0uz; i < periods_.size(); i++) | ||
| 176 | { | ||
| 177 | if (i + 1 < periods_.size()) | ||
| 178 | { | ||
| 179 | if (periods_[i].end() >= periods_[i + 1].start()) | ||
| 180 | { | ||
| 181 | throw std::logic_error{"period_seq: vector provided to private " | ||
| 182 | "constructor not ordered properly"}; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | } | ||
| 186 | } | ||
| 187 | |||
| 188 | template <class Duration> | ||
| 189 | period_seq<Duration>::period_seq(period<Duration> singleton) | ||
| 190 | : periods_{singleton} | ||
| 191 | { | ||
| 192 | } | ||
| 193 | |||
| 194 | template <class Duration> | ||
| 195 | auto period_seq<Duration>::intersect(period_seq const& other) const | ||
| 196 | -> period_seq | ||
| 197 | { | ||
| 198 | auto it1 = periods_.begin(); | ||
| 199 | auto end1 = periods_.end(); | ||
| 200 | auto it2 = other.periods_.begin(); | ||
| 201 | auto end2 = other.periods_.end(); | ||
| 202 | |||
| 203 | auto res = std::vector<period<Duration>>{}; | ||
| 204 | while (it1 != end1 && it2 != end2) | ||
| 205 | { | ||
| 206 | auto overlap = it1->intersect(*it2); | ||
| 207 | if (overlap) | ||
| 208 | { | ||
| 209 | res.push_back(*overlap); | ||
| 210 | if (it1->end() < it2->end()) | ||
| 211 | { | ||
| 212 | it1++; | ||
| 213 | } | ||
| 214 | else | ||
| 215 | { | ||
| 216 | it2++; | ||
| 217 | } | ||
| 218 | } | ||
| 219 | else | ||
| 220 | { | ||
| 221 | if (it1->end() < it2->start()) | ||
| 222 | { | ||
| 223 | it1++; | ||
| 224 | } | ||
| 225 | else | ||
| 226 | { | ||
| 227 | it2++; | ||
| 228 | } | ||
| 229 | } | ||
| 230 | } | ||
| 231 | |||
| 232 | return period_seq{res}; | ||
| 233 | } | ||
| 234 | |||
| 235 | template <class Duration> | ||
| 236 | auto period_seq<Duration>::except(period_seq const& other) const -> period_seq | ||
| 237 | { | ||
| 238 | // This code was pretty tricky to write, I wouldn't be surprised if it | ||
| 239 | // has some bugs in it. | ||
| 240 | |||
| 241 | auto it1 = periods_.begin(); | ||
| 242 | auto end1 = periods_.end(); | ||
| 243 | auto it2 = other.periods_.begin(); | ||
| 244 | auto end2 = other.periods_.end(); | ||
| 245 | |||
| 246 | auto res = std::vector<period<Duration>>{}; | ||
| 247 | if (it1 == end1) | ||
| 248 | return period_seq{res}; | ||
| 249 | if (it2 == end2) | ||
| 250 | return period_seq{periods_}; | ||
| 251 | auto period1 = period<Duration>{*it1++}; | ||
| 252 | |||
| 253 | while (it1 != end1 && it2 != end2) | ||
| 254 | { | ||
| 255 | if (period1.end() <= it2->start()) | ||
| 256 | { | ||
| 257 | res.push_back(period1); | ||
| 258 | period1 = *it1++; | ||
| 259 | } | ||
| 260 | else if (it2->end() <= period1.start()) | ||
| 261 | { | ||
| 262 | it2++; | ||
| 263 | } | ||
| 264 | else /* period1.begin() < it2->end() && it2->begin() < | ||
| 265 | period1.end() */ | ||
| 266 | { | ||
| 267 | auto const [mbefore, mafter] = period1.except(*it2); | ||
| 268 | if (mbefore) | ||
| 269 | res.push_back(*mbefore); | ||
| 270 | if (mafter) | ||
| 271 | { | ||
| 272 | period1 = *mafter; | ||
| 273 | } | ||
| 274 | else | ||
| 275 | { | ||
| 276 | period1 = *it1++; | ||
| 277 | } | ||
| 278 | } | ||
| 279 | } | ||
| 280 | |||
| 281 | return period_seq{res}; | ||
| 282 | } | ||
| 283 | |||
| 284 | template <class Duration> | ||
| 285 | auto period_seq<Duration>::periods() const | ||
| 286 | -> std::vector<period<Duration>> const& | ||
| 287 | { | ||
| 288 | return periods_; | ||
| 289 | } | ||
| 290 | |||
| 291 | template <class Duration> | ||
| 292 | auto operator<<(std::ostream& os, period<Duration> const& p) -> std::ostream& | ||
| 293 | { | ||
| 294 | return os << "[" << p.start() << ", " << p.end() << ")"; | ||
| 295 | } | ||
| 296 | |||
| 297 | template <class Duration> | ||
| 298 | auto operator<<(std::ostream& os, period_seq<Duration> const& ps) | ||
| 299 | -> std::ostream& | ||
| 300 | { | ||
| 301 | os << "{"; | ||
| 302 | auto it = ps.periods().begin(); | ||
| 303 | while (it != ps.periods().end()) | ||
| 304 | { | ||
| 305 | os << " " << *it; | ||
| 306 | if (++it != ps.periods().end()) | ||
| 307 | { | ||
| 308 | os << ","; | ||
| 309 | } | ||
| 310 | } | ||
| 311 | return os << " }"; | ||
| 312 | } | ||
| 110 | 313 | ||
| 111 | } // namespace routemon::time | 314 | } // namespace routemon::time |
diff --git a/server/src/trace.cpp b/server/src/trace.cpp index f2935a9..cc51604 100644 --- a/server/src/trace.cpp +++ b/server/src/trace.cpp | |||
| @@ -1,9 +1,3 @@ | |||
| 1 | module; | ||
| 2 | |||
| 3 | // Might as well since we're using OpenSSL | ||
| 4 | #include <openssl/err.h> | ||
| 5 | #include <openssl/rand.h> | ||
| 6 | |||
| 7 | module routemon:trace$impl; | 1 | module routemon:trace$impl; |
| 8 | 2 | ||
| 9 | import :trace; | 3 | import :trace; |
diff --git a/server/src/util.cppm b/server/src/util.cppm index 2857fe5..986e350 100644 --- a/server/src/util.cppm +++ b/server/src/util.cppm | |||
| @@ -20,14 +20,9 @@ constexpr auto parse_double( | |||
| 20 | { | 20 | { |
| 21 | auto x = 0.0; | 21 | auto x = 0.0; |
| 22 | auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); | 22 | auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); |
| 23 | if (ec == std::errc{}) | 23 | if (ec != std::errc{}) |
| 24 | { | ||
| 25 | return x; | ||
| 26 | } | ||
| 27 | else | ||
| 28 | { | ||
| 29 | return std::nullopt; | 24 | return std::nullopt; |
| 30 | } | 25 | return x; |
| 31 | } | 26 | } |
| 32 | 27 | ||
| 33 | constexpr auto parse_float( | 28 | constexpr auto parse_float( |
| @@ -37,14 +32,20 @@ constexpr auto parse_float( | |||
| 37 | { | 32 | { |
| 38 | auto x = 0.0; | 33 | auto x = 0.0; |
| 39 | auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); | 34 | auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); |
| 40 | if (ec == std::errc{}) | 35 | if (ec != std::errc{}) |
| 41 | { | ||
| 42 | return x; | ||
| 43 | } | ||
| 44 | else | ||
| 45 | { | ||
| 46 | return std::nullopt; | 36 | return std::nullopt; |
| 47 | } | 37 | return x; |
| 38 | } | ||
| 39 | |||
| 40 | export template <std::integral T> | ||
| 41 | constexpr auto parse_int(std::string_view s, int base = 10) noexcept | ||
| 42 | -> std::optional<T> | ||
| 43 | { | ||
| 44 | auto x = T{}; | ||
| 45 | auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, base); | ||
| 46 | if (ec != std::errc{}) | ||
| 47 | return std::nullopt; | ||
| 48 | return x; | ||
| 48 | } | 49 | } |
| 49 | 50 | ||
| 50 | template <class T> | 51 | template <class T> |
| @@ -107,10 +108,14 @@ public: | |||
| 107 | { | 108 | { |
| 108 | } | 109 | } |
| 109 | 110 | ||
| 111 | constexpr zstring_view(std::string s) : zstring_view{s.c_str(), s.length()} {} | ||
| 112 | |||
| 110 | constexpr auto length() const -> std::size_t { return length_; } | 113 | constexpr auto length() const -> std::size_t { return length_; } |
| 111 | 114 | ||
| 112 | constexpr auto c_str() const -> char const* { return s_; } | 115 | constexpr auto c_str() const -> char const* { return s_; } |
| 113 | 116 | ||
| 117 | constexpr auto empty() const -> bool { return length() == 0; } | ||
| 118 | |||
| 114 | constexpr operator std::string_view() const | 119 | constexpr operator std::string_view() const |
| 115 | { | 120 | { |
| 116 | return std::string_view{s_, length_}; | 121 | return std::string_view{s_, length_}; |
| @@ -239,3 +244,26 @@ public: | |||
| 239 | explicit not_null(lazy_zstring_view s) -> not_null<lazy_zstring_view>; | 244 | explicit not_null(lazy_zstring_view s) -> not_null<lazy_zstring_view>; |
| 240 | 245 | ||
| 241 | } // namespace routemon::util | 246 | } // namespace routemon::util |
| 247 | |||
| 248 | template <> | ||
| 249 | struct std::formatter<routemon::util::zstring_view, char> | ||
| 250 | { | ||
| 251 | template <class ParseContext> | ||
| 252 | constexpr auto parse(ParseContext& ctx) -> ParseContext::iterator | ||
| 253 | { | ||
| 254 | auto it = ctx.begin(); | ||
| 255 | if (it != ctx.end() && *it != '}') | ||
| 256 | throw std::format_error{ | ||
| 257 | "unexpected formatting arguments for util::zstring_view" | ||
| 258 | }; | ||
| 259 | return it; | ||
| 260 | } | ||
| 261 | |||
| 262 | template <class FmtContext> | ||
| 263 | auto format(routemon::util::zstring_view s, FmtContext& ctx) const | ||
| 264 | -> FmtContext::iterator | ||
| 265 | { | ||
| 266 | return std::ranges::copy(std::string_view{s.c_str(), s.length()}, ctx.out()) | ||
| 267 | .out; | ||
| 268 | } | ||
| 269 | }; | ||
diff --git a/server/src/xml.cppm b/server/src/xml.cppm index ffaf159..2d186da 100644 --- a/server/src/xml.cppm +++ b/server/src/xml.cppm | |||
| @@ -250,8 +250,8 @@ public: | |||
| 250 | 250 | ||
| 251 | struct position | 251 | struct position |
| 252 | { | 252 | { |
| 253 | std::size_t line; | 253 | std::uint64_t line; |
| 254 | std::size_t col; | 254 | std::uint64_t col; |
| 255 | }; | 255 | }; |
| 256 | 256 | ||
| 257 | class executor | 257 | class executor |
| @@ -443,8 +443,8 @@ public: | |||
| 443 | [[nodiscard]] inline auto position() -> position | 443 | [[nodiscard]] inline auto position() -> position |
| 444 | { | 444 | { |
| 445 | return { | 445 | return { |
| 446 | .line = XML_GetCurrentLineNumber(p_), | 446 | .line = XML_GetCurrentLineNumber64(p_), |
| 447 | .col = XML_GetCurrentColumnNumber(p_), | 447 | .col = XML_GetCurrentColumnNumber64(p_), |
| 448 | }; | 448 | }; |
| 449 | } | 449 | } |
| 450 | 450 | ||