Input and output¶
jitterbug.io.data_loader
¶
Data loading: file, database and DataFrame entry points.
A file goes through a reader (jitterbug.io.readers, chosen by format) and a database
query through a source (jitterbug.io.sources, chosen by kind); both return a raw
DataFrame, which then goes through the normalizer (jitterbug.io.normalize) that
applies the column mapping, units and row policies of InputConfig.
EPOCH_COLUMN = 'epoch'
module-attribute
¶
Default time column (InputConfig.time_column).
RTT_COLUMNS = RTT_COLUMN_SYNONYMS
module-attribute
¶
Accepted names for the RTT column when InputConfig.rtt_column is None.
SKIPPED_NO_VALID_ROWS = 'no valid RTT rows (every row was missing, non-positive or too large)'
module-attribute
¶
Reason recorded for a series whose rows the row policies all dropped.
DataLoader
¶
Data loader for RTT data.
Supports loading from files (CSV, TSV, generic JSONL, scamper JSON, RIPE Atlas
results, ping/fping output, optionally compressed, and Parquet/Arrow; see
jitterbug.io.readers), database queries (ClickHouse, InfluxDB 2 and 3, DuckDB;
see jitterbug.io.sources) and pandas DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_config
|
InputConfig | None
|
Column mapping, units and row policies; |
None
|
load_from_file(file_path, file_format=None)
¶
Load RTT data from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Union[str, Path]
|
Path to the data file. A trailing |
required |
file_format
|
Optional[str]
|
A registered format ( |
None
|
Returns:
| Type | Description |
|---|---|
RTTDataset
|
Loaded RTT dataset; |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the format is unknown, the content does not satisfy the input contract, a
|
ImportError
|
If the file is compressed with a codec that is not installed. |
read_raw(file_path, file_format=None, apply_series_filter=True)
¶
Read a file into raw rows, without normalizing them; series filters applied.
This is the first half of :meth:load_from_file, shared with :meth:load_series
and jitterbug inspect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path to the data file (possibly compressed). |
required |
file_format
|
str | None
|
A registered format, or |
None
|
apply_series_filter
|
bool
|
Whether to keep only the rows matching |
True
|
Returns:
| Type | Description |
|---|---|
tuple[Reader, RawData, InputConfig]
|
The reader used; its raw data, with |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the format is unknown, the file cannot be read, or a |
ImportError
|
If the file is compressed with a codec that is not installed, or is Parquet or Arrow and pyarrow is not installed. |
load_series(file_path, file_format=None, skipped=None)
¶
Load a file as one dataset per series (InputConfig.group_by).
The series filters are applied first; the rows are then split by the
group_by columns and each series is normalized on its own, so duplicates,
sorting and drops are handled per series. time_unit: auto is inferred once,
on all the rows, so every series is read in the same unit. Without group_by
the result has one entry, under the key ().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path to the data file (possibly compressed). |
required |
file_format
|
str | None
|
A registered format, or |
None
|
skipped
|
dict[SeriesKey, str] | None
|
If given, receives the series left out because the row policies dropped every one of their rows, with the reason. They are logged either way. |
None
|
Returns:
| Type | Description |
|---|---|
dict[SeriesKey, RTTDataset]
|
Datasets in order of first appearance in the file. Each dataset's
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
As :meth: |
ImportError
|
If the file is compressed with a codec that is not installed. |
load_from_dataframe(df)
¶
Load RTT data from a pandas DataFrame.
The frame is mapped through this loader's InputConfig (see
docs/INPUT_FORMATS.md); with the defaults: an epoch column with Unix
seconds (UTC) and one RTT column named values, rtt_value, rtt or
latency holding milliseconds; source and destination are optional.
Rows not matching input.series are left out first. Validation happens once,
on the whole frame (jitterbug.io.normalize):
- a missing column or a value that cannot be read in its unit raises
ValueError; - rows with a missing time or RTT are dropped; non-positive RTTs and RTTs above
MAX_RTT_MSare dropped (or rejected without_of_range: error); drops are counted inmetadata["dropped_rows"]; - rows are sorted by time (stable) if they are not already (or rejected with
unsorted: error); rows sharing a timestamp are handled byduplicates(kept by default).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing RTT data. |
required |
Returns:
| Type | Description |
|---|---|
RTTDataset
|
Loaded RTT dataset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a required column is missing, a value cannot be read, a policy set to
|
load_series_from_dataframe(df, skipped=None)
¶
Load a DataFrame as one dataset per series; see :meth:load_series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows, mapped through this loader's |
required |
skipped
|
dict[SeriesKey, str] | None
|
If given, receives the series whose rows were all dropped, with the reason. |
None
|
Returns:
| Type | Description |
|---|---|
dict[SeriesKey, RTTDataset]
|
Datasets in order of first appearance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
As :meth: |
read_raw_source(source, apply_series_filter=True)
¶
Run the query of a database source into raw rows, without normalizing them.
The counterpart of :meth:read_raw for databases, shared with
:meth:load_from_source, :meth:load_series_from_source and
jitterbug inspect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
Back end, connection settings (no secrets) and query. |
required |
apply_series_filter
|
bool
|
Whether to keep only the rows matching |
True
|
Returns:
| Type | Description |
|---|---|
tuple[RawData, InputConfig]
|
The result rows ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there is no query, or a |
ImportError
|
If the back end's client library is not installed. |
SourceError
|
If the connection or the query fails (the message is redacted). |
load_from_source(source)
¶
Load RTT data from a database query.
The result rows are mapped like a file's: input column mapping, units, row
policies, series filters; with group_by, they must form a single series.
Credentials come from environment variables (SourceConfig.secret_env).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
Back end, connection settings and query. |
required |
Returns:
| Type | Description |
|---|---|
RTTDataset
|
Loaded dataset; |
Raises:
| Type | Description |
|---|---|
ValueError
|
As :meth: |
ImportError
|
If the back end's client library is not installed. |
SourceError
|
If the connection or the query fails (the message is redacted). |
load_series_from_source(source, skipped=None)
¶
Load a database query as one dataset per series; see :meth:load_series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
Back end, connection settings and query. |
required |
skipped
|
dict[SeriesKey, str] | None
|
If given, receives the series whose rows were all dropped, with the reason. |
None
|
Returns:
| Type | Description |
|---|---|
dict[SeriesKey, RTTDataset]
|
Datasets in order of first appearance in the result. |
Raises:
| Type | Description |
|---|---|
ValueError
|
As :meth: |
ImportError
|
If the back end's client library is not installed. |
SourceError
|
If the connection or the query fails (the message is redacted). |
load_from_influxdb(url, token, org, bucket, query)
¶
Load RTT data directly from InfluxDB 2 with a Flux query.
Kept for existing callers; :meth:load_from_source with an influxdb2
SourceConfig does the same and reads the token from the environment. The
Flux columns _time and _value are used unless input maps others.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
InfluxDB URL. |
required |
token
|
str
|
InfluxDB token. |
required |
org
|
str
|
InfluxDB organization. |
required |
bucket
|
str
|
InfluxDB bucket (unused: the Flux query names it). |
required |
query
|
str
|
Flux query to execute. |
required |
Returns:
| Type | Description |
|---|---|
RTTDataset
|
Loaded RTT dataset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the result has no RTT column, or as :meth: |
ImportError
|
If |
SourceError
|
If the connection or the query fails (the message is redacted). |
validate_data(dataset)
¶
Validate RTT dataset and return quality metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
RTTDataset
|
Dataset to validate. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, any]
|
Validation results and quality metrics. |
jitterbug.io.normalize
¶
The single normalization path from raw rows to an RTTDataset.
Every reader (CSV, TSV, JSONL, scamper, ...) and DataLoader.load_from_dataframe
end here, so the input contract is enforced in one place. The steps, in order:
- Mapping. Find the time and RTT columns named by
InputConfig(the RTT column falls back to the synonymsvalues,rtt_value,rtt,latency). - Units. Convert times to Unix seconds (from
s,ms,us,ns, ISO 8601 strings, or a unit inferred byauto) and RTTs to milliseconds. A value that cannot be read in the given unit is an error. - Row policies. Drop rows with a missing time or RTT; drop (or reject) RTTs outside
(0, MAX_RTT_MS]; sort (or reject) rows out of time order; keep, thin out or reject rows that share a timestamp. Nothing is imputed or resampled.
Selecting series (InputConfig.series and group_by) happens before, on the raw
rows (jitterbug.io.series), so these steps apply to each series on its own. When
neither is set and the rows hold several paths (distinct (source, destination) pairs, or
the combinations of a format's path_keys), a warning says so.
TIME_UNIT_DIVISORS = {'s': 1.0, 'ms': 1000.0, 'us': 1000000.0, 'ns': 1000000000.0}
module-attribute
¶
Divide a numeric time in this unit by the value to get Unix seconds.
RTT_UNIT_SCALES = {'ms': (1.0, 1.0), 's': (1000.0, 1.0), 'us': (1.0, 1000.0), 'ns': (1.0, 1000000.0)}
module-attribute
¶
(multiplier, divisor) that turn an RTT in this unit into milliseconds. Dividing,
rather than multiplying by a fraction, keeps e.g. 1500 us at exactly 1.5 ms.
AUTO_TIME_UNIT_LIMITS = ((100000000000.0, 's'), (100000000000000.0, 'ms'), (1e+17, 'us'))
module-attribute
¶
time_unit: auto picks the first unit whose limit exceeds the median absolute time:
Unix seconds stay below 1e11 until the year 5138, milliseconds since 1973 are above it,
and each finer unit is 1000 times larger. Anything at or above 1e17 is nanoseconds.
EPOCH_RANGE = (datetime(1, 1, 2, tzinfo=UTC).timestamp(), datetime(9999, 12, 30, tzinfo=UTC).timestamp())
module-attribute
¶
Unix seconds a timestamp can hold (datetime years 1 to 9999, a day of margin on
each side for local-time conversions).
NoValidRowsError
¶
Bases: ValueError
Every row was dropped by the row policies (missing, non-positive or too large
RTTs). A ValueError, so callers that catch that keep working; per-series loading
uses it to skip one series instead of failing the whole input.
normalize(df, config=None, path_keys=())
¶
Turn a raw frame into a validated, time-ordered RTTDataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows, one RTT sample each, with column names as in the input. |
required |
config
|
InputConfig | None
|
Column mapping, units and row policies; |
None
|
path_keys
|
Sequence[str]
|
Key names that tell the input's paths apart ( |
()
|
Returns:
| Type | Description |
|---|---|
RTTDataset
|
The samples, with metadata describing what was done: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a column is missing, a value cannot be read in its unit, a policy set to
|
resolve_rtt_column(df, config)
¶
Return the name of the RTT column of df under config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
config
|
InputConfig
|
|
required |
Returns:
| Type | Description |
|---|---|
str
|
Column name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configured column, or every synonym, is missing. |
epoch_seconds(column, time_unit, name)
¶
Convert a time column to Unix seconds (floats, NaN where missing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
Series
|
Raw time values. |
required |
time_unit
|
str
|
One of |
required |
name
|
str
|
Column name, for messages. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Series, str]
|
Seconds since the epoch, and the unit that was applied (the inferred one for
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value cannot be read in the unit. |
infer_time_unit(column, name)
¶
Guess the unit of a time column (time_unit: auto).
Datetime values, and strings that are not numbers, are iso. Numbers are judged
by the median absolute value against AUTO_TIME_UNIT_LIMITS. The choice is logged
at INFO level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
Series
|
Raw time values. |
required |
name
|
str
|
Column name, for the log message. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
datetimes_to_epoch(times)
¶
Seconds since the Unix epoch for tz-aware UTC datetimes, whatever their resolution.
Rounded to microseconds like pd.Timestamp.timestamp(): a float64 epoch cannot
hold nanoseconds. NaT becomes NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
Series
|
|
required |
Returns:
| Type | Description |
|---|---|
Series
|
Float seconds. |
numeric_column(column, name, hint='')
¶
Return column as floats; NaN and blank strings become NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
Series
|
Raw values. |
required |
name
|
str
|
Column name, for messages. |
required |
hint
|
str
|
Appended to the error message. |
''
|
Returns:
| Type | Description |
|---|---|
Series
|
Float values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any other value is not numeric. |
jitterbug.io.series
¶
Series selection on raw rows: the series filters and group_by keys of
InputConfig.
Both work on the raw frame a reader returns, before normalization, so that the row
policies (duplicates, sorting) apply to each series on its own. A name in group_by
or series is resolved by :func:resolve_key_column: source and destination
stand for the mapped source_column and destination_column; any other name is a
raw column. Values are compared as text (:func:key_values).
SeriesKey = tuple[tuple[str, str | None], ...]
module-attribute
¶
Identifies one series: (name, value) pairs in group_by order, e.g.
(("destination", "8.8.8.8"),). A missing value is None. The empty tuple is the
whole input (no group_by).
MAX_LISTED_VALUES = 20
module-attribute
¶
Error messages list at most this many available values or keys.
resolve_key_column(name, config)
¶
Return the raw column a group_by or series name refers to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
required |
config
|
InputConfig
|
Supplies |
required |
Returns:
| Type | Description |
|---|---|
str
|
The column name in the raw frame. |
key_values(df, name, config)
¶
Return the values of a key column as text (None where missing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
name
|
str
|
|
required |
config
|
InputConfig
|
Column mapping. |
required |
Returns:
| Type | Description |
|---|---|
Series
|
Object series aligned with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the column does not exist. |
format_series_key(key)
¶
Render a series key as name=value pairs, the syntax of --series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
SeriesKey
|
The key. |
required |
Returns:
| Type | Description |
|---|---|
str
|
E.g. |
series_key_dict(key)
¶
Return a series key as a {name: value} mapping (the form written to JSON).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
SeriesKey
|
The key. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str | None]
|
Names in |
filter_rows(df, config)
¶
Keep the rows that match every config.series filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
config
|
InputConfig
|
|
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The matching rows ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a filter names a column that does not exist, or no row matches; the message lists the values the column does have among the rows the earlier filters kept. |
split_series(df, config)
¶
Split raw rows by config.group_by.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows (already filtered by :func: |
required |
config
|
InputConfig
|
|
required |
Returns:
| Type | Description |
|---|---|
dict[SeriesKey, DataFrame]
|
One frame per distinct key, in order of first appearance; rows keep their file
order. Without |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a |
describe_keys(keys)
¶
List series keys for an error or log message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[SeriesKey]
|
Keys. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
count_source_destination_pairs(df, config)
¶
Count the distinct (source, destination) pairs of raw rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
config
|
InputConfig
|
Column mapping; an absent source or destination column counts as one value. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of distinct pairs (0 for an empty frame). |
path_key_names(df, config, path_keys=())
¶
Return the key names that tell the paths of raw rows apart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
config
|
InputConfig
|
Column mapping, for |
required |
path_keys
|
Sequence[str]
|
Names a format declares for its paths ( |
()
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The names among those whose column is present, usable as |
count_paths(df, config, names)
¶
Count the distinct combinations of the names key columns among raw rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Raw rows. |
required |
config
|
InputConfig
|
Column mapping, for |
required |
names
|
Sequence[str]
|
Key names whose columns are present (see :func: |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of distinct combinations (0 for an empty frame, 1 without names). |
series_flags(names)
¶
Return the --series flags that keep one path, one per key name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
Sequence[str]
|
Key names (see :func: |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
jitterbug.io.inspection
¶
A dry run of ingestion: what loading a file or a database query would do, without analyzing anything.
:func:inspect_file reads a file with the same reader, column mapping, units and row
policies as :meth:jitterbug.io.DataLoader.load_from_file, but instead of building a
dataset it reports the format, the mapping in effect, how many rows each policy would
drop or reorder, and the series the file holds. It never raises for a policy set to
error: it says the load would fail and why. :func:inspect_source does the same for
a database query. jitterbug inspect prints these reports.
inspect_file(file_path, file_format=None, input_config=None)
¶
Report what loading file_path would do, without analyzing it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Input file (possibly compressed). |
required |
file_format
|
str | None
|
A registered format, or |
None
|
input_config
|
InputConfig | None
|
Mapping, units, row policies, |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
JSON-serializable report with the keys:
When a |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the format is unknown or the file cannot be read at all. |
inspect_source(source, input_config=None)
¶
Report what loading a database query would do, without analyzing it.
The query runs (it is the only way to see its columns), then the rows are examined
as :func:inspect_file examines a file's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
Back end, connection settings and query. |
required |
input_config
|
InputConfig | None
|
Mapping, units, row policies, |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The keys of :func: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there is no query. |
ImportError
|
If the back end's client library is not installed. |
SourceError
|
If the connection or the query fails (the message is redacted). |
jitterbug.io.readers.base
¶
The reader registry: one small reader per file format.
A reader turns a file into a raw pandas.DataFrame and nothing more; column mapping,
units and row policies are applied afterwards by :func:jitterbug.io.normalize.normalize.
Adding a format is one module that calls :func:register_reader.
MAGIC_SIZE = 8
module-attribute
¶
Bytes read from the start of a file to match Reader.magic.
RawData
dataclass
¶
What a reader returns.
Attributes:
| Name | Type | Description |
|---|---|---|
frame |
DataFrame
|
Raw rows, column names as in the file. |
metadata |
dict[str, Any]
|
Merged into the dataset metadata after normalization ( |
schema |
dict[str, Any]
|
|
finish |
Callable[[RTTDataset], None] | None
|
Called on the normalized dataset, e.g. to add format-specific metadata. |
path_keys |
list[str]
|
Key names (as in |
Reader
dataclass
¶
A registered file format.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Format name, as passed to |
label |
str
|
Human-readable name for messages ( |
read |
ReadFunction
|
|
extensions |
tuple[str, ...]
|
Lower-case suffixes that select this format ( |
sniff |
SniffFunction | None
|
Given the first non-empty line of a file with an unknown extension, whether it looks like this format. Readers are tried in registration order. |
magic |
tuple[bytes, ...]
|
Byte prefixes that identify a binary format ( |
register_reader(reader)
¶
available_formats()
¶
Return the registered format names, in registration order.
Returns:
| Type | Description |
|---|---|
list[str]
|
E.g. |
get_reader(name)
¶
Return the reader registered as name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Format name. |
required |
Returns:
| Type | Description |
|---|---|
Reader
|
The reader. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no reader has that name. |
first_line(path, max_lines=100)
¶
Return the first non-empty line of a (possibly compressed) text file, stripped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path. |
required |
max_lines
|
int
|
Give up after this many blank lines. |
100
|
Returns:
| Type | Description |
|---|---|
str
|
The line, or |
infer_format(path)
¶
Pick the format of path: by extension (ignoring a compression suffix), otherwise
by the magic bytes of a binary format, otherwise by sniffing its first non-empty line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A registered format name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be read as text or no reader recognizes it. |
ImportError
|
If the file is compressed with a codec that is not installed. |
magic_format(path)
¶
Return the binary format whose magic bytes start the content of path.
The raw bytes are checked first; for a compressed file, the decompressed ones too, so
that data.gz holding Parquet is recognized (its reader then rejects the outer
compression) instead of being decoded as text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
A registered format name, or |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the file is compressed with a codec that is not installed. |
jitterbug.io.sources.base
¶
The source registry: one small module per database back end.
A back end runs a query and returns a raw pandas.DataFrame, nothing more, like a
file reader. :func:fetch_raw wraps it: it reads the secret from the environment, runs
the query, redacts any error, reads datetime columns as datetimes, applies the back
end's default column names, and returns :class:~jitterbug.io.readers.RawData that
then goes through the same series selection and normalization as a file.
QuerySource
dataclass
¶
A registered database back end.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
label |
str
|
Human-readable name for messages ( |
fetch |
FetchFunction
|
|
time_column |
str | None
|
Name the back end gives the sample time ( |
rtt_column |
str | None
|
Column used as the RTT when |
path_keys |
tuple[str, ...]
|
Key names that tell paths apart in the back end's results ( |
register_source(source)
¶
Add a back end to the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
QuerySource
|
The back end. |
required |
Returns:
| Type | Description |
|---|---|
QuerySource
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the kind is already registered. |
available_sources()
¶
Return the registered source kinds.
Returns:
| Type | Description |
|---|---|
list[str]
|
E.g. |
get_source(kind)
¶
Return the back end registered as kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
Source kind. |
required |
Returns:
| Type | Description |
|---|---|
QuerySource
|
The back end. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no back end has that kind. |
import_client(module, extra, package)
¶
Import a client library, or raise an ImportError naming the extra to install.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
Import name ( |
required |
extra
|
str
|
The |
required |
package
|
str
|
Its PyPI distribution, for the message. |
required |
Returns:
| Type | Description |
|---|---|
ModuleType
|
The module. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If it is not installed. |
query_text(source)
¶
The query to run: source.query, or the content of source.query_file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
The source. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Query text, stripped. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither is set, the query is empty, or the file cannot be read. |
describe_source(source)
¶
Connection details of source safe to record and display (never a secret).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
The source. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
fetch_raw(source, config)
¶
Run the query of source and return its rows as raw data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
Back end, connection settings and query. |
required |
config
|
InputConfig
|
Input settings: the default column names of the back end apply only where these are left at their defaults, and a datetime time column is read as datetimes. |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If there is no query or it cannot be read. |
ImportError
|
If the back end's client library is not installed. |
SourceError
|
If the connection or the query fails; the message is redacted. |
run_redacted(label, call, secrets)
¶
Run a client call; any error but a missing library becomes a redacted SourceError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Back end name for the message ( |
required |
call
|
Callable[[], DataFrame]
|
Connects, queries and closes. |
required |
secrets
|
list[str | None]
|
Values to scrub from the message, besides the generic credential patterns. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
What |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the client library is missing (the message names the extra). |
SourceError
|
For any other failure. The client's exception is not chained, since it may quote the secret. |
raw_from_result(frame, config, backend, metadata)
¶
Wrap a query result as raw data, with the schema the result decides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Result rows. |
required |
config
|
InputConfig
|
Input settings. |
required |
backend
|
QuerySource
|
The back end, for its default column names. |
required |
metadata
|
dict[str, Any]
|
Recorded in the dataset metadata. |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The rows, metadata, schema and path keys. |
jitterbug.io.sources.uri
¶
Source URIs: a database source written where a file path would go.
Forms (credentials are rejected; see docs/DATA_SOURCES.md):
clickhouse://[user@]host[:port][/database];clickhouses://connects over HTTPS;influxdb2://host[:port]?org=ORG(Flux);influxdb2s://over HTTPS;influxdb3://host[:port]/database[?language=influxql](SQL by default);influxdb3s://over HTTPS;duckdb:orduckdb://(in-memory),duckdb:///absolute/path.db,duckdb:relative/path.db;?read_only=falseopens a file for writing.
SCHEMES = {'clickhouse': ('clickhouse', False), 'clickhouses': ('clickhouse', True), 'influxdb2': ('influxdb2', False), 'influxdb2s': ('influxdb2', True), 'influxdb3': ('influxdb3', False), 'influxdb3s': ('influxdb3', True), 'duckdb': ('duckdb', False)}
module-attribute
¶
URI scheme -> (source kind, secure).
uri_scheme(text)
¶
The lower-case scheme of text if it is a source URI scheme, else None.
influxdb is reported too, so that it can be rejected with a helpful message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A command-line input argument. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The scheme, or |
is_source_uri(text)
¶
Whether text is written as a database source URI rather than a file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A command-line input argument. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
parse_source_uri(uri)
¶
Turn a source URI into a SourceConfig without a query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
A URI of one of the forms listed in this module's docstring. |
required |
Returns:
| Type | Description |
|---|---|
SourceConfig
|
Connection settings; the query is set separately ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the scheme is not a source scheme, the URI holds a password or token, or a part does not apply to the kind. Messages never repeat a secret. |
jitterbug.io.sources.credentials
¶
Secrets of database sources: read from the environment, kept out of every message.
Passwords and tokens are never part of a SourceConfig; :func:read_secret takes
them from the environment when a query runs. Errors raised by the client libraries can
quote connection strings or headers, so :func:redact scrubs the secret itself and the
usual credential patterns from any text before it reaches a log, an exception or a
report.
REDACTED = '***'
module-attribute
¶
What a secret is replaced with.
SourceError
¶
Bases: RuntimeError
A database source could not be read. The message has been redacted, and the client library's exception is not chained (it may hold the secret).
RedactingFilter
¶
Bases: Filter
A logging filter that redacts records before a handler writes them.
Client libraries log on their own (clickhouse-connect logs transport errors with
their traceback); attached to a handler, this filter scrubs every secret read by
:func:read_secret and the generic credential patterns of :func:redact from the
message and the formatted traceback. jitterbug commands install it on the root
handlers; library users can do the same.
filter(record)
¶
Redact record in place; never drops it.
read_secret(source)
¶
Read the password or token of source from its environment variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
SourceConfig
|
The source; |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The secret, or |
redact(text, secrets=())
¶
Remove secrets from text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A message, typically from a client library's exception. |
required |
secrets
|
Iterable[str | None]
|
Known secret values to replace wherever they appear; |
()
|
Returns:
| Type | Description |
|---|---|
str
|
|
install_redacting_filter(logger=None)
¶
Add a :class:RedactingFilter to every handler of logger (the root by default,
plus logging.lastResort) that does not have one yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
Logger | None
|
Logger whose handlers to filter. |
None
|
jitterbug.io.readers.delimited
¶
CSV-like readers: csv (comma, tab or semicolon, detected) and tsv (tab).
DELIMITERS = (',', '\t', ';')
module-attribute
¶
Separators detect_delimiter chooses from, in order of preference on ties.
detect_delimiter(header)
¶
Pick the field separator of a header line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header
|
str
|
First non-empty line of the file. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The one of |
read_csv(path, config)
¶
Read a delimited file with a header row; the separator is config.delimiter or
detected from the header (comma, tab or semicolon).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path (possibly compressed). |
required |
config
|
InputConfig
|
Input settings; only |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The raw frame; |
read_tsv(path, config)
¶
Read a tab-separated file with a header row (config.delimiter overrides the tab).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path (possibly compressed). |
required |
config
|
InputConfig
|
Input settings; only |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The raw frame; |
jitterbug.io.readers.jsonl
¶
JSON readers: scamper (scamper -O json output), jsonl (one flat object per
line, mapped through InputConfig), and json, which looks at the records and picks
one of those two or atlas (RIPE Atlas results, :mod:jitterbug.io.readers.atlas).
A file is either JSON lines or one JSON array of records (see
:func:jitterbug.io.readers.json_records.parse_json_records). Telling the record kinds
apart, in this order:
- scamper output when at least one record is a scamper
ping("type": "ping"with aresponsesfield) or one of scamper's bookkeeping records ("type"list,cycle-def,cycle-startorcycle-stop); - RIPE Atlas results when at least one record has the
prb_id,msm_idandresultfields every Atlas result carries; - generic JSONL otherwise.
A type field alone is not enough: scamper and RIPE Atlas both write
"type": "ping", and so may anything else.
SCAMPER_BOOKKEEPING_TYPES = frozenset({'list', 'cycle-def', 'cycle-start', 'cycle-stop'})
module-attribute
¶
Record types scamper writes around its measurements.
SCAMPER_SCHEMA = {'time_column': 'epoch', 'time_unit': 's', 'rtt_column': 'rtt', 'rtt_unit': 'ms', 'source_column': 'source', 'destination_column': 'destination'}
module-attribute
¶
The frame the scamper reader builds is in this fixed schema, whatever the user's column and unit settings are.
is_scamper_record(record)
¶
Return whether a parsed JSON line is a scamper record (see the module docstring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
Any
|
One parsed line. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
read_scamper(path, config)
¶
Read scamper JSON output (scamper -O json, sc_warts2json).
Only ping records are used: each response with an rtt (milliseconds) and a
tx time becomes a row, with src/dst as source and destination. Other
records, timeouts and invalid JSON lines are skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path (possibly compressed). |
required |
config
|
InputConfig
|
Unused: the scamper schema is fixed ( |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The raw frame in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be read or holds no usable response. |
read_jsonl(path, config)
¶
Read generic JSON lines: one flat object per line (or a JSON array of flat objects),
fields mapped through InputConfig like CSV columns. Invalid JSON lines are
skipped with a warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path (possibly compressed). |
required |
config
|
InputConfig
|
Unused here; the mapping happens during normalization. |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The raw frame. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be read, a line is not a JSON object, or there is no record. |
read_json(path, config)
¶
Read JSON lines (or a JSON array of records) as scamper output, RIPE Atlas results or generic JSONL, decided by content (see the module docstring). A file with no records at all is treated as scamper output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
File path (possibly compressed). |
required |
config
|
InputConfig
|
Input settings. |
required |
Returns:
| Type | Description |
|---|---|
RawData
|
The raw frame; |
jitterbug.io.exporters
¶
Result export utilities.
JSON and CSV outputs are compressed when the path ends in .zst, .gz, .bz2 or
.xz (results.json.zst); see :mod:jitterbug.io.compression.
ResultExporter
¶
Exporter for analysis results to various formats.
export_to_json(results, output_path, pretty=True)
¶
Export results to JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
CongestionInferenceResult
|
Analysis results to export. |
required |
output_path
|
Union[str, Path]
|
Path to save JSON file; compressed if it ends in |
required |
pretty
|
bool
|
Whether to format JSON with indentation. |
True
|
export_to_csv(results, output_path)
¶
Export results to CSV format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
CongestionInferenceResult
|
Analysis results to export. |
required |
output_path
|
Union[str, Path]
|
Path to save CSV file; compressed if it ends in |
required |
export_to_parquet(results, output_path)
¶
Export results to Parquet format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
CongestionInferenceResult
|
Analysis results to export. |
required |
output_path
|
Union[str, Path]
|
Path to save Parquet file. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
export_summary(results, output_path)
¶
Export summary statistics to JSON format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
CongestionInferenceResult
|
Analysis results to export. |
required |
output_path
|
Union[str, Path]
|
Path to save summary JSON file; compressed if it ends in |
required |
reject_compressed_parquet(output_path)
¶
Raise ValueError for compressed (*.zst, *.gz, ...) Parquet output, which
would compress twice.
jitterbug.io.compression
¶
Transparent compression for input and output files.
A path whose last suffix is .zst, .gz, .bz2 or .xz (rtts.csv.gz,
results.json.zst) is read and written through the matching codec; any other path is
a plain file. gzip, bzip2 and xz use the standard library. The Zstandard codec is the
standard library's compression.zstd on Python 3.14 and later, otherwise the
zstandard package (the zstd extra).
COMPRESSION_SUFFIXES = {'.zst': 'zstd', '.gz': 'gzip', '.bz2': 'bzip2', '.xz': 'xz'}
module-attribute
¶
Compressed-file suffixes and the codec each one names.
is_zstd(path)
¶
Return whether path names a Zstandard-compressed file (last suffix .zst).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
compression_of(path)
¶
Return the codec named by the last suffix of path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
|
is_compressed(path)
¶
Return whether path names a compressed file (see COMPRESSION_SUFFIXES).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
inner_suffix(path)
¶
Return the suffix that describes the content, ignoring a compression suffix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Lower-case suffix, e.g. |
open_text(path, mode='r', newline=None)
¶
Open a text file, through a decompressing stream when path is compressed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
mode
|
str
|
|
'r'
|
newline
|
str | None
|
Passed to the text layer, as in :func: |
None
|
Returns:
| Type | Description |
|---|---|
IO[str]
|
Text stream; use it as a context manager. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If |
read_head(path, size=16)
¶
Return the first bytes of a file's content, decompressed when path is compressed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path. |
required |
size
|
int
|
Number of bytes to read at most. |
16
|
Returns:
| Type | Description |
|---|---|
bytes
|
Up to |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
Notes
Errors reading the file or decoding it with its codec propagate unchanged.