Skip to main content

ingraph/primitives/mediatime/timestamp/
mod.rs

1//! The [`MediaTimestamp`] primitive: the newtype, its filter, that filter's storage-side comparison,
2//! and the overflow both nanosecond crossings raise.
3
4use core::fmt;
5
6use crate::{CompositeFilterMarker, CompositeMarker, DefaultMarker, ScalarFilter, ToGraphqlInput};
7use mediatime as mt;
8
9use super::TimebaseFilter;
10use crate::graphql::filter::opt_accessor;
11
12#[cfg(feature = "sqlx")]
13mod comparison;
14#[cfg(feature = "async-graphql")]
15mod graphql;
16mod storage;
17
18pub use storage::MediaTimestampLeaf;
19
20#[cfg(test)]
21mod tests;
22
23#[cfg(feature = "sqlx")]
24pub use comparison::{MediaTimestampCrossingError, SqlMediaTimestampComparison};
25
26/// A presentation timestamp — an integer PTS in units of its own [`Timebase`], wrapping
27/// [`mediatime::Timestamp`].
28///
29/// [`Ord`] is `mediatime`'s: two timestamps compare by the exact rational instant, across
30/// timebases, by 128-bit cross-multiplication rather than by `pts`.
31///
32/// [`Timebase`]: super::Timebase
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct MediaTimestamp(mt::Timestamp);
35
36impl MediaTimestamp {
37  /// Wrap a [`mediatime::Timestamp`].
38  ///
39  /// The `const` route in; [`From`] is the other one and is not `const`.
40  #[inline]
41  pub const fn new(timestamp: mt::Timestamp) -> Self {
42    Self(timestamp)
43  }
44
45  /// The wrapped [`mediatime::Timestamp`].
46  #[inline]
47  pub const fn get(&self) -> mt::Timestamp {
48    self.0
49  }
50
51  /// The storage form: the instant in NANOSECONDS since the timebase's origin.
52  ///
53  /// Normalizing at the crossing is what makes an ordering operator mean what it says. Two
54  /// timestamps in different timebases are not comparable by `pts` at all, so a filter that lowered
55  /// `gt` to `WHERE pts > ?` would be silently wrong whenever the stored timebase differed from the
56  /// one the query was written in. There is exactly one unit in the column, and it is this one.
57  ///
58  /// Rounds toward zero, as `mediatime`'s own rescaling does, so the map is not injective — see the
59  /// module docs for which way that leans.
60  ///
61  /// # Errors
62  ///
63  /// [`NanosecondOverflow`] when the instant does not fit `i64` nanoseconds, which spans about
64  /// ±292 years. A real media timestamp always fits; a garbage one must not become a wrong number,
65  /// so this neither panics nor saturates.
66  ///
67  /// The product `pts × 10⁹ × num` is computed in `i128` and cannot overflow THERE. `|pts|` is
68  /// bounded by `2⁶³` and `num` by `i32::MAX`, the latter because `mediatime`'s constructor pins a
69  /// numerator non-negative and its type caps it at `2³¹ − 1`; the largest magnitude is therefore
70  /// `2⁶³ × 10⁹ × (2³¹ − 1) ≈ 1.98 × 10³⁷` against an `i128` ceiling of `≈ 1.70 × 10³⁸`, a factor
71  /// of about 8.6 clear. The only range check that can fail is the one back into `i64`.
72  #[inline]
73  pub const fn to_nanos(self) -> Result<i64, NanosecondOverflow> {
74    let timebase = self.0.timebase();
75    let nanos = (self.0.pts() as i128) * NANOS_PER_SECOND * (timebase.num() as i128)
76      / (timebase.den().get() as i128);
77
78    if nanos < i64::MIN as i128 || nanos > i64::MAX as i128 {
79      Err(NanosecondOverflow { nanos })
80    } else {
81      Ok(nanos as i64)
82    }
83  }
84}
85
86impl From<mt::Timestamp> for MediaTimestamp {
87  #[inline]
88  fn from(timestamp: mt::Timestamp) -> Self {
89    Self(timestamp)
90  }
91}
92
93impl From<MediaTimestamp> for mt::Timestamp {
94  #[inline]
95  fn from(timestamp: MediaTimestamp) -> Self {
96    timestamp.0
97  }
98}
99
100/// A whole timestamp, on its way IN as an IDENTITY operand — the exact pair, and nothing that merely
101/// names a position.
102///
103/// A type of its own rather than [`MediaTimestamp`], and GraphQL's shared name namespace is what forces
104/// it — the same wall [`TimebaseOperand`](super::TimebaseOperand) is on the other side of.///
105/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
106/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form. The binding's half
107/// — the `#[Scalar]` that reads the arms and writes the canonical one — is in `graphql`.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109pub struct MediaTimestampOperand(MediaTimestamp);
110
111impl MediaTimestampOperand {
112  /// Wrap a [`MediaTimestamp`] as an identity operand.
113  #[inline]
114  #[must_use]
115  pub const fn new(timestamp: MediaTimestamp) -> Self {
116    Self(timestamp)
117  }
118
119  /// The wrapped [`MediaTimestamp`].
120  #[inline]
121  #[must_use]
122  pub const fn get(&self) -> MediaTimestamp {
123    self.0
124  }
125}
126
127impl From<MediaTimestamp> for MediaTimestampOperand {
128  #[inline]
129  fn from(timestamp: MediaTimestamp) -> Self {
130    Self(timestamp)
131  }
132}
133
134impl From<MediaTimestampOperand> for MediaTimestamp {
135  #[inline]
136  fn from(operand: MediaTimestampOperand) -> Self {
137    operand.0
138  }
139}
140
141/// A position on the timeline, on its way IN as a BOUND — every exact form, plus the three that name
142/// a position without naming a value.
143///
144/// Holds a [`MediaTimestamp`] like its identity twin. A wide form lands in `mediatime`'s `NANOS` timebase,
145/// which is a value like any other and is exactly what a position with no declared unit is.
146///
147/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
148/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form. The binding's half
149/// — the `#[Scalar]` that reads the arms and writes the canonical one — is in `graphql`.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
151pub struct MediaInstantBound(MediaTimestamp);
152
153impl MediaInstantBound {
154  /// Wrap a [`MediaTimestamp`] as a bound.
155  #[inline]
156  #[must_use]
157  pub const fn new(timestamp: MediaTimestamp) -> Self {
158    Self(timestamp)
159  }
160
161  /// The wrapped [`MediaTimestamp`].
162  #[inline]
163  #[must_use]
164  pub const fn get(&self) -> MediaTimestamp {
165    self.0
166  }
167
168  /// A bare nanosecond position, as the timestamp it is: a count in `mediatime`'s `NANOS`.
169  #[inline]
170  #[must_use]
171  pub const fn of_nanos(nanos: i64) -> Self {
172    Self(MediaTimestamp::new(mt::Timestamp::new(
173      nanos,
174      mt::Timebase::NANOS,
175    )))
176  }
177}
178
179impl From<MediaTimestamp> for MediaInstantBound {
180  #[inline]
181  fn from(timestamp: MediaTimestamp) -> Self {
182    Self(timestamp)
183  }
184}
185
186impl From<MediaInstantBound> for MediaTimestamp {
187  #[inline]
188  fn from(bound: MediaInstantBound) -> Self {
189    bound.0
190  }
191}
192
193/// The OPERAND's own crossing, so a `[MediaTimestamp]` column knows what one element looks like.
194///
195/// The identity door is the one a collection element goes through: a list of timestamps is a list of
196/// VALUES.
197impl ToGraphqlInput for MediaTimestamp {
198  type Input = MediaTimestampOperand;
199  type Error = core::convert::Infallible;
200
201  #[inline]
202  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
203    Ok(input.into())
204  }
205
206  #[inline]
207  fn carry(operand: &Self) -> Self::Input {
208    MediaTimestampOperand::new(*operand)
209  }
210}
211/// The BOUND door's own crossing — and the reason this type is the slot's carrier rather than
212/// [`MediaTimestamp`].
213///
214/// One Rust type serves two doors here: `exact`/`eq`/`ne`/`in`/`notIn` name a VALUE and register
215/// [`MediaTimestampOperand`], while `gt`/`gte`/`lt`/`lte` name a POSITION and register `MediaInstantBound` —
216/// a wider grammar, since a bound may be written as a clock or a count of seconds where an equality
217/// may not. A crossing is ONE row per type, so the two doors cannot both be spelled on `MediaTimestamp`;
218/// the bound slots hold this newtype instead, and it crosses as ITSELF.
219impl ToGraphqlInput for MediaInstantBound {
220  type Input = Self;
221  type Error = core::convert::Infallible;
222
223  #[inline]
224  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
225    Ok(input)
226  }
227
228  #[inline]
229  fn carry(operand: &Self) -> Self::Input {
230    *operand
231  }
232}
233
234/// What guards a [`MediaTimestamp`] column — [`Timebase`]'s row, and the same reading of it: a timestamp
235/// stores every field it declares, so the two seats name one predicate.
236///
237/// [`Timebase`]: super::Timebase
238impl CompositeFilterMarker for MediaTimestamp {
239  type Filter = MediaTimestampFilter;
240  type ColumnFilter = MediaTimestampFilter;
241}
242
243/// The interpretation a [`MediaTimestamp`] field is read under — [`Timebase`]'s reading, and this crate
244/// no longer mints either: a timestamp occupies columns of its own and all of them can be absent
245/// together, which is exactly the VALUE family [`CompositeMarker`] names.
246///
247/// [`Timebase`]: super::Timebase
248impl DefaultMarker for MediaTimestamp {
249  type Marker = CompositeMarker<MediaTimestamp>;
250}
251
252/// **A COLLECTION of positions is asked through the QUANTIFIERS**, and the reason is the ELEMENT's
253/// shape rather than its order.
254///
255/// This type HAS a total order — unlike a span, whose three orderings are why neither range citizen
256/// derives one — so the four lexicographic list operators would at least be well defined over it.
257/// They are still not offered, because the reading a [`ListFilter`](crate::ListFilter) publishes is
258/// the SCALAR one: its operators hold a whole element as a single value, and a media instant is
259/// three columns whose identity question already has two answers — `exact` on the encoding, `eq` on
260/// the derived position. A list operator would have to pick one silently.
261///
262/// [`MediaTimestampFilter`] holds both, so `any` carries the choice WHOLE: *is there a cue at this
263/// exact pts* and *is there a cue at this instant* are two questions the quantifier keeps apart, and
264/// `count` is *how many cues are there*.
265impl crate::DefaultVecMarker for MediaTimestamp {
266  type Marker = crate::QuantifiedMarker<Vec<MediaTimestamp>>;
267}
268
269/// The filter that guards a [`MediaTimestamp`] column: an IDENTITY facet, a BOUND facet, and the two
270/// components a timestamp is made of.
271///
272/// # Four groups, and TWO of them are identities
273///
274/// | facet | slots | operand | columns | asks |
275/// |---|---|---|---|---|
276/// | STRUCTURAL | `exact` | an EXACT timestamp | `pts`, `timebase_*` | which ENCODING a row holds |
277/// | SEMANTIC | `eq`, `ne`, `in_`, `not_in` | an EXACT timestamp | `nanos` | which INSTANT it is at |
278/// | BOUND | `gt`, `gte`, `lt`, `lte` | any nameable POSITION | `nanos` | where it sits on the timeline |
279/// | COMPONENT | `pts`, `timebase` | that half's own filter | one column each | one column, on its own terms |
280///
281/// # `exact` and `eq` are two identities, and neither is the other's approximation
282///
283/// | | `exact: "1 @ 1/1000"` | `eq: "1 @ 1/1000"` |
284/// |---|---|---|
285/// | lowers to | `pts = 1 AND tb_num = 1 AND tb_den = 1000` | `nanos = 1000000` |
286/// | admits `1000 @ 1/1000000` | **no** — a different encoding | **yes** — the same instant |
287/// | admits a sub-nanosecond neighbour | **no** | **yes** — they share a position |
288/// | truncation | NONE: the columns are the value | inherits it: a position is a bucket |
289/// | cross-timebase | no, by construction | yes, by construction |
290///
291/// Both take the SAME operand — a `{pts, timebase}` pair or the text that spells one — and a clock
292/// string is refused by both, for the reason below. What differs is which columns the operand
293/// reaches, and therefore which question is being asked. `exact` is *find the row I wrote*; `eq` is
294/// *find what happened then*.
295///
296/// **Neither subsumes the other and both are exact about what they are.** `eq` is coarser in two
297/// directions at once — across timebases and below the nanosecond — and that is not a defect to be
298/// fixed by `exact`, it is what a position IS. A client de-duplicating rows wants `exact`; a client
299/// asking what was playing at an instant wants `eq`, and would be wrong to be handed structural
300/// equality instead, since the row it is looking for was very likely written in another timebase.
301///
302/// **ENDORSED, 2026-08-29.** PR #453's 呈裁 5 put the two-slot design up for a ruling — whether
303/// `eq`/`ne`/`in`/`notIn` should stay SEMANTIC beside a STRUCTURAL `exact`, or whether one of them
304/// should have been the other — and the ruling kept both slots exactly as the table above reads:
305/// the identity four stay on the derived position, `exact` stays the value-leaf tuple, and neither
306/// moves. The general law ruled beside it says the same thing one level up and for every citizen —
307/// *a derived leaf serves the SEMANTIC order only; every STRUCTURAL judgment walks VALUE leaves
308/// only*, written out at [`ColumnShape`](crate::ColumnShape) — so this house's two slots are that
309/// law's two sides rather than a local arrangement. What the law DID move is where a structural
310/// judgment is spelled elsewhere: pagination's null test and an element's row-value equality both
311/// walked the whole width and now walk the value leaves (ingraph #454, #455).
312///
313/// **There is no `notExact`, and the omission is reasoned.** Its complement is a set nobody asks
314/// for: excluding ONE encoding while keeping every other encoding of the same instant. A client
315/// wanting "not this instant" already has `ne`, which is the wider and the useful exclusion. If a
316/// use appears it is one slot and one `NOT ( … )` conjunct — the shape the timebase citizen's
317/// `excluded` already has — and the same argument extends to `in`/`notIn` twins, which would double
318/// the identity surface for a question asked once.
319///
320/// Both groups hold the same Rust type — a [`MediaTimestamp`] — and the difference is entirely in what
321/// the DOOR admits. An identity operand must be an exact `{pts, timebase}` pair or the exact text
322/// that spells one; a bound operand may additionally be `{seconds}`, `{nanos}`, or a CLOCK STRING
323/// such as `"0:01:30.5"`. A wide form lands as a timestamp in nanoseconds, which is a value like any
324/// other.
325///
326/// # Why the BOUND facet takes more shapes than either identity
327///
328/// **The asymmetry is the same law the timebase's reduction states, transposed.** Both sides of a
329/// crossing must go through ONE function or they select nothing: a stored row's sort key is
330/// [`MediaTimestamp::to_nanos`] applied to the pair the stream declared, so an identity operand that goes
331/// through that same function matches exactly, by construction. A clock string does not go through
332/// it — it is an independent route to a number — so an equality against one is a numeric
333/// COINCIDENCE rather than an identity, and it lands or misses on sub-nanosecond rounding nobody
334/// wrote. `mediatime` says the same thing about its own rendering: the clock *is lossy and has no
335/// inverse*.
336///
337/// As a BOUND the objection evaporates. "Everything after 0:01:30.5" is exactly the question a clock
338/// string asks, and a boundary moved by a fraction of a nanosecond selects the same rows.
339///
340/// **A bare number is refused in both groups**, for the reason it is refused at a timebase: `90` could
341/// be a `pts`, a count of seconds or a count of nanoseconds, and those are three different instants.
342/// A parser that picked one would be guessing at what a client meant, silently.
343///
344/// # The components are recursive
345///
346/// `timebase` is a whole [`TimebaseFilter`] — a citizen nested inside a citizen — so every facet
347/// that filter has is reachable here: `timebase: { eq: "MPEG_90K" }` selects the rows counted on the
348/// MPEG clock whatever instant they name, and `timebase: { numerator: { gt: 1 } }` reaches two
349/// levels down. `pts` is the raw stored count, which is a question about the ENCODING rather than
350/// about time — two rows at one instant in different timebases have different `pts`.
351///
352/// # The wire face is DECLARED, not written
353///
354/// `#[ingraph(composed)]` reads the eleven slots below once and emits the registration, the parse
355/// and the render from them. The four BOUND slots hold [`MediaInstantBound`] rather than [`MediaTimestamp`],
356/// and that is this face's one shape rule: a crossing is one row per type, so the value door and
357/// the wider bound door cannot both be spelled on `MediaTimestamp` — see the crossing on `MediaInstantBound`,
358/// which is where the argument is.
359#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
360#[ingraph(composed)]
361pub struct MediaTimestampFilter {
362  exact: Option<MediaTimestamp>,
363  eq: Option<MediaTimestamp>,
364  ne: Option<MediaTimestamp>,
365  in_: Option<Box<[MediaTimestamp]>>,
366  not_in: Option<Box<[MediaTimestamp]>>,
367  gt: Option<MediaInstantBound>,
368  gte: Option<MediaInstantBound>,
369  lt: Option<MediaInstantBound>,
370  lte: Option<MediaInstantBound>,
371  pts: Option<ScalarFilter<i64>>,
372  timebase: Option<TimebaseFilter>,
373}
374
375impl MediaTimestampFilter {
376  /// The empty filter — no operator set on any facet.
377  #[inline]
378  pub const fn new() -> Self {
379    Self {
380      exact: None,
381      eq: None,
382      ne: None,
383      in_: None,
384      not_in: None,
385      gt: None,
386      gte: None,
387      lt: None,
388      lte: None,
389      pts: None,
390      timebase: None,
391    }
392  }
393
394  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
395  /// field.
396  ///
397  /// Inherent as well as [`GraphqlFilter::is_empty`]; see [`TimebaseFilter::is_empty`].
398  ///
399  /// [`TimebaseFilter::is_empty`]: super::TimebaseFilter::is_empty
400  #[inline]
401  pub const fn is_empty(&self) -> bool {
402    self.exact.is_none()
403      && self.eq.is_none()
404      && self.ne.is_none()
405      && self.in_.is_none()
406      && self.not_in.is_none()
407      && self.gt.is_none()
408      && self.gte.is_none()
409      && self.lt.is_none()
410      && self.lte.is_none()
411      && match &self.pts {
412        Some(pts) => pts.is_empty(),
413        None => true,
414      }
415      && match &self.timebase {
416        Some(timebase) => timebase.is_empty(),
417        None => true,
418      }
419  }
420
421  /// The stored count's own filter — the ENCODING rather than the instant.
422  #[inline]
423  pub const fn pts(&self) -> Option<&ScalarFilter<i64>> {
424    self.pts.as_ref()
425  }
426
427  /// The timebase's own filter, whole — the nested citizen.
428  #[inline]
429  pub const fn timebase(&self) -> Option<&TimebaseFilter> {
430    self.timebase.as_ref()
431  }
432
433  opt_accessor!(exact: MediaTimestamp => with_exact, set_exact, maybe_exact, update_exact);
434  opt_accessor!(eq: MediaTimestamp => with_eq, set_eq, maybe_eq, update_eq);
435  opt_accessor!(ne: MediaTimestamp => with_ne, set_ne, maybe_ne, update_ne);
436  opt_accessor!(in_: [MediaTimestamp] => with_in_, set_in_, maybe_in_, update_in_);
437  opt_accessor!(not_in: [MediaTimestamp] => with_not_in, set_not_in, maybe_not_in, update_not_in);
438  opt_accessor!(gt: MediaInstantBound => with_gt, set_gt, maybe_gt, update_gt);
439  opt_accessor!(gte: MediaInstantBound => with_gte, set_gte, maybe_gte, update_gte);
440  opt_accessor!(lt: MediaInstantBound => with_lt, set_lt, maybe_lt, update_lt);
441  opt_accessor!(lte: MediaInstantBound => with_lte, set_lte, maybe_lte, update_lte);
442
443  /// Replace the stored count's filter (consuming).
444  #[must_use]
445  #[inline]
446  pub fn with_pts(mut self, pts: ScalarFilter<i64>) -> Self {
447    self.set_pts(pts);
448    self
449  }
450
451  /// Replace the stored count's filter (in place).
452  #[inline]
453  pub fn set_pts(&mut self, pts: ScalarFilter<i64>) -> &mut Self {
454    self.pts = Some(pts);
455    self
456  }
457
458  /// Replace the timebase's filter (consuming).
459  #[must_use]
460  #[inline]
461  pub fn with_timebase(mut self, timebase: TimebaseFilter) -> Self {
462    self.set_timebase(timebase);
463    self
464  }
465
466  /// Replace the timebase's filter (in place).
467  #[inline]
468  pub fn set_timebase(&mut self, timebase: TimebaseFilter) -> &mut Self {
469    self.timebase = Some(timebase);
470    self
471  }
472}
473
474impl Default for MediaTimestampFilter {
475  #[inline]
476  fn default() -> Self {
477    Self::new()
478  }
479}
480
481/// An instant does not fit `i64` nanoseconds.
482///
483/// Raised by [`MediaTimestamp::to_nanos`] and [`MediaTimeRange::to_nanos`], which neither panic nor saturate:
484/// `i64` nanoseconds span about ±292 years, so a value outside them is not a large media timestamp
485/// but a wrong one, and the storage boundary is the last place it can still be refused rather than
486/// silently turned into a different instant.
487///
488/// [`MediaTimeRange::to_nanos`]: super::MediaTimeRange::to_nanos
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
490pub struct NanosecondOverflow {
491  nanos: i128,
492}
493
494impl NanosecondOverflow {
495  /// The nanosecond count that did not fit.
496  ///
497  /// Exact rather than clamped: the conversion computes in `i128`, which the product cannot
498  /// overflow, so the number reported here is the one the caller asked for.
499  #[inline]
500  pub const fn nanos(&self) -> i128 {
501    self.nanos
502  }
503}
504
505impl fmt::Display for NanosecondOverflow {
506  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507    write!(f, "{} nanoseconds does not fit an i64", self.nanos)
508  }
509}
510
511impl core::error::Error for NanosecondOverflow {}
512
513/// The nanosecond conversion's multiplier, as the `i128` the whole product is computed in.
514const NANOS_PER_SECOND: i128 = 1_000_000_000;