ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! MEDIA TIME: a position measured against a STREAM's own timebase, and the four newtypes that make
//! a foreign `mediatime` value declarable.
//!
//! # Two time domains, and this is the second one
//!
//! [`Timestamp`](crate::Timestamp) and [`TimeRange`](crate::TimeRange) are the FRAMEWORK's temporal
//! citizens and they measure against the UTC timeline: an instant is absolute, needs no context to
//! read, and every build has them. This house measures against a `Timebase` — a tick count whose
//! meaning is the rational that rides beside it, so the same `pts` names different instants under
//! different units. The two are SIBLINGS rather than rivals: the interval algebra here is the one
//! [`TimeRange`](crate::TimeRange) publishes, word for word, over a different notion of *when*.
//!
//! The split is measured rather than asserted. `mediagraph`'s speech-span household reached for the
//! framework's wall-clock range, could not use it — a segmenter emits pts pairs in the decoder's
//! timebase, and there is no instant to convert them to without a wall-clock anchor the stream does
//! not carry — and declared against this family instead. That is the evidence the second domain
//! exists.
//!
//! # The name walk: `Media` is the qualifier, and only where a resident word is at stake
//!
//! Every citizen of the two POSITION households wears it — [`MediaTimestamp`],
//! [`MediaTimeRange`] and the operands, filters, bounds and comparisons whose stems they are —
//! because each names a position or an extent, which is the exact thing the resident family names,
//! and `Timestamp`, `TimeRange`, `Contained`, `Instant`, `Span` and `Duration` are all words that
//! family owns or would want.
//!
//! [`Timebase`] and [`Rate`] do NOT wear it. A timebase is a UNIT and a rate is a FREQUENCY; neither
//! is a position, no resident name is near either, and a qualifier that disambiguates nothing is
//! noise. That is the [`lang`](super::lang) family's own shape — `ScriptSubtag` qualified because a
//! resident `Script` was at stake, `Language` and `Region` bare because nothing was.
//!
//! **Which side renames was not a coin toss.** This crate has already decided the case, on this
//! exact name: when `jiff::Timestamp` wanted a filter name, the framework's own `Timestamp` kept
//! `TimestampFilter` and the VOCABULARY type took `DateTimeFilter` — *"it belongs to the framework's
//! own `Timestamp` above, whose operators do read a scalar of that name"*. The residents are ungated
//! and present in every build; this family arrives behind a feature. The unqualified word stays with
//! the citizen every build sees.
//!
//! It is also why the rename could not be avoided by module scoping alone. A path disambiguates
//! Rust; GraphQL keeps ONE FLAT NAMESPACE, so two `Timestamp` types in one schema are a name
//! async-graphql resolves in silence. The wire forced the walk, and the Rust names follow it because
//! both this house and the framework hold the same law — one name across the wire and the domain.
//!
//! # The gate
//!
//! The whole family rides `feature = "mediatime"`, the door named for the dependency it admits.
//! Every face beneath it carries its own cross-gate on top — `async-graphql` for the wire, `sqlx`
//! for the comparisons — so a build takes the vocabulary without the faces it has no backend for.
//!
//! # Three layers, and the one crossing between them
//!
//! Each type keeps ONE name across the wire and the domain — the GraphQL type is spelled exactly as
//! the Rust newtype — and changes shape only at the crossing into storage:
//!
//! ```text
//!   domain             crossing          storage
//!   Timebase           ←reduce→          (i32, i32)   lowest terms
//!   Rate               ←reduce→          (i32, i32)   lowest terms, the RATE's own reading
//!   MediaTimestamp     ←reduce+nanos→    (i64, i32, i32, i64?)   count, units, position
//!   MediaTimeRange     ←reduce+nanos→    (i64, i64, i32, i32, i64?, i64?)
//! ```
//!
//! A FIFTH crossing of this shape exists downstream, over a sound-event detection, and it is not
//! this crate's: a two-column value whose halves are a code and a score decomposes the same way and
//! is written up beside the value it belongs to.
//!
//! # Where domain equality and storage equality part company
//!
//! Every crossing is deliberate, and none is an identity. Stating where each one lands is what
//! keeps a lowering honest, because a lowering that assumes they agree is wrong wherever they do
//! not:
//!
//! - **`Rate` — they agree, by the timebase's own reduction over the other reading.** A rate and a
//!   timebase are one rational read two ways, and each citizen stores the reading its field is named
//!   for: `fps_num`/`fps_den` hold `30000/1001` where `timebase_num`/`timebase_den` hold
//!   `1001/30000`. Storing the reciprocal instead would leave two `INTEGER` columns whose convention
//!   nothing in the schema states — see [`Rate`], where the rule is.
//! - **`Timebase` — they agree, and the reduction is what makes them.** `mediatime` compares
//!   timebases by VALUE (`1/2 == 2/4`, by cross-multiplication), and both sides of the crossing
//!   reduce to lowest terms through [`Timebase::reduced`] — so two spellings of one timebase become
//!   one stored pair, and an index on `(num, den)` answers `eq` exactly. What canonicalising costs
//!   is the pair the stream declared, which storage does not keep and
//!   [`Display`](core::fmt::Display) does.
//! - **`MediaTimestamp` — the VALUE is exact and the POSITION is coarser.** The count and the timebase
//!   are stored as declared, so nothing about the value is lost. The derived nanosecond column
//!   truncates toward zero, so two distinct instants finer than a nanosecond apart share one
//!   position. The implication runs one way only: equal timestamps always produce equal nanoseconds
//!   (the truncation is a function of the exact rational, so it cannot separate what the domain
//!   calls equal), while equal nanoseconds do not imply equal timestamps.
//!
//!   That one-way implication is exactly what decides which operands the two operator groups admit.
//!   An IDENTITY operand must reach its position through the same `to_nanos` the write path used, so
//!   it is required to be an exact pair; a BOUND may be any position, a clock string included, since
//!   a boundary displaced by a fraction of a nanosecond selects the same rows. See
//!   [`MediaTimestampFilter`].
//!
//!   It is also why there are TWO identity seats rather than one. `eq` asks about the POSITION and
//!   inherits the coarseness in both its directions — across timebases, and below the nanosecond.
//!   `exact` asks about the ENCODING and reaches the value columns, where there is no coarseness to
//!   inherit: a client de-duplicating rows wants the second, a client asking what was playing at an
//!   instant wants the first, and neither is the other's approximation. [`MediaTimeRange`] carries the
//!   same seat, where it is the type's only whole-value identity — a range has no `eq`, so what
//!   `exact` closes there is the round trip rather than a truncation.
//!
//! # Every citizen has crossed, and two of them nest a third
//!
//! All four storage sides are built. [`SqlTimebaseComparison`] holds the two reduced halves of a
//! timebase; [`SqlMediaTimestampComparison`] holds a derived position, a declared count and a WHOLE
//! timebase comparison; [`SqlMediaTimeRangeComparison`] holds the interval algebra over two derived
//! positions, two counts and the same nested citizen. They live behind the `sqlx` feature with the
//! rest of the SQL family, so a default build has the filters and no comparison at all — which is
//! right: a comparison is a fact about a BACKEND, and a build that compiles none has nothing to
//! state.
//!
//! **The nesting is the recursion, and it goes both ways.** A timestamp's filter holds a
//! [`TimebaseFilter`] and its comparison holds a [`SqlTimebaseComparison`], so everything the
//! timebase citizen can answer is answerable one level up without a line of it being restated —
//! its row-value memberships, its render facet, its refusals. A range holds the same citizen again.
//! On the wire the same recursion is a nested INPUT OBJECT and, on the way out, a nested object:
//! `MediaTimeRange.startInstant` is a whole `MediaTimestamp` with its own derived readings.
//!
//! Every one of them implements `ingraph`'s [`ComplexComparison`], whose `apply` takes ONE address — which a
//! two-column comparison can satisfy because an address carries a PATH: each part pushes one
//! segment onto it, so an address at `timebase` reaches `timebase_num` and `timebase_den` and one
//! at `detected` reaches `detected_code` and `detected_score`, while the same two comparisons
//! applied at the TOP LEVEL reach `num`/`den` and `code`/`score` — the empty path being what a
//! prefix has no spelling for. The `_` between the segments is the [`Backend`]'s, and whatever
//! emits the DDL is the party that has to agree with it. What the shape rules out is a lowering
//! taking a name PER column, where two arguments of one type can be passed in the wrong order and
//! no assertion over the rendered SQL can see which operand landed where.
//!
//! The timebase and the detection arrive at their second column from opposite directions — a
//! timebase is one value that DECOMPOSES, a detection is a pair to begin with — and that shows in
//! what each crossing may refuse. The timebase's has a three-variant error: naming one column's
//! equality twice, either way round, and an affix operand holding a character its rendering cannot.
//! A crossing over a pair that was never one value has none to make.
//!
//! It was SEVEN variants, and the four that went are the measure of what the row value bought: a
//! whole-timebase `ne`, `in` and `not_in` were refused as unanswerable and are now one predicate
//! each, and the affix operators were refused for want of a subject and now build one in SQL. See
//! [`SqlTimebaseComparison`], where each spelling is argued.
//!
//! The two TIME citizens add a third refusal shape between them, and it is the one the derived
//! columns buy: an operand with no `i64` nanosecond position, refused at the crossing rather than
//! clamped to the ceiling. The same ceiling met by a stored VALUE is answered differently — the
//! write path binds `NULL` for the position and keeps the value columns exact — and the two
//! postures are stated where each is taken.
//!
//! # A COLLECTION of these, and which two citizens are admitted as one
//!
//! [`MediaTimestamp`] and [`MediaTimeRange`] each carry a `CollectionElement` admission and a
//! quantified `Vec` reading, so `Vec<MediaTimeRange>` and `Vec<MediaTimestamp>` are field types a
//! declaration can name: a speech-span list, a scene list, a cue list, a chapter table. That is the
//! shape the household exists to serve, and the row that lets an edge table hold one.
//!
//! [`Timebase`] and [`Rate`] carry NEITHER, and the absence is a ruling rather than an omission. A
//! stream declares ONE tick unit and ONE frame rate; a `Vec` of either is not a question anyone asks
//! of a stream, and admitting one would publish a collection face over a value whose whole job is to
//! be the SINGLE unit the positions beside it are counted in. The day a caller has a real list of
//! rates, the two rows are two lines — which is the crate's own *a name arrives when a caller does*
//! read at face scale.
//!
//! Both admitted readings are QUANTIFIED rather than wide, and the two arguments differ. A span has
//! no order at all, so the wide kind's four lexicographic operators are not questions it could
//! answer; a position HAS one, and is refused the wide kind for a different reason — its identity
//! already has two answers, `exact` on the encoding and `eq` on the derived position, and a whole-
//! element list operator would have to pick one in silence. Each row carries its own.
//!
//! # The wire faces
//!
//! Behind the `async-graphql` feature: the four newtypes as GraphQL OBJECTS, EIGHT operand scalars
//! beneath them, and FIVE input objects — one per filter, plus the range's nested duration facet.
//!
//! # Wire shape
//!
//! Each wire type mirrors its Rust struct field for field, and [`Timebase`] adds four DERIVED
//! readings beside its two. The derived-field rule the other time types follow — no `seconds`, no
//! formatted duration, because a lossy field sitting next to the exact one invites a client to read
//! the wrong one — is stated as a rule about EXACTNESS rather than about derivation, and a timebase
//! is where it stops applying: `name` and `text` are exact, and `hz`/`secondsPerTick` are the one
//! question a timebase is actually asked, computed here rather than in whatever precision a client
//! can afford. The exact pair is published beside them, which is the condition the rule states.
//!
//! ```text
//! scalar RateOperand
//! scalar TimebaseOperand    scalar MediaTimestampOperand   scalar MediaInstantBound
//! scalar MediaTimeRangeOperand   scalar MediaSpanBound          scalar MediaContainedOperand
//! scalar MediaDurationBound
//!
//! type Timebase            { numerator: Int! denominator: Int! name: String text: String!
//!                            hz: Float secondsPerTick: Float! }
//! type Rate                { numerator: Int! denominator: Int! name: String text: String!
//!                            hz: Int perSecond: Float! timebase: Timebase }
//! type MediaTimestamp           { pts: Int! timebase: Timebase!
//!                            nanos: Int seconds: Float clock: String }
//! type MediaTimeRange           { start: Int! end: Int! timebase: Timebase!
//!                            startInstant: MediaTimestamp! endInstant: MediaTimestamp!
//!                            durationNanos: Int durationSeconds: Float
//!                            durationClock: String }
//!
//! input TimebaseFilter     { eq: TimebaseOperand  ne: TimebaseOperand
//!                            in: [TimebaseOperand!]  notIn: [TimebaseOperand!]
//!                            startsWith: String  endsWith: String  contains: String
//!                            numerator: I32Filter  denominator: NonZeroI32Filter }
//! input MediaTimestampFilter    { exact: MediaTimestampOperand
//!                            eq/ne: MediaTimestampOperand  in/notIn: [MediaTimestampOperand!]
//!                            gt/gte/lt/lte: MediaInstantBound
//!                            pts: I64Filter  timebase: TimebaseFilter }
//! input MediaTimeRangeFilter    { exact: MediaTimeRangeOperand
//!                            contains: MediaContainedOperand  overlaps: MediaSpanBound
//!                            within: MediaSpanBound  before/after: MediaInstantBound
//!                            duration: MediaSpanDurationFilter
//!                            startPts: I64Filter  endPts: I64Filter
//!                            timebase: TimebaseFilter }
//! input MediaSpanDurationFilter { gt/gte/lt/lte: MediaDurationBound }
//! input RateFilter         { eq/ne: RateOperand  in/notIn: [RateOperand!]
//!                            startsWith: String  endsWith: String  contains: String
//!                            numerator: I32Filter  denominator: NonZeroI32Filter }
//! ```
//!
//! The two TIME objects publish DERIVED readings beside their stored fields, as the timebase does
//! and for its reason: `nanos`, `seconds` and `clock` are three readings of one position, and the
//! exact value sits beside them. All of them are NULLABLE together, an instant past ±292 years
//! having no `i64` position — and the stored fields never are, a value being a value however
//! extreme.
//!
//! `clock` is rendered at NANOSECOND resolution rather than through `mediatime`'s millisecond one,
//! so what it publishes is a string [`MediaInstantBound`] reads back to the same position. A face
//! publishing a bound its own door refuses would be lying about its vocabulary.
//!
//! Every field here maps to a scalar async-graphql already ships. The time fields all land on
//! GraphQL's `Int`, and a timebase's two halves land there EXACTLY: `Int` is specified as a 32-bit
//! SIGNED integer, which is `i32` and nothing else, so `numerator` gives up nothing at all and
//! [`NonZeroI32`] gives up only zero.
//!
//! `i64` is the field type that is NOT exact. async-graphql maps it to `Int` as well, so a `pts`
//! past ±2³¹ is a JSON number wider than a strict client expects, in either direction. It is the
//! same trade async-graphql makes for every `i64`, and the alternative — a `String`-encoded custom
//! scalar — would give up numeric comparison on the wire to fix a range problem that only shows up
//! past ~6.6 hours of 90 kHz PTS. A field where that trade does NOT hold is one whose values are
//! ALREADY past the `Int` ceiling rather than merely able to reach it; no field in this house is.
//!
//! Two PAIRS of the eight operand scalars are one domain type behind two doors, and that pair is the
//! ruling this layer exists to carry: [`MediaTimestampOperand`] admits an exact `{pts, timebase}` and
//! nothing else, where [`MediaInstantBound`] additionally admits `{seconds}`, `{nanos}` and a CLOCK
//! STRING. Identity needs the operand to reach its position through the same function the write path
//! used; a bound does not. See [`MediaTimestampFilter`] for the whole argument.
//!
//! [`Backend`]: crate::Backend
//! [`ComplexComparison`]: crate::ComplexComparison
//! [`NonZeroI32`]: core::num::NonZeroI32

mod clock;
mod rate;
mod rational;
mod timebase;
mod timerange;
mod timestamp;

#[cfg(test)]
mod tests;

pub use clock::ParseClockError;
pub use rate::{ParseRateError, Rate, RateColumnError, RateFilter};
pub use timebase::{ParseTimebaseError, Timebase, TimebaseColumnError, TimebaseFilter};
pub use timerange::{
  InvertedMediaTimeRange, MediaContained, MediaSpanDurationFilter, MediaTimeRange,
  MediaTimeRangeFilter, MediaTimeRangeLeaf,
};
pub use timestamp::{MediaTimestamp, MediaTimestampFilter, MediaTimestampLeaf, NanosecondOverflow};

#[cfg(feature = "async-graphql")]
pub use rate::RateOperand;
#[cfg(feature = "sqlx")]
pub use rate::{RateCrossingError, SqlRateComparison};
#[cfg(feature = "async-graphql")]
pub use timebase::TimebaseOperand;
#[cfg(feature = "sqlx")]
pub use timebase::{SqlTimebaseComparison, TimebaseCrossingError};
// UNGATED for `MediaInstantBound`'s reason: each is a CARRIER some slot holds, or the wire form a
// crossing names, so an API that exists in every build with this vocabulary names it.
// `MediaDurationBound` is there by the orphan rule — a length is `mediatime`'s and no crossing can
// be spelled on a foreign type — and the other three because their doors are the second one over a
// type whose crossing was already spent.
pub use timerange::{
  MediaContainedOperand, MediaDurationBound, MediaSpanBound, MediaTimeRangeOperand,
};
#[cfg(feature = "sqlx")]
pub use timerange::{MediaTimeRangeCrossingError, SqlMediaTimeRangeComparison};
// UNGATED, unlike the operand re-exports above it: `MediaInstantBound` is the carrier
// `MediaTimestampFilter`'s four bound slots hold, so it is named by an API that exists in every
// build with this vocabulary. The rule is the same one the declarations follow — a crossing is a
// fact about the value — and the export follows what the ungated surface has to be able to name.
pub use timestamp::{MediaInstantBound, MediaTimestampOperand};
#[cfg(feature = "sqlx")]
pub use timestamp::{MediaTimestampCrossingError, SqlMediaTimestampComparison};