Skip to content

Commit a827452

Browse files
committed
[mock_uss] Set of typing fixes
1 parent 682dd9b commit a827452

File tree

18 files changed

+208
-829
lines changed

18 files changed

+208
-829
lines changed

.basedpyright/baseline.json

Lines changed: 6 additions & 764 deletions
Large diffs are not rendered by default.

monitoring/mock_uss/tracer/context.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
KEY_TRACER_OUTPUT_FOLDER,
1111
)
1212
from monitoring.mock_uss.tracer.observation_areas import ObservationAreaID
13-
from monitoring.mock_uss.tracer.tracerlog import Logger
13+
from monitoring.mock_uss.tracer.tracerlog import DummyLogger, Logger
1414
from monitoring.monitorlib import infrastructure
1515
from monitoring.monitorlib.auth import make_auth_adapter
1616
from monitoring.monitorlib.fetch import scd
@@ -23,7 +23,7 @@
2323
scd_cache: dict[ObservationAreaID, dict[str, scd.FetchedEntity]] = {}
2424

2525

26-
def _get_tracer_logger() -> Logger | None:
26+
def _get_tracer_logger() -> Logger:
2727
kml_server = webapp.config[KEY_TRACER_KML_SERVER]
2828
kml_folder = webapp.config[KEY_TRACER_KML_FOLDER]
2929
output_folder = webapp.config[KEY_TRACER_OUTPUT_FOLDER]
@@ -36,7 +36,7 @@ def _get_tracer_logger() -> Logger | None:
3636
if kml_server
3737
else None
3838
)
39-
return Logger(output_folder, kml_session) if output_folder else None
39+
return Logger(output_folder, kml_session) if output_folder else DummyLogger()
4040

4141

4242
tracer_logger: Logger = _get_tracer_logger()
@@ -57,14 +57,16 @@ def resolve_auth_spec(requested_auth_spec: AuthSpec | None) -> AuthSpec:
5757
return requested_auth_spec
5858

5959

60-
def resolve_rid_dss_base_url(dss_base_url: str, rid_version: RIDVersion) -> str:
60+
def resolve_rid_dss_base_url(dss_base_url: str | None, rid_version: RIDVersion) -> str:
6161
if not dss_base_url:
62-
if KEY_DSS_URL not in webapp.config or not webapp.config[KEY_DSS_URL]:
62+
63+
dss_base_url = webapp.config.get(KEY_DSS_URL)
64+
65+
if not dss_base_url:
6366
raise ValueError(
6467
"DSS base URL was not specified explicitly nor in mock_uss_configuration"
6568
)
66-
else:
67-
dss_base_url = webapp.config[KEY_DSS_URL]
69+
6870
if rid_version == RIDVersion.f3411_19:
6971
return dss_base_url
7072
elif rid_version == RIDVersion.f3411_22a:
@@ -75,14 +77,15 @@ def resolve_rid_dss_base_url(dss_base_url: str, rid_version: RIDVersion) -> str:
7577
)
7678

7779

78-
def resolve_scd_dss_base_url(dss_base_url: str) -> str:
80+
def resolve_scd_dss_base_url(dss_base_url: str | None) -> str:
7981
if not dss_base_url:
80-
if KEY_DSS_URL not in webapp.config or not webapp.config[KEY_DSS_URL]:
82+
dss_base_url = webapp.config.get(KEY_DSS_URL)
83+
84+
if not dss_base_url:
8185
raise ValueError(
8286
"DSS base URL was not specified explicitly nor in mock_uss_configuration"
8387
)
84-
else:
85-
dss_base_url = webapp.config[KEY_DSS_URL]
88+
8689
return dss_base_url
8790

8891

monitoring/mock_uss/tracer/diff.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1+
from typing import cast
12
from monitoring.monitorlib import formatting
23
from monitoring.monitorlib.fetch import rid, scd, summarize
34

45

56
def isa_diff_text(a: rid.FetchedISAs | None, b: rid.FetchedISAs | None) -> str:
67
"""Create text to display to a real-time user describing a change in ISAs."""
78
a_summary = summarize.isas(a) if a else {}
8-
a_summary = summarize.limit_long_arrays(a_summary, 6)
9+
a_summary = cast(dict, summarize.limit_long_arrays(a_summary, 6))
910
b_summary = summarize.isas(b) if b else {}
10-
b_summary = summarize.limit_long_arrays(b_summary, 6)
11+
b_summary = cast(dict, summarize.limit_long_arrays(b_summary, 6))
1112
if b is not None and b.success and a is not None and not a.success:
1213
a_summary = {}
1314
if a is not None and a.success and b is not None and not b.success:
@@ -26,9 +27,9 @@ def entity_diff_text(
2627
if entity_type and "_" in entity_type:
2728
entity_type = entity_type[0 : entity_type.index("_")]
2829
a_summary = summarize.entities(a, entity_type) if a else {}
29-
a_summary = summarize.limit_long_arrays(a_summary, 6)
30+
a_summary = cast(dict, summarize.limit_long_arrays(a_summary, 6))
3031
b_summary = summarize.entities(b, entity_type) if b else {}
31-
b_summary = summarize.limit_long_arrays(b_summary, 6)
32+
b_summary = cast(dict, summarize.limit_long_arrays(b_summary, 6))
3233
if b is not None and b.success and a is not None and not a.success:
3334
a_summary = {}
3435
if a is not None and a.success and b is not None and not b.success:

monitoring/mock_uss/tracer/kml.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from datetime import UTC, datetime, timedelta
88
from enum import Enum
99
from typing import Protocol
10+
from abc import abstractmethod
1011

1112
import yaml
1213
from implicitdict import ImplicitDict
@@ -40,7 +41,8 @@ def __enter__(self):
4041
self._start_time = datetime.now(UTC)
4142

4243
def __exit__(self, exc_type, exc_val, exc_tb):
43-
self.elapsed_time += datetime.now(UTC) - self._start_time
44+
if self._start_time:
45+
self.elapsed_time += datetime.now(UTC) - self._start_time
4446

4547

4648
class VolumeType(str, Enum):
@@ -57,10 +59,12 @@ class HistoricalVolumesCollection:
5759
active_at: datetime
5860

5961

60-
class HistoricalVolumesRenderer(Protocol):
62+
class HistoricalVolumesRenderer[T](Protocol):
63+
64+
@abstractmethod
6165
def __call__(
6266
self,
63-
log_entry: TracerLogEntry,
67+
log_entry: T,
6468
existing_volume_collections: list[HistoricalVolumesCollection],
6569
) -> list[HistoricalVolumesCollection]:
6670
"""Function that generates named collections of 4D volumes from a tracer log entry.
@@ -71,6 +75,7 @@ def __call__(
7175
7276
Returns: Collection of 4D volume collections.
7377
"""
78+
raise NotImplementedError
7479

7580

7681
@dataclass
@@ -126,6 +131,10 @@ def _historical_volumes_op_intent_notification(
126131
existing_volume_collections: list[HistoricalVolumesCollection],
127132
) -> list[HistoricalVolumesCollection]:
128133
try:
134+
135+
if log_entry.request.json is None:
136+
raise ValueError("No json data in log entry")
137+
129138
req = ImplicitDict.parse(
130139
log_entry.request.json, PutOperationalIntentDetailsParameters
131140
)
@@ -136,7 +145,7 @@ def _historical_volumes_op_intent_notification(
136145
return []
137146
assert isinstance(req, PutOperationalIntentDetailsParameters)
138147

139-
claims = get_token_claims(log_entry.request.headers)
148+
claims = get_token_claims(log_entry.request.headers or {})
140149
manager = claims.get("sub", "[Unknown manager]")
141150
name = f"{manager} {req.operational_intent_id}"
142151

@@ -148,7 +157,7 @@ def _historical_volumes_op_intent_notification(
148157
else:
149158
version = "[deleted]"
150159
state = "Ended"
151-
volumes = []
160+
volumes = Volume4DCollection()
152161

153162
# See if this op intent version already has a volumes collection
154163
already_defined = False
@@ -183,6 +192,10 @@ def _historical_volumes_op_intent_poll(
183192
# Add newly-polled operational intents
184193
for op_intent_id, query in log_entry.poll.uss_queries.items():
185194
try:
195+
196+
if query.json_result is None:
197+
raise ValueError("No json result in query")
198+
186199
resp = ImplicitDict.parse(
187200
query.json_result, GetOperationalIntentDetailsResponse
188201
)
@@ -222,6 +235,10 @@ def _historical_volumes_op_intent_poll(
222235
# Remove any existing operational intents that no longer exist as of this poll
223236
for cached_op_intent_id, cached_query in log_entry.poll.cached_uss_queries.items():
224237
try:
238+
239+
if cached_query.json_result is None:
240+
raise ValueError("No json result in query")
241+
225242
resp = ImplicitDict.parse(
226243
cached_query.json_result, GetOperationalIntentDetailsResponse
227244
)
@@ -274,17 +291,19 @@ class VolumesFolder:
274291
def truncate(self, latest_time: Time) -> None:
275292
to_remove = []
276293
for v in self.volumes:
277-
if v.volume.time_start.datetime > latest_time.datetime:
294+
if v.volume.time_start and v.volume.time_start.datetime > latest_time.datetime:
278295
to_remove.append(v)
279-
elif v.volume.time_end.datetime > latest_time.datetime:
296+
elif v.volume.time_end and v.volume.time_end.datetime > latest_time.datetime:
280297
v.volume.time_end = latest_time
281298
for v in to_remove:
282299
self.volumes.remove(v)
283300
for c in self.children:
284301
c.truncate(latest_time)
285302

286-
def to_kml_folder(self) -> kml.Folder:
303+
def to_kml_folder(self):
287304
def dt(t: Time) -> int:
305+
if self.reference_time is None:
306+
return -1
288307
return round((t.datetime - self.reference_time.datetime).total_seconds())
289308

290309
if self.reference_time:
@@ -293,7 +312,7 @@ def dt(t: Time) -> int:
293312
else:
294313
folder = kml.Folder(kml.name(self.name))
295314
for v in self.volumes:
296-
name = f"{v.name} {dt(v.volume.time_start)}s-{dt(v.volume.time_end)}s"
315+
name = f"{v.name} {dt(v.volume.time_start) if v.volume.time_start else '?'}s-{dt(v.volume.time_end) if v.volume.time_end else '?'}s"
297316
folder.append(
298317
make_placemark_from_volume(v.volume, name=name, style_url=v.style)
299318
)
@@ -408,13 +427,13 @@ def render_historical_kml(log_folder: str) -> str:
408427
version_folder.children.append(future_folder)
409428

410429
for i, v in enumerate(hvc.volumes):
411-
if v.time_end.datetime <= hvc.active_at:
430+
if v.time_end and v.time_end.datetime <= hvc.active_at:
412431
# This volume ended before the collection was declared, so it never actually existed
413432
continue
414-
if v.time_start.datetime < hvc.active_at:
433+
if v.time_start and v.time_start.datetime < hvc.active_at:
415434
# Volume is declared in the past, but it's only visible starting now
416435
v.time_start = t_hvc
417-
elif v.time_start.datetime > hvc.active_at:
436+
elif v.time_start and v.time_start.datetime > hvc.active_at:
418437
# Add a "future" volume between when this volume was declared and its start time
419438
future_v = Volume4D(v)
420439
future_v.time_end = v.time_start

monitoring/mock_uss/tracer/observation_areas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ class ObservationArea(ImplicitDict):
6767
@property
6868
def polls(self) -> bool:
6969
"""Whether any of the observation activity involves periodic polling."""
70-
return (self.f3411 and self.f3411.poll) or (self.f3548 and self.f3548.poll)
70+
return bool(self.f3411 and self.f3411.poll) or bool(self.f3548 and self.f3548.poll)
7171

7272

7373
class F3411ObservationAreaRequest(ImplicitDict):
@@ -134,7 +134,7 @@ class ObservationAreaRequest(ImplicitDict):
134134
@property
135135
def polls(self) -> bool:
136136
"""Whether any of the observation activity requested involves periodic polling."""
137-
return (self.f3411 and self.f3411.poll) or (self.f3548 and self.f3548.poll)
137+
return bool(self.f3411 and self.f3411.poll) or bool(self.f3548 and self.f3548.poll)
138138

139139

140140
class ListObservationAreasResponse(ImplicitDict):

monitoring/mock_uss/tracer/routes/observation_areas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737

3838
@webapp.route("/tracer/observation_areas", methods=["GET"])
39-
@ui_auth.login_required
39+
@ui_auth.login_required()
4040
def tracer_list_observation_areas() -> flask.Response:
4141
with db as tx:
4242
result = ListObservationAreasResponse(
@@ -131,7 +131,7 @@ def tracer_import_observation_areas() -> tuple[str, int] | flask.Response:
131131
elif request.area.volume.outline_polygon:
132132
points = [
133133
s2sphere.LatLng.from_degrees(p.lat, p.lng)
134-
for p in request.area.volume.outline_polygon.vertices
134+
for p in request.area.volume.outline_polygon.vertices or []
135135
]
136136
else:
137137
raise NotImplementedError(

monitoring/mock_uss/tracer/routes/scd.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ def tracer_scd_v21_operation_notification(observation_area_id: str) -> tuple[str
3939
label = colored("Operation", "blue")
4040
try:
4141
json = flask.request.json
42+
43+
if json is None:
44+
raise ValueError("No json in request")
45+
4246
id = json.get("operational_intent_id", "<Unknown ID>")
4347
if json.get("operational_intent"):
4448
op = json["operational_intent"]
@@ -94,6 +98,10 @@ def tracer_scd_v21_constraint_notification(observation_area_id: str) -> tuple[st
9498
label = colored("Constraint", "magenta")
9599
try:
96100
json = flask.request.json
101+
102+
if json is None:
103+
raise ValueError("No json in request")
104+
97105
id = json.get("constraint_id", "<Unknown ID>")
98106
if json.get("constraint"):
99107
constraint = json["constraint"]

0 commit comments

Comments
 (0)