userver: userver/ugrpc/datetime_utils.hpp Source File
Loading...
Searching...
No Matches
datetime_utils.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file
4/// @brief Utilities for @c google::protobuf::Timestamp, @c google::type::Date, and @c google::protobuf::Duration types.
5
6#include <chrono>
7#include <cstdint>
8#include <ratio>
9#include <stdexcept>
10#include <type_traits>
11#include <version>
12
13#include <google/protobuf/duration.pb.h>
14#include <google/protobuf/timestamp.pb.h>
15#include <google/type/date.pb.h>
16
17#include <userver/formats/json_fwd.hpp>
18#include <userver/formats/parse/to.hpp>
19#include <userver/formats/serialize/to.hpp>
20#include <userver/utils/assert.hpp>
21#include <userver/utils/datetime/cpp_20_calendar.hpp>
22#include <userver/utils/datetime/date.hpp>
23
24USERVER_NAMESPACE_BEGIN
25
26namespace ugrpc {
27
28namespace impl {
29
30template <typename Duration, typename Exception>
31Duration ToChronoDuration(std::chrono::seconds seconds, std::chrono::nanoseconds nanos, const char* error_message) {
32 using Rep = typename Duration::rep;
33 if constexpr (std::chrono::treat_as_floating_point_v<Rep>) {
34 return std::chrono::duration_cast<Duration>(seconds + std::chrono::duration_cast<Duration>(nanos));
35 } else {
36 using CommonRep = std::common_type_t<Rep, std::int64_t>;
37 using Period = typename Duration::period;
38 using NanoRatio = std::ratio_divide<std::nano, Period>;
39 CommonRep scaled_nanos{};
40 if (__builtin_mul_overflow(nanos.count(), NanoRatio::num, &scaled_nanos)) {
41 throw Exception(error_message);
42 }
43 auto subsecond_units = static_cast<std::int64_t>(scaled_nanos / NanoRatio::den) * Period::num;
44 auto whole_seconds = seconds.count();
45 if (whole_seconds < 0 && subsecond_units > 0) {
46 ++whole_seconds;
47 subsecond_units -= Period::den;
48 }
49 CommonRep units{};
50 Rep result{};
51 if (__builtin_mul_overflow(whole_seconds, Period::den, &units) ||
52 __builtin_add_overflow(units, subsecond_units, &units) ||
53 __builtin_add_overflow(units / Period::num, 0, &result))
54 {
55 throw Exception(error_message);
56 }
57 return Duration{result};
58 }
59}
60
61} // namespace impl
62
63/// @brief Checks if @c google::protobuf::Timestamp contains a valid value according to protobuf documentation.
64///
65/// The timestamp must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive
66/// and 'nanos' must be from 0 to 999,999,999 inclusive.
67bool IsValid(const google::protobuf::Timestamp& grpc_ts);
68
69/// @brief Exception thrown when timestamp conversion functions receive/produce invalid @c google::protobuf::Timestamp
70/// according to @c IsValid or otherwise lead to undefined behavior due to integer overflow.
71class TimestampConversionError : public std::overflow_error {
72 using std::overflow_error::overflow_error;
73};
74
75/// @brief Creates @c google::protobuf::Timestamp from @c std::chrono::time_point.
76///
77/// @throws TimestampConversionError if the value is not valid according to @c IsValid.
78template <class Duration>
79google::protobuf::Timestamp ToProtoTimestamp(const std::chrono::time_point<std::chrono::system_clock, Duration>&
80 system_tp) {
81 const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(system_tp.time_since_epoch());
82 const auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(system_tp.time_since_epoch() - seconds);
83
84 google::protobuf::Timestamp timestamp;
85 timestamp.set_seconds(seconds.count());
86 timestamp.set_nanos(nanos.count());
87
88 if (!IsValid(timestamp)) {
89 throw TimestampConversionError("system_tp is invalid");
90 }
91 return timestamp;
92}
93
94/// @brief Creates @c std::chrono::system_clock::time_point from @c google::protobuf::Timestamp.
95///
96/// @throws TimestampConversionError if the value is not valid according to @c IsValid or does not fit the time_point.
97template <class Duration = std::chrono::system_clock::duration>
98std::chrono::time_point<std::chrono::system_clock, Duration> ToTimePoint(const google::protobuf::Timestamp& grpc_ts) {
99 if (!IsValid(grpc_ts)) {
100 throw TimestampConversionError("grpc_ts is invalid");
101 }
102
103 const auto duration = impl::ToChronoDuration<Duration, TimestampConversionError>(
104 std::chrono::seconds{grpc_ts.seconds()},
105 std::chrono::nanoseconds{grpc_ts.nanos()},
106 "grpc_ts does not fit the output type"
107 );
108 return std::chrono::time_point<std::chrono::system_clock, Duration>{duration};
109}
110
111/// @brief Returns current (possibly, mocked) timestamp as a @c google::protobuf::Timestamp.
112google::protobuf::Timestamp NowTimestamp();
113
114/// @brief Checks if @c google::type::Date contains a valid value according to protobuf documentation.
115///
116/// Year must be from 1 to 9999.
117/// Month must be from 1 to 12.
118/// Day must be from 1 to 31 and valid for the year and month.
119bool IsValid(const google::type::Date& grpc_date);
120
121/// @brief Exception thrown when date conversion functions receive/produce invalid @c google::type::Date
122/// according to @c IsValid or otherwise lead to undefined behavior due to integer overflow.
123class DateConversionError : public std::overflow_error {
124 using std::overflow_error::overflow_error;
125};
126
127#if __cpp_lib_chrono >= 201907L
128
129/// @brief Creates @c google::type::Date from @c std::chrono::year_month_day.
130///
131/// @throws DateConversionError if the value is not valid according to @c IsValid.
132google::type::Date ToProtoDate(const std::chrono::year_month_day& system_date);
133
134/// @brief Creates @c std::chrono::year_month_day from @c google::type::Date.
135///
136/// @throws DateConversionError if the value is not valid according to @c IsValid.
137std::chrono::year_month_day ToYearMonthDay(const google::type::Date& grpc_date);
138
139#endif
140
141/// @brief Creates @c google::type::Date from @c utils::datetime::Date.
142///
143/// @throws DateConversionError if the value is not valid according to @c IsValid.
144google::type::Date ToProtoDate(const utils::datetime::Date& utils_date);
145
146/// @brief Creates @c utils::datetime::Date from @c google::type::Date.
147///
148/// @throws DateConversionError if the value is not valid according to @c IsValid.
149utils::datetime::Date ToUtilsDate(const google::type::Date& grpc_date);
150
151/// @brief Creates @c google::type::Date from @c std::chrono::time_point.
152///
153/// @throws DateConversionError if the value is not valid according to @c IsValid.
154template <class Duration>
155google::type::Date ToProtoDate(const std::chrono::time_point<std::chrono::system_clock, Duration>& system_tp) {
156 return ToProtoDate(utils::datetime::Date(std::chrono::floor<utils::datetime::Date::Days>(system_tp)));
157}
158
159/// @brief Creates @c std::chrono::system_clock::time_point from @c google::type::Date.
160///
161/// @throws DateConversionError if the value is not valid according to @c IsValid.
162std::chrono::time_point<std::chrono::system_clock, utils::datetime::Days> ToTimePoint(
163 const google::type::Date& grpc_date
164);
165
166/// @brief Returns current (possibly, mocked) timestamp as a @c google::type::Date.
167google::type::Date NowDate();
168
169/// @brief Checks if @c google::protobuf::Duration contains a valid value according to protobuf documentation.
170///
171/// Seconds must be from -315,576,000,000 to +315,576,000,000 inclusive.
172/// Note: these bounds are computed from: 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
173/// For durations of one second or more, a non-zero value for the `nanos` field must be of the same sign as `seconds`.
174/// Nanos must also be from -999,999,999 to +999,999,999 inclusive.
175bool IsValid(const google::protobuf::Duration& grpc_duration);
176
177/// @brief Exception thrown when duration conversion functions receive/produce invalid @c google::protobuf::Duration
178/// according to @c IsValid or otherwise lead to undefined behavior due to integer overflow.
179class DurationConversionError : public std::overflow_error {
180 using std::overflow_error::overflow_error;
181};
182
183/// @brief Creates @c std::chrono::duration from @c google::protobuf::Duration.
184///
185/// @throws DurationConversionError if the value is not valid according to @c IsValid or does not fit the Duration.
186template <class Duration = std::chrono::microseconds>
187Duration ToDuration(const google::protobuf::Duration& grpc_duration) {
188 if (!IsValid(grpc_duration)) {
189 throw DurationConversionError("grpc_duration is invalid");
190 }
191
192 return impl::ToChronoDuration<Duration, DurationConversionError>(
193 std::chrono::seconds{grpc_duration.seconds()},
194 std::chrono::nanoseconds{grpc_duration.nanos()},
195 "grpc_duration does not fit the output type"
196 );
197}
198
199/// @brief Creates @c google::protobuf::Duration from @c std::chrono::duration.
200///
201/// @throws DurationConversionError if the value is not valid according to @c IsValid.
202template <class Rep, class Period>
203google::protobuf::Duration ToProtoDuration(const std::chrono::duration<Rep, Period>& duration) {
204 const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
205 const auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
206
207 google::protobuf::Duration result;
208 result.set_seconds(seconds.count());
209 result.set_nanos(nanos.count());
210 if (!IsValid(result)) {
211 throw DurationConversionError("duration is invalid");
212 }
213 return result;
214}
215
216} // namespace ugrpc
217
218namespace formats::parse {
219
220google::protobuf::Timestamp Parse(const formats::json::Value& json, formats::parse::To<google::protobuf::Timestamp>);
221
222google::type::Date Parse(const formats::json::Value& json, formats::parse::To<google::type::Date>);
223
224} // namespace formats::parse
225
226namespace formats::serialize {
227
228formats::json::Value Serialize(const google::protobuf::Timestamp& value, formats::serialize::To<formats::json::Value>);
229
230formats::json::Value Serialize(const google::type::Date& value, formats::serialize::To<formats::json::Value>);
231
232} // namespace formats::serialize
233
234USERVER_NAMESPACE_END