Skip to main content

Crate mediation

Crate mediation 

Source
Expand description

Telecom usage mediation domain library.

A standalone, pure library for the arithmetic and classification that sits between a mobile or fixed network and a billing system: normalising, validating, deduplicating and correlating usage records. Zero I/O, no async, no clock, exact integer quantities.

It computes usage, not money: there is no currency, tariff, price or rate type here. What leaves this crate is octets, seconds and event counts, attributed to a charged party, a network and a service, which a rating layer then prices.

Long-form documentation lives at https://hupe1980.github.io/mediation. This page is the API reference; the site explains the failure each piece exists to prevent, and every one of its examples is compiled by this crate’s test suite.

§Modules

ModuleContents
errorParseError and DecodeError — one per input kind, string and bytes
digitsDigitString — inline digits, plus the TBCD and plain-BCD codecs
berBerReader, BerElement, BerTag — the X.690 framing a CDR arrives in
cdrtimeCdrTimestamp, QuarterHourOffset, DstAdjustment, MsTimeZone, Seconds
volumeOctets, VolumePair, ByteScale — integer data volumes
plmnMcc, Mnc, PlmnId, TadigCode — network identity, and its three-octet wire form
identityImsi, Msisdn, Imei, Imeisv, Iccid, Supi, Gpsi, Pei, Suci, AddressString
jurisdictionusage_country(), customer_country_presumption() — two questions, two countries
locationUserLocation, Uli, Cgi, Sai, Rai, Lai, Ecgi, Ncgi, Tai — where a record was produced
numberingNumberRange, NumberRangeSet, Porting, terminating_plmn — who really terminates a number
partyChargedParty, SubscriberRef, TenantRef — who the usage is charged to
correlationCorrelationKeys, ChargingId, Icid, correlate(), CorrelatedGroup, LegChain
containerServiceDataContainer, ContainerSet, RatingGroup, ChangeCondition
partialPartialInfo, PartialRun, Reassembly, RecordClosureCause
pipelineprocess(), Batch, ProcessState, ProcessOutcome — the whole layer, in one pass
sessionDnn, Snssai, RatType, ChargingCharacteristics — the network, slice, access and charging profile a session ran on
timebandsplit_session(), split_measured(), apportion() — dividing usage at a tariff boundary
recordUsageRecord, RecordType, ServiceDomain, SourceRef
latenessLatenessPolicy, Lateness — one concept behind every window
sequenceSequenceSpace, SequenceValue, SequenceTracker, SequenceSnapshot — wrap-aware gap detection
dedupRecordKey, DedupStore, DedupWindow — natural-key deduplication
dispositionDisposition, Outcome, BatchReconciliation, PeriodLedger — the conservation law
validationvalidate_records(), Rule (V01–V21), Finding, Severity
restatementRestatement, UsageDelta, RestatementLog — corrections as signed events
qualityscore_batch(), QualityGrade, ReleaseBlocker — the release gate
aggregationaggregate_released(), UsageTotal — what the batch adds up to
roamingTapBatch, BatchTotals, ScaledAmount, RapReturn — a partner’s batch, and whether it adds up
fairuseassess(), FairUseAssessment, FairUseAlert, VolumeAllowance — EU 2016/2286
retentionRetentionPolicy, RetentionSchedule, Deletion — how long a record may be kept
fraudSignal, Indication, impossible_travel() — evidence, never verdicts
privacyPseudonymiser, Reduction — narrowing an identity to the question

§Time is local, not UTC

A charging record carries a local wall-clock time and a numeric offset (3GPP TS 32.298), and the offset counts quarter-hours because a great many zones are not on an hour boundary. Reading such a value as UTC books every evening event of a UTC+X network onto the wrong day, and unlike a fixed-zone mistake it cannot be corrected downstream by a constant, because the offset varies per record.

use mediation::CdrTimestamp;

let ts: CdrTimestamp = "2026-07-28T00:30:00+05:45".parse().unwrap();

// The subscriber's day …
assert_eq!(ts.local_date().to_string(), "2026-07-28");
// … is not the UTC day.
assert_eq!(ts.to_utc().date().to_string(), "2026-07-27");

cdrtime documents the rest, including why CdrTimestamp implements no ordering at all.

§Numeric types

Every chargeable quantity is an integer: Octets is a u64 and Seconds a u32. A data volume is inherently a count, so a float is not merely imprecise but categorically wrong — above 2^53 octets (about 9.01 PB) consecutive integers are no longer representable, and a national monthly aggregate crosses that. No value here is ever routed through a float.

Uplink and downlink are kept apart in VolumePair, with no constructor that takes only a total: asymmetric tariffs and interconnect settlement need the split, and it cannot be recovered once summed.

§Determinism

No function in this crate reads the system clock, the filesystem, the network or any other ambient state. Every input is an argument, so equal inputs always produce equal outputs and any result can be replayed or cached. Where an evaluation instant is needed it is a parameter, which is what allows an archived batch to be reprocessed years later and yield the verdicts it originally did rather than the verdicts of today.

§Every record reaches exactly one outcome

The crate’s central invariant, and the difference between a mediation layer and a data pipeline: a pipeline moves records, while a mediation layer can prove it did not lose any.

carried_in + ingested == billable + suppressed + duplicate + rejected + held

BatchReconciliation::balances is that equation. A batch that fails it has unknown completeness, and billing over unknown completeness invoices an amount nobody can prove is right. And because a held record comes back, PeriodLedger chains batches so the law telescopes across a whole period rather than holding only inside each one. See disposition.

§Rounding is a rating decision

Rounding up to whole chargeable units — per minute, per kilobyte — is priced behaviour. It is offered here as a named primitive (Octets::units_ceil, Seconds::units_ceil) and applied by nothing. What leaves this crate is the measured quantity.

§Every input is untrusted

A mediation layer reads records that arrived over a network from a partner’s equipment, so no input may panic a parser or a decoder. Every FromStr and every wire decoder here returns a Result for arbitrary input, and a property suite hammers all of them with generated strings and bytes on every build.

Two consequences are visible in the API. Anything whose size is chosen by the input is bounded: SequenceTracker::observe caps the missing identities it lists, PartialRun::assess caps the holes it names while still counting them exactly, and BerReader bounds how deep indefinite lengths may nest. And nothing is silently skipped: a decoder that stepped over a field it could not read would produce a record missing exactly the fields it failed on, which is worse than no record.

Re-exports§

pub use aggregation::AggregationError;
pub use aggregation::ReleasedTotals;
pub use aggregation::UsageTotal;
pub use aggregation::aggregate;
pub use aggregation::aggregate_by;
pub use aggregation::aggregate_rating_groups;
pub use aggregation::aggregate_released;
pub use aggregation::aggregate_released_with_carry;
pub use ber::BerElement;
pub use ber::BerLength;
pub use ber::BerReader;
pub use ber::BerTag;
pub use ber::TagClass;
pub use cdrtime::CdrTimestamp;
pub use cdrtime::Century;
pub use cdrtime::DstAdjustment;
pub use cdrtime::MsTimeZone;
pub use cdrtime::QuarterHourOffset;
pub use cdrtime::Seconds;
pub use container::ChangeCondition;
pub use container::ContainerSet;
pub use container::Qos5qi;
pub use container::RatingGroup;
pub use container::ServiceDataContainer;
pub use correlation::BrokenLeg;
pub use correlation::ChargingId;
pub use correlation::CorrelatedGroup;
pub use correlation::CorrelationConfig;
pub use correlation::CorrelationKey;
pub use correlation::CorrelationKeys;
pub use correlation::CorrelationResult;
pub use correlation::Icid;
pub use correlation::LegChain;
pub use correlation::PacketSessionId;
pub use correlation::Unmatched;
pub use correlation::UnmatchedReason;
pub use correlation::correlate;
pub use dedup::DedupDecision;
pub use dedup::DedupStore;
pub use dedup::DedupWindow;
pub use dedup::NotKeyable;
pub use dedup::RecordKey;
pub use digits::DigitString;
pub use disposition::BatchReconciliation;
pub use disposition::ChainBreak;
pub use disposition::Disposition;
pub use disposition::HoldReason;
pub use disposition::Outcome;
pub use disposition::PeriodLedger;
pub use disposition::PeriodTotals;
pub use disposition::RejectReason;
pub use disposition::SuppressReason;
pub use error::DecodeError;
pub use error::ParseError;
pub use fairuse::AllowanceStatus;
pub use fairuse::FairUseAlert;
pub use fairuse::FairUseAssessment;
pub use fairuse::ObservationWindow;
pub use fairuse::PresenceDay;
pub use fairuse::Region;
pub use fairuse::Regions;
pub use fairuse::SafeHarbour;
pub use fairuse::VolumeAllowance;
pub use fraud::CalledParty;
pub use fraud::Indication;
pub use fraud::Signal;
pub use fraud::TrafficShape;
pub use fraud::TransitTimes;
pub use fraud::UniformTransit;
pub use fraud::ait_signature;
pub use fraud::bypass_signature;
pub use fraud::impossible_travel;
pub use fraud::premium_destination;
pub use fraud::wangiri_pattern;
pub use identity::AddressString;
pub use identity::Gpsi;
pub use identity::Iccid;
pub use identity::Imei;
pub use identity::Imeisv;
pub use identity::Imsi;
pub use identity::Msin;
pub use identity::Msisdn;
pub use identity::Nai;
pub use identity::NatureOfAddress;
pub use identity::NumberingPlan;
pub use identity::Pei;
pub use identity::RoutingIndicator;
pub use identity::Suci;
pub use identity::Supi;
pub use identity::Tac;
pub use jurisdiction::Ambiguity;
pub use jurisdiction::Jurisdiction;
pub use jurisdiction::customer_country_presumption;
pub use jurisdiction::is_abroad;
pub use jurisdiction::usage_country;
pub use lateness::Lateness;
pub use lateness::LatenessPolicy;
pub use location::CellId;
pub use location::Cgi;
pub use location::Ecgi;
pub use location::Eci;
pub use location::EnbKind;
pub use location::ExtendedEnbKind;
pub use location::ExtendedMacroEnbId;
pub use location::GnbIdLength;
pub use location::Lac;
pub use location::Lai;
pub use location::MacroEnbId;
pub use location::Ncgi;
pub use location::Nci;
pub use location::Rai;
pub use location::RoutingAreaCode;
pub use location::Sai;
pub use location::ServiceAreaCode;
pub use location::TacWidth;
pub use location::Tai;
pub use location::TrackingAreaCode;
pub use location::Uli;
pub use location::UserLocation;
pub use numbering::NumberRange;
pub use numbering::NumberRangeSet;
pub use numbering::Porting;
pub use numbering::is_ported;
pub use numbering::terminating_plmn;
pub use partial::OrphanReason;
pub use partial::PartialFormat;
pub use partial::PartialInfo;
pub use partial::PartialRun;
pub use partial::Reassembly;
pub use partial::RecordClosureCause;
pub use party::ChargedParty;
pub use party::NfInstanceId;
pub use party::PartyId;
pub use party::SubscriberRef;
pub use party::TenantRef;
pub use party::UnattributableReason;
pub use pipeline::Batch;
pub use pipeline::NoSuppression;
pub use pipeline::ProcessConfig;
pub use pipeline::ProcessOutcome;
pub use pipeline::ProcessState;
pub use pipeline::SequenceGap;
pub use pipeline::Suppression;
pub use pipeline::process;
pub use pipeline::process_with;
pub use plmn::Mcc;
pub use plmn::Mnc;
pub use plmn::MncWidth;
pub use plmn::MncWidths;
pub use plmn::NorthAmericanRule;
pub use plmn::PlmnId;
pub use plmn::TadigCode;
pub use privacy::NumberPrefix;
pub use privacy::Pseudonym;
pub use privacy::Pseudonymiser;
pub use privacy::ReducedSubscriber;
pub use privacy::Reduction;
pub use privacy::reduce_equipment;
pub use privacy::reduce_to_country;
pub use privacy::reduce_to_network;
pub use privacy::software_version;
pub use quality::QualityGrade;
pub use quality::QualityReport;
pub use quality::ReleaseBlocker;
pub use quality::score_batch;
pub use record::NodeId;
pub use record::PrimaryMeasure;
pub use record::RecordType;
pub use record::ServiceDomain;
pub use record::SourceRef;
pub use record::UsageRecord;
pub use restatement::RestateReason;
pub use restatement::Restatement;
pub use restatement::RestatementLog;
pub use restatement::UsageDelta;
pub use retention::Deletion;
pub use retention::RetentionBasis;
pub use retention::RetentionPolicy;
pub use retention::RetentionSchedule;
pub use roaming::BatchDiscrepancy;
pub use roaming::BatchTotals;
pub use roaming::RapReturn;
pub use roaming::ScaledAmount;
pub use roaming::TapBatch;
pub use roaming::TotalKind;
pub use sequence::SequenceObservation;
pub use sequence::SequenceSpace;
pub use sequence::SequenceTracker;
pub use sequence::SequenceValue;
pub use session::ChargingCharacteristics;
pub use session::Dnn;
pub use session::RatType;
pub use session::SessionContext;
pub use session::SliceServiceType;
pub use session::Snssai;
pub use timeband::Apportionment;
pub use timeband::SplitError;
pub use timeband::TimeSlice;
pub use timeband::UsageSplit;
pub use timeband::apportion;
pub use timeband::split_measured;
pub use timeband::split_session;
pub use validation::Finding;
pub use validation::Rule;
pub use validation::Severity;
pub use validation::ValidationConfig;
pub use validation::ValidationReport;
pub use validation::validate_records;
pub use volume::ByteScale;
pub use volume::Octets;
pub use volume::VolumePair;

Modules§

aggregation
What the batch adds up to.
ber
Basic Encoding Rules — the framing every 3GPP charging record is wrapped in.
cdrtime
Charging-record time: local time plus an offset, never a bare instant.
container
Per-service usage inside one record.
correlation
Tying a record to the usage it describes — the identifiers, and the join.
dedup
Deduplication: the natural key is the whole design.
digits
DigitString — a short run of decimal digits, stored inline, and the two binary-coded-decimal conventions a charging record uses.
disposition
The conservation law: every ingested record reaches exactly one outcome.
error
ParseError — the single error type every FromStr in this crate returns.
fairuse
Fair use and permanent roaming (EU 2016/2286).
fraud
Fraud signals: evidence, never verdicts.
identity
Subscriber, subscription and equipment identifiers.
jurisdiction
Which country’s rules apply — and which question you are asking.
lateness
How late a record is, and what that changes.
location
Where a record was produced: cells, service areas and tracking areas.
numbering
What a dialled number means: ranges, and who actually terminates it.
partial
Partial records: reconstruct, never invent.
party
Who a usage record is attributed to.
pipeline
One pass over a batch: the pieces of this crate, wired in a fixed order.
plmn
Network identity: Mcc, Mnc, PlmnId and TadigCode.
privacy
Reducing an identity to what a question actually needs.
quality
The release gate: may this batch be invoiced?
record
The core usage record, and the vocabulary that classifies it.
restatement
Corrections are new records, never edits.
retention
How long a record may be kept, and what it is anchored to.
roaming
Roaming batches: what a partner sent, and whether it adds up.
sequence
Completeness: sequence gaps are the only evidence of loss.
session
What a PDU session was established against: a data network and a slice.
timeband
Splitting one session across tariff-time boundaries.
validation
The numbered rule catalogue.
volume
Data volumes as integer octets, and the unit arithmetic around them.