mesh-things 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mesh_things/__init__.py +3 -0
- mesh_things/archive.py +39 -0
- mesh_things/catalog.py +40 -0
- mesh_things/channels.py +134 -0
- mesh_things/client/__init__.py +36 -0
- mesh_things/client/_client.py +308 -0
- mesh_things/client/_core.py +189 -0
- mesh_things/client/_helpers.py +64 -0
- mesh_things/client/_namespaces.pyi +2305 -0
- mesh_things/client/_stubgen.py +71 -0
- mesh_things/client/errors.py +101 -0
- mesh_things/client/openapi.json +9918 -0
- mesh_things/client/schema.py +106 -0
- mesh_things/codec.py +173 -0
- mesh_things/detectors.py +171 -0
- mesh_things/env.py +38 -0
- mesh_things/exports.py +13 -0
- mesh_things/influx_query.py +112 -0
- mesh_things/node_ids.py +22 -0
- mesh_things/pandas.py +137 -0
- mesh_things/portnum_registry.py +49 -0
- mesh_things/portnums.py +12 -0
- mesh_things/protobuf.py +71 -0
- mesh_things/py.typed +0 -0
- mesh_things/streams.py +6 -0
- mesh_things/timestamps.py +19 -0
- mesh_things/units.py +57 -0
- mesh_things-0.1.0.dist-info/METADATA +195 -0
- mesh_things-0.1.0.dist-info/RECORD +31 -0
- mesh_things-0.1.0.dist-info/WHEEL +4 -0
- mesh_things-0.1.0.dist-info/licenses/LICENSE +674 -0
mesh_things/__init__.py
ADDED
mesh_things/archive.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""A mesh's Parquet archive, read straight from S3. Needs mesh-things[archive]."""
|
|
2
|
+
try:
|
|
3
|
+
import pyarrow.dataset as ds
|
|
4
|
+
import pyarrow.fs as fs
|
|
5
|
+
except ImportError as error:
|
|
6
|
+
raise ImportError("mesh_things.archive needs pyarrow: pip install 'mesh-things[archive]'") from error
|
|
7
|
+
|
|
8
|
+
from mesh_things.client._core import require_secure, resolve_allow_insecure_http
|
|
9
|
+
from mesh_things.client._helpers import ARCHIVE_CREDENTIALS
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def dataset(credentials: dict, *, allow_insecure_http: bool | None = None) -> ds.Dataset:
|
|
13
|
+
"""The archive the temporary `credentials` grant, as a Hive-partitioned dataset.
|
|
14
|
+
|
|
15
|
+
`dt` and `hour` come back as columns and prune whole files when filtered on. An
|
|
16
|
+
`http://` endpoint other than this machine raises `InsecureTransport` unless
|
|
17
|
+
allowed, as in `MeshThings`.
|
|
18
|
+
"""
|
|
19
|
+
options = {
|
|
20
|
+
"access_key": credentials["access_key_id"],
|
|
21
|
+
"secret_key": credentials["secret_access_key"],
|
|
22
|
+
"session_token": credentials["session_token"],
|
|
23
|
+
"region": credentials["region"],
|
|
24
|
+
}
|
|
25
|
+
# A null endpoint means AWS, which pyarrow reaches on its own.
|
|
26
|
+
if credentials["endpoint"]:
|
|
27
|
+
allowed = resolve_allow_insecure_http(allow_insecure_http)
|
|
28
|
+
require_secure(credentials["endpoint"], "the archive's S3 credentials", allowed)
|
|
29
|
+
scheme, host = credentials["endpoint"].split("://", 1)
|
|
30
|
+
options.update({"endpoint_override": host, "scheme": scheme})
|
|
31
|
+
s3 = fs.S3FileSystem(**options)
|
|
32
|
+
# The credentials can list this mesh's prefix only, so the dataset starts there.
|
|
33
|
+
root = f"{credentials['bucket']}/{credentials['prefix'].rstrip('/')}"
|
|
34
|
+
return ds.dataset(root, filesystem=s3, format="parquet", partitioning="hive")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def open_dataset(api, mesh_id: str) -> ds.Dataset:
|
|
38
|
+
"""Request temporary credentials for a mesh's archive and open it. Operators only."""
|
|
39
|
+
return dataset(api.call(ARCHIVE_CREDENTIALS, mesh_id), allow_insecure_http=api.allow_insecure_http)
|
mesh_things/catalog.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""The telemetry channels the Meshtastic `Telemetry` protobuf can carry."""
|
|
2
|
+
from typing import Iterator, NamedTuple
|
|
3
|
+
|
|
4
|
+
from google.protobuf.descriptor import FieldDescriptor
|
|
5
|
+
from meshtastic.protobuf import telemetry_pb2
|
|
6
|
+
|
|
7
|
+
from mesh_things.channels import TELEMETRY
|
|
8
|
+
|
|
9
|
+
_SKIP_CPP_TYPES = (FieldDescriptor.CPPTYPE_STRING, FieldDescriptor.CPPTYPE_MESSAGE)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TelemetryVariant(NamedTuple):
|
|
13
|
+
payload_kind: str
|
|
14
|
+
message_name: str
|
|
15
|
+
field_names: tuple[str, ...]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def is_catalogued(field: FieldDescriptor) -> bool:
|
|
19
|
+
"""Whether a protobuf field is one numeric channel.
|
|
20
|
+
|
|
21
|
+
Repeated numerics arrive as a list, so nothing downstream can write them.
|
|
22
|
+
"""
|
|
23
|
+
if field.cpp_type in _SKIP_CPP_TYPES:
|
|
24
|
+
return False
|
|
25
|
+
# protobuf >= 6 dropped FieldDescriptor.label in favour of is_repeated.
|
|
26
|
+
is_repeated = getattr(field, "is_repeated", None)
|
|
27
|
+
if is_repeated is None:
|
|
28
|
+
is_repeated = field.label == FieldDescriptor.LABEL_REPEATED
|
|
29
|
+
return not is_repeated
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def telemetry_variants() -> Iterator[TelemetryVariant]:
|
|
33
|
+
"""Each `Telemetry.variant` and its catalogued fields, in schema order."""
|
|
34
|
+
for variant_field in telemetry_pb2.Telemetry.DESCRIPTOR.oneofs_by_name["variant"].fields:
|
|
35
|
+
message = variant_field.message_type
|
|
36
|
+
yield TelemetryVariant(
|
|
37
|
+
payload_kind=f"{TELEMETRY}:{variant_field.name}",
|
|
38
|
+
message_name=message.name,
|
|
39
|
+
field_names=tuple(f.name for f in message.fields if is_catalogued(f)),
|
|
40
|
+
)
|
mesh_things/channels.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Channel naming convention: "<measurement>.<field>".
|
|
2
|
+
|
|
3
|
+
A *channel* is one addressable timeseries.
|
|
4
|
+
This vocabulary is shared by (all need to be the same):
|
|
5
|
+
|
|
6
|
+
- blueprint inputs/outputs (registry's PostprocessingStep)
|
|
7
|
+
- quality thresholds (mesh.quality_config.v1's key)
|
|
8
|
+
- the streams per-channel keying (flink/pattern_detection_job.py)
|
|
9
|
+
- the batches (quality_worker/influx_io.py)
|
|
10
|
+
|
|
11
|
+
Naming must be the same as writer/point_builders.py, which is what defines
|
|
12
|
+
the InfluxDB measurement name. Each telemetry sub-metric dict becomes its own
|
|
13
|
+
measurement, and everything else uses its payload kind.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
# A payload_kind is always "<namespace>:<measurement>".
|
|
17
|
+
# The measurement half is the InfluxDB measurement name
|
|
18
|
+
TELEMETRY = "telemetry" # a sensor reading
|
|
19
|
+
DEVICE = "device" # the device describing itself
|
|
20
|
+
COMPUTED = "computed" # produced by this pipeline
|
|
21
|
+
|
|
22
|
+
# The measurement bit for everything that is NOT a telemetry variant. Telemetry
|
|
23
|
+
# variants are dynamic (one per Telemetry sub-metric), so they are not listed.
|
|
24
|
+
# These must match writer/point_builders.py, which is what names each measurement.
|
|
25
|
+
DERIVED = "derived" # all blueprint outputs, attributed by the point's blueprint_id tag
|
|
26
|
+
QUALITY = "quality"
|
|
27
|
+
ALARMS = "alarms"
|
|
28
|
+
POSITION = "position" # Not telemetry, but coming from the device
|
|
29
|
+
NODEINFO = "nodeinfo" # Not telemetry
|
|
30
|
+
PORTNUM_PREFIX = "portnum_" # an undecoded portnum, e.g. portnum_67
|
|
31
|
+
|
|
32
|
+
DEVICE_MEASUREMENTS = frozenset({POSITION, NODEINFO})
|
|
33
|
+
COMPUTED_MEASUREMENTS = frozenset({DERIVED, QUALITY, ALARMS})
|
|
34
|
+
|
|
35
|
+
# The full payload_kinds that are fixed rather than per-variant.
|
|
36
|
+
DERIVED_KIND = f"{COMPUTED}:{DERIVED}"
|
|
37
|
+
QUALITY_KIND = f"{COMPUTED}:{QUALITY}"
|
|
38
|
+
ALARMS_KIND = f"{COMPUTED}:{ALARMS}"
|
|
39
|
+
POSITION_KIND = f"{DEVICE}:{POSITION}"
|
|
40
|
+
NODEINFO_KIND = f"{DEVICE}:{NODEINFO}"
|
|
41
|
+
|
|
42
|
+
# channel_origins
|
|
43
|
+
# The producer of a value. Part of the namespace, and exposed on the API.
|
|
44
|
+
ORIGIN_MEASURED = "measured"
|
|
45
|
+
ORIGIN_DEVICE = "device"
|
|
46
|
+
ORIGIN_COMPUTED = "computed"
|
|
47
|
+
ORIGIN_OTHER = "other"
|
|
48
|
+
|
|
49
|
+
def channel_name(payload_kind: str, field_name: str) -> str:
|
|
50
|
+
"""Gets the channel name for a payload_kind and field name
|
|
51
|
+
|
|
52
|
+
Example:
|
|
53
|
+
channel_name("telemetry:environment_metrics", "temperature")
|
|
54
|
+
-> "environment_metrics.temperature".
|
|
55
|
+
"""
|
|
56
|
+
return f"{measurement_of(payload_kind)}.{field_name}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def measurement_of(payload_kind: str) -> str:
|
|
60
|
+
"""The InfluxDB measurement a payload_kind is stored under.
|
|
61
|
+
|
|
62
|
+
Storage drops the namespace: telemetry:environment_metrics -> environment_metrics.
|
|
63
|
+
"""
|
|
64
|
+
return (payload_kind or "unknown").split(":", 1)[-1]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def payload_kind_of_measurement(measurement: str) -> str:
|
|
68
|
+
"""The payload_kind an InfluxDB measurement was written from.
|
|
69
|
+
|
|
70
|
+
Inverse of measurement_of: storage keeps only the measurement half, so the
|
|
71
|
+
namespace has to be put back on. Anything not named here is a telemetry
|
|
72
|
+
variant, since those are dynamic.
|
|
73
|
+
"""
|
|
74
|
+
return f"{namespace_of_measurement(measurement)}:{measurement}"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def namespace_of_measurement(measurement: str) -> str:
|
|
78
|
+
"""Return the producer, of the three, that an InfluxDB measurement came from."""
|
|
79
|
+
if measurement in COMPUTED_MEASUREMENTS:
|
|
80
|
+
return COMPUTED
|
|
81
|
+
if measurement in DEVICE_MEASUREMENTS or measurement.startswith(PORTNUM_PREFIX):
|
|
82
|
+
return DEVICE
|
|
83
|
+
return TELEMETRY
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def split_channel(channel: str) -> tuple[str, str]:
|
|
87
|
+
"""Inverse of channel_name: "environment_metrics.temperature" -> the pair."""
|
|
88
|
+
measurement, _, field = (channel or "").partition(".")
|
|
89
|
+
if not measurement or not field:
|
|
90
|
+
raise ValueError(f"Invalid channel: {channel!r}, expected '<measurement>.<field>'")
|
|
91
|
+
return measurement, field
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def namespace_of(payload_kind: str) -> str:
|
|
95
|
+
"""The part before the colon, or the whole thing when ""."""
|
|
96
|
+
return (payload_kind or "").split(":", 1)[0]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def origin_of(payload_kind: str) -> str:
|
|
100
|
+
"""Return the origin of a value, from the payload_kind's namespace."""
|
|
101
|
+
return {
|
|
102
|
+
TELEMETRY: ORIGIN_MEASURED,
|
|
103
|
+
DEVICE: ORIGIN_DEVICE,
|
|
104
|
+
COMPUTED: ORIGIN_COMPUTED,
|
|
105
|
+
}.get(namespace_of(payload_kind), ORIGIN_OTHER)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def origin_of_measurement(measurement: str) -> str:
|
|
109
|
+
"""Get origin of an InfluxDB measurement"""
|
|
110
|
+
return origin_of(payload_kind_of_measurement(measurement))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def channels_in(payload_kind: str, payload: dict):
|
|
114
|
+
"""Yield ("<measurement>.<field>", value) for every numeric value of a
|
|
115
|
+
decoded payload, matching build_telemetry_points' measurement choice."""
|
|
116
|
+
fallback = (payload_kind or "unknown").split(":", 1)[-1]
|
|
117
|
+
for key, value in (payload or {}).items():
|
|
118
|
+
if key == "time":
|
|
119
|
+
continue
|
|
120
|
+
if isinstance(value, dict):
|
|
121
|
+
for field, leaf in numeric_leaves(value):
|
|
122
|
+
yield f"{key}.{field}", leaf
|
|
123
|
+
elif isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
124
|
+
yield f"{fallback}.{key}", value
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def numeric_leaves(d: dict):
|
|
128
|
+
"""Recursive numeric-leaf walk.
|
|
129
|
+
bools are excluded."""
|
|
130
|
+
for key, value in d.items():
|
|
131
|
+
if isinstance(value, dict):
|
|
132
|
+
yield from numeric_leaves(value)
|
|
133
|
+
elif isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
134
|
+
yield key, value
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Access to the mesh-things API, bound to the OpenAPI snapshot shipped beside it."""
|
|
2
|
+
from ._client import AsyncMeshThings, MeshThings, Namespace
|
|
3
|
+
from ._core import MeshThingsVersionWarning
|
|
4
|
+
from ._helpers import terms_fields
|
|
5
|
+
from .errors import (
|
|
6
|
+
ApiError,
|
|
7
|
+
Conflict,
|
|
8
|
+
ExportFailed,
|
|
9
|
+
ExportInProgress,
|
|
10
|
+
Forbidden,
|
|
11
|
+
InsecureTransport,
|
|
12
|
+
NotFound,
|
|
13
|
+
ServerError,
|
|
14
|
+
Throttled,
|
|
15
|
+
Unauthorized,
|
|
16
|
+
ValidationFailed,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ApiError",
|
|
21
|
+
"AsyncMeshThings",
|
|
22
|
+
"Conflict",
|
|
23
|
+
"ExportFailed",
|
|
24
|
+
"ExportInProgress",
|
|
25
|
+
"Forbidden",
|
|
26
|
+
"InsecureTransport",
|
|
27
|
+
"MeshThings",
|
|
28
|
+
"MeshThingsVersionWarning",
|
|
29
|
+
"Namespace",
|
|
30
|
+
"NotFound",
|
|
31
|
+
"ServerError",
|
|
32
|
+
"Throttled",
|
|
33
|
+
"Unauthorized",
|
|
34
|
+
"ValidationFailed",
|
|
35
|
+
"terms_fields",
|
|
36
|
+
]
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""The sync and async clients, with one namespace per API tag and one method per operation."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import AsyncIterator, Iterator
|
|
5
|
+
from datetime import date
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from . import _core, _helpers
|
|
12
|
+
from .errors import NotFound, Throttled
|
|
13
|
+
from .schema import Operation, operations
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from ._namespaces import AsyncNamespaces, SyncNamespaces
|
|
17
|
+
else:
|
|
18
|
+
AsyncNamespaces = SyncNamespaces = object
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Namespace:
|
|
22
|
+
"""The operations of one API tag, for example `meshes`."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, name: str):
|
|
25
|
+
self._name = name
|
|
26
|
+
|
|
27
|
+
def __repr__(self) -> str:
|
|
28
|
+
methods = sorted(m for m in vars(self) if not m.startswith("_"))
|
|
29
|
+
return f"<{self._name}: {', '.join(methods)}>"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _Client:
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
base_url: str | None,
|
|
36
|
+
api_key: str | None,
|
|
37
|
+
readings_url: str | None,
|
|
38
|
+
retries: int,
|
|
39
|
+
allow_insecure_http: bool | None,
|
|
40
|
+
):
|
|
41
|
+
self.base_url = _core.resolve_base_url(base_url)
|
|
42
|
+
self.readings_url = readings_url.rstrip("/") if readings_url else None
|
|
43
|
+
self.retries = retries
|
|
44
|
+
self.allow_insecure_http = _core.resolve_allow_insecure_http(allow_insecure_http)
|
|
45
|
+
key = _core.resolve_api_key(api_key)
|
|
46
|
+
if key:
|
|
47
|
+
for url in filter(None, (self.base_url, self.readings_url)):
|
|
48
|
+
_core.require_secure(url, "the API key", self.allow_insecure_http)
|
|
49
|
+
self._headers = {"Authorization": f"Bearer {key}"} if key else {}
|
|
50
|
+
self._versions_warned: set[str] = set()
|
|
51
|
+
namespaces: dict[str, Namespace] = {}
|
|
52
|
+
for op in operations().values():
|
|
53
|
+
if op.namespace not in namespaces:
|
|
54
|
+
namespaces[op.namespace] = Namespace(op.namespace)
|
|
55
|
+
setattr(self, op.namespace, namespaces[op.namespace])
|
|
56
|
+
setattr(namespaces[op.namespace], op.name, self._bind(op))
|
|
57
|
+
|
|
58
|
+
def _bind(self, op: Operation) -> Callable[..., Any]:
|
|
59
|
+
raise NotImplementedError
|
|
60
|
+
|
|
61
|
+
def _prepare(self, operation_id: str, args: tuple, kwargs: dict):
|
|
62
|
+
op = operations()[operation_id]
|
|
63
|
+
_core.warn_if_deprecated(op)
|
|
64
|
+
return op, _core.prepare(op, self.base_url, self.readings_url, args, kwargs)
|
|
65
|
+
|
|
66
|
+
def _finish(self, op: Operation, response: httpx.Response) -> Any:
|
|
67
|
+
_core.check_version(response, self._versions_warned)
|
|
68
|
+
return _core.result(op, response)
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def _decorate(fn, op: Operation):
|
|
72
|
+
fn.__name__ = op.name
|
|
73
|
+
fn.__qualname__ = f"{op.namespace}.{op.name}"
|
|
74
|
+
fn.__doc__ = op.description
|
|
75
|
+
fn.__signature__ = _core.signature(op)
|
|
76
|
+
return fn
|
|
77
|
+
|
|
78
|
+
def _retry_delay(self, error: Throttled, attempt: int) -> float | None:
|
|
79
|
+
if attempt >= self.retries or error.retry_after is None:
|
|
80
|
+
return None
|
|
81
|
+
return error.retry_after
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class MeshThings(_Client, SyncNamespaces):
|
|
85
|
+
"""Client for the mesh-things API.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
base_url: The API's root, for example `https://api.example.org`. Defaults to
|
|
89
|
+
`MESH_THINGS_URL`.
|
|
90
|
+
api_key: An owner's API key. Defaults to `MESH_THINGS_API_KEY`; pass `""` to send
|
|
91
|
+
none even when that is set. Without a key only public data can be read.
|
|
92
|
+
readings_url: A separate root for `/readings` paths, for a local stack that serves
|
|
93
|
+
them on their own port.
|
|
94
|
+
timeout: Seconds before a request is abandoned.
|
|
95
|
+
retries: How many times a rate-limited request is retried after the delay the API
|
|
96
|
+
asks for.
|
|
97
|
+
allow_insecure_http: Send the API key over plain `http://` to a host other than
|
|
98
|
+
this machine. Defaults to `MESH_THINGS_ALLOW_HTTP`; otherwise that raises
|
|
99
|
+
`InsecureTransport`.
|
|
100
|
+
http: An `httpx.Client` to send requests with, instead of a new one.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
base_url: str | None = None,
|
|
106
|
+
api_key: str | None = None,
|
|
107
|
+
*,
|
|
108
|
+
readings_url: str | None = None,
|
|
109
|
+
timeout: float = 30.0,
|
|
110
|
+
retries: int = 0,
|
|
111
|
+
allow_insecure_http: bool | None = None,
|
|
112
|
+
http: httpx.Client | None = None,
|
|
113
|
+
):
|
|
114
|
+
self._http = http or httpx.Client(timeout=timeout)
|
|
115
|
+
super().__init__(base_url, api_key, readings_url, retries, allow_insecure_http)
|
|
116
|
+
|
|
117
|
+
def call(self, operation_id: str, *args: Any, **kwargs: Any) -> Any:
|
|
118
|
+
"""Run any operation by its operationId."""
|
|
119
|
+
op, request = self._prepare(operation_id, args, kwargs)
|
|
120
|
+
attempt = 0
|
|
121
|
+
while True:
|
|
122
|
+
response = self._http.request(
|
|
123
|
+
request.method, request.url, params=request.params, json=request.json, headers=self._headers,
|
|
124
|
+
)
|
|
125
|
+
try:
|
|
126
|
+
return self._finish(op, response)
|
|
127
|
+
except Throttled as error:
|
|
128
|
+
delay = self._retry_delay(error, attempt)
|
|
129
|
+
if delay is None:
|
|
130
|
+
raise
|
|
131
|
+
attempt += 1
|
|
132
|
+
time.sleep(delay)
|
|
133
|
+
|
|
134
|
+
def _bind(self, op: Operation) -> Callable[..., Any]:
|
|
135
|
+
def method(*args, **kwargs):
|
|
136
|
+
return self.call(op.operation_id, *args, **kwargs)
|
|
137
|
+
return self._decorate(method, op)
|
|
138
|
+
|
|
139
|
+
def get_terms(self, kind: str = "account", locale: str = "en") -> dict | None:
|
|
140
|
+
"""The terms of `kind`: `account`, `meshes`, `sinks` or `sources`.
|
|
141
|
+
|
|
142
|
+
Returns None on an instance that enforces no terms. Pass the result to
|
|
143
|
+
`terms_fields()` to accept them when creating the resource.
|
|
144
|
+
"""
|
|
145
|
+
try:
|
|
146
|
+
return self.call(_helpers.terms_operation(kind), locale=locale)
|
|
147
|
+
except NotFound:
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
def wait_for_export(self, mesh_id: str, export_id: str, *, interval: float = 5.0,
|
|
151
|
+
timeout: float | None = None) -> dict:
|
|
152
|
+
"""Poll an export until it is ready and return it.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ExportFailed: If it ends `failed` or `expired`.
|
|
156
|
+
TimeoutError: If it is still running after `timeout` seconds.
|
|
157
|
+
"""
|
|
158
|
+
until = _helpers.deadline(timeout)
|
|
159
|
+
while True:
|
|
160
|
+
export = self.call(_helpers.EXPORT_GET, mesh_id, export_id)
|
|
161
|
+
if _helpers.finished_export(export):
|
|
162
|
+
return export
|
|
163
|
+
_helpers.check_deadline(until, export)
|
|
164
|
+
time.sleep(interval)
|
|
165
|
+
|
|
166
|
+
def download(self, url: str, path: str | Path | None = None) -> bytes | Path:
|
|
167
|
+
"""Fetch a presigned link, such as a ready export's `url`. Writes to `path` when given."""
|
|
168
|
+
with self._http.stream("GET", url) as response:
|
|
169
|
+
response.raise_for_status()
|
|
170
|
+
if path is None:
|
|
171
|
+
return response.read()
|
|
172
|
+
target = Path(path)
|
|
173
|
+
with target.open("wb") as out:
|
|
174
|
+
for chunk in response.iter_bytes():
|
|
175
|
+
out.write(chunk)
|
|
176
|
+
return target
|
|
177
|
+
|
|
178
|
+
def download_partition(self, mesh_id: str, day: str | date, hour: int,
|
|
179
|
+
path: str | Path | None = None) -> bytes | Path:
|
|
180
|
+
"""Fetch one hour of a mesh's Parquet archive. Writes to `path` when given."""
|
|
181
|
+
return self.download(self.call(_helpers.PARTITION, mesh_id, day, hour), path)
|
|
182
|
+
|
|
183
|
+
def traceroutes(self, mesh_id: str, *, node_id: int | str | None = None,
|
|
184
|
+
page_size: int = 100) -> Iterator[dict]:
|
|
185
|
+
"""Every traceroute heard on a mesh, newest first, fetched a page at a time."""
|
|
186
|
+
size = _helpers.page_size(page_size)
|
|
187
|
+
before = None
|
|
188
|
+
while True:
|
|
189
|
+
page = self.call(_helpers.TRACEROUTES, mesh_id, limit=size, before=before, node_id=node_id)
|
|
190
|
+
yield from page
|
|
191
|
+
before = _helpers.next_before(page, size)
|
|
192
|
+
if before is None:
|
|
193
|
+
return
|
|
194
|
+
|
|
195
|
+
def close(self) -> None:
|
|
196
|
+
self._http.close()
|
|
197
|
+
|
|
198
|
+
def __enter__(self) -> "MeshThings":
|
|
199
|
+
return self
|
|
200
|
+
|
|
201
|
+
def __exit__(self, *exc: object) -> None:
|
|
202
|
+
self.close()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class AsyncMeshThings(_Client, AsyncNamespaces):
|
|
206
|
+
"""Async client for the mesh-things API. Takes the same arguments as `MeshThings`."""
|
|
207
|
+
|
|
208
|
+
def __init__(
|
|
209
|
+
self,
|
|
210
|
+
base_url: str | None = None,
|
|
211
|
+
api_key: str | None = None,
|
|
212
|
+
*,
|
|
213
|
+
readings_url: str | None = None,
|
|
214
|
+
timeout: float = 30.0,
|
|
215
|
+
retries: int = 0,
|
|
216
|
+
allow_insecure_http: bool | None = None,
|
|
217
|
+
http: httpx.AsyncClient | None = None,
|
|
218
|
+
):
|
|
219
|
+
self._http = http or httpx.AsyncClient(timeout=timeout)
|
|
220
|
+
super().__init__(base_url, api_key, readings_url, retries, allow_insecure_http)
|
|
221
|
+
|
|
222
|
+
async def call(self, operation_id: str, *args: Any, **kwargs: Any) -> Any:
|
|
223
|
+
"""Run any operation by its operationId."""
|
|
224
|
+
op, request = self._prepare(operation_id, args, kwargs)
|
|
225
|
+
attempt = 0
|
|
226
|
+
while True:
|
|
227
|
+
response = await self._http.request(
|
|
228
|
+
request.method, request.url, params=request.params, json=request.json, headers=self._headers,
|
|
229
|
+
)
|
|
230
|
+
try:
|
|
231
|
+
return self._finish(op, response)
|
|
232
|
+
except Throttled as error:
|
|
233
|
+
delay = self._retry_delay(error, attempt)
|
|
234
|
+
if delay is None:
|
|
235
|
+
raise
|
|
236
|
+
attempt += 1
|
|
237
|
+
await asyncio.sleep(delay)
|
|
238
|
+
|
|
239
|
+
def _bind(self, op: Operation) -> Callable[..., Any]:
|
|
240
|
+
async def method(*args, **kwargs):
|
|
241
|
+
return await self.call(op.operation_id, *args, **kwargs)
|
|
242
|
+
return self._decorate(method, op)
|
|
243
|
+
|
|
244
|
+
async def get_terms(self, kind: str = "account", locale: str = "en") -> dict | None:
|
|
245
|
+
"""The terms of `kind`: `account`, `meshes`, `sinks` or `sources`.
|
|
246
|
+
|
|
247
|
+
Returns None on an instance that enforces no terms. Pass the result to
|
|
248
|
+
`terms_fields()` to accept them when creating the resource.
|
|
249
|
+
"""
|
|
250
|
+
try:
|
|
251
|
+
return await self.call(_helpers.terms_operation(kind), locale=locale)
|
|
252
|
+
except NotFound:
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
async def wait_for_export(self, mesh_id: str, export_id: str, *, interval: float = 5.0,
|
|
256
|
+
timeout: float | None = None) -> dict:
|
|
257
|
+
"""Poll an export until it is ready and return it.
|
|
258
|
+
|
|
259
|
+
Raises:
|
|
260
|
+
ExportFailed: If it ends `failed` or `expired`.
|
|
261
|
+
TimeoutError: If it is still running after `timeout` seconds.
|
|
262
|
+
"""
|
|
263
|
+
until = _helpers.deadline(timeout)
|
|
264
|
+
while True:
|
|
265
|
+
export = await self.call(_helpers.EXPORT_GET, mesh_id, export_id)
|
|
266
|
+
if _helpers.finished_export(export):
|
|
267
|
+
return export
|
|
268
|
+
_helpers.check_deadline(until, export)
|
|
269
|
+
await asyncio.sleep(interval)
|
|
270
|
+
|
|
271
|
+
async def download(self, url: str, path: str | Path | None = None) -> bytes | Path:
|
|
272
|
+
"""Fetch a presigned link, such as a ready export's `url`. Writes to `path` when given."""
|
|
273
|
+
async with self._http.stream("GET", url) as response:
|
|
274
|
+
response.raise_for_status()
|
|
275
|
+
if path is None:
|
|
276
|
+
return await response.aread()
|
|
277
|
+
target = Path(path)
|
|
278
|
+
with target.open("wb") as out:
|
|
279
|
+
async for chunk in response.aiter_bytes():
|
|
280
|
+
out.write(chunk)
|
|
281
|
+
return target
|
|
282
|
+
|
|
283
|
+
async def download_partition(self, mesh_id: str, day: str | date, hour: int,
|
|
284
|
+
path: str | Path | None = None) -> bytes | Path:
|
|
285
|
+
"""Fetch one hour of a mesh's Parquet archive. Writes to `path` when given."""
|
|
286
|
+
return await self.download(await self.call(_helpers.PARTITION, mesh_id, day, hour), path)
|
|
287
|
+
|
|
288
|
+
async def traceroutes(self, mesh_id: str, *, node_id: int | str | None = None,
|
|
289
|
+
page_size: int = 100) -> AsyncIterator[dict]:
|
|
290
|
+
"""Every traceroute heard on a mesh, newest first, fetched a page at a time."""
|
|
291
|
+
size = _helpers.page_size(page_size)
|
|
292
|
+
before = None
|
|
293
|
+
while True:
|
|
294
|
+
page = await self.call(_helpers.TRACEROUTES, mesh_id, limit=size, before=before, node_id=node_id)
|
|
295
|
+
for traceroute in page:
|
|
296
|
+
yield traceroute
|
|
297
|
+
before = _helpers.next_before(page, size)
|
|
298
|
+
if before is None:
|
|
299
|
+
return
|
|
300
|
+
|
|
301
|
+
async def aclose(self) -> None:
|
|
302
|
+
await self._http.aclose()
|
|
303
|
+
|
|
304
|
+
async def __aenter__(self) -> "AsyncMeshThings":
|
|
305
|
+
return self
|
|
306
|
+
|
|
307
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
308
|
+
await self.aclose()
|