1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#[cfg(feature = "sqlx")]
use crate::pg_num::PgU8;
use crate::user::{ShortUser, UserIdRef};
use chrono::{DateTime, Duration, NaiveDateTime, TimeZone, Timelike, Utc};
#[cfg(feature = "serde")]
use etwin_serde_tools::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "sqlx")]
use sqlx::postgres::types::PgRange;
#[cfg(feature = "sqlx")]
use sqlx::{postgres, Postgres};
use std::fmt;
#[cfg(feature = "sqlx")]
use std::ops::Bound;
use std::ops::{Range, RangeFrom};
#[cfg(feature = "sqlx")]
use thiserror::Error;

pub type HtmlFragment = String;

declare_new_enum!(
  pub enum LocaleId {
    #[str("de-DE")]
    DeDe,
    #[str("en-US")]
    EnUs,
    #[str("eo")]
    Eo,
    #[str("es-SP")]
    EsSp,
    #[str("fr-FR")]
    FrFr,
  }
  pub type ParseError = LocaleIdParseError;
  const SQL_NAME = "locale_id";
);

/// A point in time, with a millisecond precision.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Instant(DateTime<Utc>);

const NANOSECOND_PER_MILLISECOND: u32 = 1_000_000;

impl Instant {
  /// Round down nanosecond precision Chrono DateTime to to millisecond precision Instant.
  pub fn new_round_down(inner: DateTime<Utc>) -> Self {
    let nanos = inner.nanosecond();
    Self(
      inner
        .with_nanosecond(nanos - (nanos % NANOSECOND_PER_MILLISECOND))
        .expect("invalid time"),
    )
  }

  // TODO: Return result (error on invalid data)
  // TODO: Avoid deprecated functions in implementation
  pub fn ymd_hms(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> Self {
    #[allow(deprecated)]
    Self(Utc.ymd(year, month, day).and_hms(hour, min, sec))
  }

  // TODO: Return result (error on invalid data)
  // TODO: Avoid deprecated functions in implementation
  pub fn ymd_hms_milli(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32, milli: u32) -> Self {
    #[allow(deprecated)]
    Self(Utc.ymd(year, month, day).and_hms_milli(hour, min, sec, milli))
  }

  /// Create an Instant from the number of POSIX seconds since 1970-01-01T00:00:00Z.
  ///
  /// Note: POSIX seconds are defined as 1/86400 of a day (they ignore leap seconds).
  pub fn from_posix_timestamp(secs: i64) -> Self {
    let naive = match NaiveDateTime::from_timestamp_opt(secs, 0) {
      Some(t) => t,
      None => panic!("invalid posix timestamp {secs}"),
    };
    Self(DateTime::<Utc>::from_utc(naive, Utc))
  }

  pub fn into_chrono(self) -> DateTime<Utc> {
    self.0
  }

  pub fn into_posix_timestamp(self) -> i64 {
    self.0.timestamp()
  }
}

impl fmt::Display for Instant {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Display::fmt(&self.0, f)
  }
}

#[cfg(feature = "serde")]
impl Serialize for Instant {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: Serializer,
  {
    const INSTANT_FORMAT: &str = "%FT%T%.3fZ";

    self.0.format(INSTANT_FORMAT).to_string().serialize(serializer)
  }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Instant {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let inner = DateTime::<Utc>::deserialize(deserializer)?;
    Ok(Self::new_round_down(inner))
  }
}

#[cfg(feature = "sqlx")]
impl sqlx::Type<Postgres> for Instant {
  fn type_info() -> postgres::PgTypeInfo {
    postgres::PgTypeInfo::with_name("instant")
  }

  fn compatible(ty: &postgres::PgTypeInfo) -> bool {
    *ty == Self::type_info() || *ty == DateTime::<Utc>::type_info()
  }
}

#[cfg(feature = "sqlx")]
impl<'r> sqlx::Decode<'r, Postgres> for Instant {
  fn decode(value: postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
    let v: DateTime<Utc> = <DateTime<Utc> as sqlx::Decode<Postgres>>::decode(value)?;
    Ok(Self::new_round_down(v))
  }
}

#[cfg(feature = "sqlx")]
impl<'q> sqlx::Encode<'q, Postgres> for Instant {
  fn encode_by_ref(&self, buf: &mut postgres::PgArgumentBuffer) -> sqlx::encode::IsNull {
    let v: DateTime<Utc> = self.into_chrono();
    v.encode(buf)
  }
}

impl std::ops::Add<chrono::Duration> for Instant {
  type Output = Instant;

  fn add(self, rhs: Duration) -> Self::Output {
    Self::new_round_down(self.into_chrono() + rhs)
  }
}

/// Private type used to serialize PeriodLower and its variants.
#[cfg(feature = "serde")]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
struct SerializablePeriodLower {
  pub start: Instant,
  pub end: Option<Instant>,
}

#[cfg(feature = "serde")]
impl From<PeriodFrom> for SerializablePeriodLower {
  fn from(period: PeriodFrom) -> Self {
    Self {
      start: period.start,
      end: None,
    }
  }
}

#[cfg(feature = "serde")]
impl From<FinitePeriod> for SerializablePeriodLower {
  fn from(period: FinitePeriod) -> Self {
    Self {
      start: period.start,
      end: Some(period.end),
    }
  }
}

#[cfg(feature = "serde")]
impl From<PeriodLower> for SerializablePeriodLower {
  fn from(period: PeriodLower) -> Self {
    match period {
      PeriodLower::From(p) => p.into(),
      PeriodLower::Finite(p) => p.into(),
    }
  }
}

#[cfg_attr(feature = "serde", derive(Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PeriodFrom {
  pub start: Instant,
}

#[cfg(feature = "serde")]
impl Serialize for PeriodFrom {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: Serializer,
  {
    SerializablePeriodLower::from(*self).serialize(serializer)
  }
}

impl From<RangeFrom<Instant>> for PeriodFrom {
  fn from(r: RangeFrom<Instant>) -> Self {
    Self { start: r.start }
  }
}

impl From<PeriodFrom> for RangeFrom<Instant> {
  fn from(r: PeriodFrom) -> Self {
    r.start..
  }
}

#[cfg_attr(feature = "serde", derive(Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FinitePeriod {
  pub start: Instant,
  pub end: Instant,
}

#[cfg(feature = "serde")]
impl Serialize for FinitePeriod {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: Serializer,
  {
    SerializablePeriodLower::from(*self).serialize(serializer)
  }
}

impl From<Range<Instant>> for FinitePeriod {
  fn from(r: Range<Instant>) -> Self {
    Self {
      start: r.start,
      end: r.end,
    }
  }
}

impl From<FinitePeriod> for Range<Instant> {
  fn from(r: FinitePeriod) -> Self {
    r.start..r.end
  }
}

/// Represents the raw `PERIOD` Postgres type. It should not be used directly.
#[cfg(feature = "sqlx")]
struct PgPeriod;

#[cfg(feature = "sqlx")]
impl sqlx::Type<Postgres> for PgPeriod {
  fn type_info() -> postgres::PgTypeInfo {
    postgres::PgTypeInfo::with_name("period")
  }

  fn compatible(ty: &postgres::PgTypeInfo) -> bool {
    *ty == Self::type_info()
  }
}

/// Represents any period with a lower bound
#[cfg_attr(feature = "serde", derive(Deserialize), serde(untagged))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PeriodLower {
  Finite(FinitePeriod),
  From(PeriodFrom),
}

impl PeriodLower {
  pub const fn new(start: Instant, end: Option<Instant>) -> Self {
    match end {
      Some(end) => Self::bounded(start, end),
      None => Self::unbounded(start),
    }
  }

  pub const fn unbounded(start: Instant) -> Self {
    Self::From(PeriodFrom { start })
  }

  pub const fn bounded(start: Instant, end: Instant) -> Self {
    Self::Finite(FinitePeriod { start, end })
  }

  pub const fn start(self) -> Instant {
    match self {
      Self::Finite(p) => p.start,
      Self::From(p) => p.start,
    }
  }

  pub const fn end(self) -> Option<Instant> {
    match self {
      Self::Finite(p) => Some(p.end),
      Self::From(_) => None,
    }
  }

  /// Updates the end instant to be the minimum of the current end and provided value
  pub fn end_min(self, other_end: Option<Instant>) -> Self {
    if let Some(end) = other_end {
      Self::Finite(self.bounded_end_min(end))
    } else {
      self
    }
  }

  /// Updates the end instant to be the minimum of the current end and provided value
  pub fn bounded_end_min(self, other_end: Instant) -> FinitePeriod {
    match self {
      Self::From(PeriodFrom { start }) => FinitePeriod { start, end: other_end },
      Self::Finite(FinitePeriod { start, end }) => FinitePeriod {
        start,
        end: Instant::min(end, other_end),
      },
    }
  }
}

#[cfg(feature = "serde")]
impl Serialize for PeriodLower {
  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  where
    S: Serializer,
  {
    SerializablePeriodLower::from(*self).serialize(serializer)
  }
}

#[cfg(feature = "sqlx")]
impl sqlx::Type<Postgres> for PeriodLower {
  fn type_info() -> postgres::PgTypeInfo {
    postgres::PgTypeInfo::with_name("period_lower")
  }

  fn compatible(ty: &postgres::PgTypeInfo) -> bool {
    *ty == Self::type_info() || *ty == PgPeriod::type_info() || *ty == (PgRange::<DateTime<Utc>>::type_info())
  }
}

#[cfg(feature = "sqlx")]
#[derive(Debug, Error)]
#[error("decoded invalid Postgres PERIOD_LOWER as {:?}", .0)]
struct InvalidPeriodLower(PgRange<Instant>);

#[cfg(feature = "sqlx")]
impl<'r> sqlx::Decode<'r, Postgres> for PeriodLower {
  fn decode(value: postgres::PgValueRef<'r>) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
    let range = PgRange::<Instant>::decode(value)?;
    match (range.start, range.end) {
      (Bound::Included(start), Bound::Unbounded) => Ok(PeriodLower::From(PeriodFrom { start })),
      (Bound::Included(start), Bound::Excluded(end)) => Ok(PeriodLower::Finite(FinitePeriod { start, end })),
      _ => Err(Box::new(InvalidPeriodLower(range))),
    }
  }
}

#[cfg(feature = "sqlx")]
impl<'q> sqlx::Encode<'q, Postgres> for PeriodLower {
  fn encode_by_ref(&self, buf: &mut postgres::PgArgumentBuffer) -> sqlx::encode::IsNull {
    let range: PgRange<Instant> = match *self {
      Self::Finite(FinitePeriod { start, end }) => (start..end).into(),
      Self::From(PeriodFrom { start }) => (start..).into(),
    };
    range.encode_by_ref(buf)
  }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UserDot {
  pub time: Instant,
  pub user: ShortUser,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RawUserDot {
  pub time: Instant,
  pub user: UserIdRef,
}

// TODO SecretString/SecretBytes
#[derive(Clone)]
pub struct Secret(String);

impl Secret {
  pub fn new(str: String) -> Self {
    Self(str)
  }

  pub fn as_str(&self) -> &str {
    &self.0
  }
}

declare_new_int! {
  /// A percentage value between 0 and 100 (inclusive) supporting only integer
  /// values.
  pub struct IntPercentage(u8);
  pub type RangeError = IntPercentageRangeError;
  const BOUNDS = 0..=100;
  type SqlType = PgU8;
  const SQL_NAME = "int_percentage";
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Listing<T> {
  pub offset: u32,
  pub limit: u32,
  pub count: u32,
  pub items: Vec<T>,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ListingCount {
  pub count: u32,
}

#[cfg(test)]
mod test {
  #[cfg(feature = "serde")]
  use crate::core::{FinitePeriod, Instant, PeriodFrom, PeriodLower};
  #[cfg(feature = "serde")]
  use std::fs;

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_finite_period_one_millisecond() -> FinitePeriod {
    FinitePeriod {
      start: Instant::ymd_hms(2021, 1, 1, 0, 0, 0),
      end: Instant::ymd_hms_milli(2021, 1, 1, 0, 0, 0, 1),
    }
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_finite_period_one_millisecond() {
    let s = fs::read_to_string("../../test-resources/core/core/finite-period/one-millisecond/value.json").unwrap();
    let actual: FinitePeriod = serde_json::from_str(&s).unwrap();
    let expected = get_finite_period_one_millisecond();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_finite_period_one_millisecond() {
    let value = get_finite_period_one_millisecond();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected =
      fs::read_to_string("../../test-resources/core/core/finite-period/one-millisecond/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_finite_period_one_second() -> FinitePeriod {
    FinitePeriod {
      start: Instant::ymd_hms(2021, 1, 1, 0, 0, 0),
      end: Instant::ymd_hms(2021, 1, 1, 0, 0, 1),
    }
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_finite_period_one_second() {
    let s = fs::read_to_string("../../test-resources/core/core/finite-period/one-second/value.json").unwrap();
    let actual: FinitePeriod = serde_json::from_str(&s).unwrap();
    let expected = get_finite_period_one_second();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_finite_period_one_second() {
    let value = get_finite_period_one_second();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected = fs::read_to_string("../../test-resources/core/core/finite-period/one-second/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_period_from_unbounded() -> PeriodFrom {
    PeriodFrom {
      start: Instant::ymd_hms(2021, 1, 1, 0, 0, 0),
    }
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_period_from_unbounded() {
    let s = fs::read_to_string("../../test-resources/core/core/period-from/unbounded/value.json").unwrap();
    let actual: PeriodFrom = serde_json::from_str(&s).unwrap();
    let expected = get_period_from_unbounded();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_period_from_unbounded() {
    let value = get_period_from_unbounded();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected = fs::read_to_string("../../test-resources/core/core/period-from/unbounded/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_period_lower_one_millisecond() -> PeriodLower {
    PeriodLower::Finite(FinitePeriod {
      start: Instant::ymd_hms(2021, 1, 1, 0, 0, 0),
      end: Instant::ymd_hms_milli(2021, 1, 1, 0, 0, 0, 1),
    })
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_period_lower_one_millisecond() {
    let s = fs::read_to_string("../../test-resources/core/core/period-lower/one-millisecond/value.json").unwrap();
    let actual: PeriodLower = serde_json::from_str(&s).unwrap();
    let expected = get_period_lower_one_millisecond();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_period_lower_one_millisecond() {
    let value = get_period_lower_one_millisecond();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected =
      fs::read_to_string("../../test-resources/core/core/period-lower/one-millisecond/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_period_lower_one_second() -> PeriodLower {
    PeriodLower::Finite(FinitePeriod {
      start: Instant::ymd_hms(2021, 1, 1, 0, 0, 0),
      end: Instant::ymd_hms(2021, 1, 1, 0, 0, 1),
    })
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_period_lower_one_second() {
    let s = fs::read_to_string("../../test-resources/core/core/period-lower/one-second/value.json").unwrap();
    let actual: PeriodLower = serde_json::from_str(&s).unwrap();
    let expected = get_period_lower_one_second();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_period_lower_one_second() {
    let value = get_period_lower_one_second();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected = fs::read_to_string("../../test-resources/core/core/period-lower/one-second/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }

  #[cfg(feature = "serde")]
  #[allow(clippy::unnecessary_wraps)]
  fn get_period_lower_unbounded() -> PeriodLower {
    PeriodLower::unbounded(Instant::ymd_hms(2021, 1, 1, 0, 0, 0))
  }

  #[cfg(feature = "serde")]
  #[test]
  fn read_period_lower_unbounded() {
    let s = fs::read_to_string("../../test-resources/core/core/period-lower/unbounded/value.json").unwrap();
    let actual: PeriodLower = serde_json::from_str(&s).unwrap();
    let expected = get_period_lower_unbounded();
    assert_eq!(actual, expected);
  }

  #[cfg(feature = "serde")]
  #[test]
  fn write_period_lower_unbounded() {
    let value = get_period_lower_unbounded();
    let actual: String = serde_json::to_string_pretty(&value).unwrap();
    let expected = fs::read_to_string("../../test-resources/core/core/period-lower/unbounded/value.json").unwrap();
    assert_eq!(&actual, expected.trim());
  }
}