Skip to content

Commit da22c0f

Browse files
[MISC] Migrate typing syntax to Python 3.10+ (#816)
1 parent 68fb053 commit da22c0f

File tree

12 files changed

+144
-152
lines changed

12 files changed

+144
-152
lines changed

src/backups.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import time
1212
from datetime import datetime, timezone
1313
from io import BytesIO
14-
from typing import Dict, List, Optional, Tuple
1514

1615
import boto3 as boto3
1716
import botocore
@@ -89,7 +88,7 @@ def _tls_ca_chain_filename(self) -> str:
8988
return f"{self.charm._storage_path}/pgbackrest-tls-ca-chain.crt"
9089
return ""
9190

92-
def _are_backup_settings_ok(self) -> Tuple[bool, Optional[str]]:
91+
def _are_backup_settings_ok(self) -> tuple[bool, str | None]:
9392
"""Validates whether backup settings are OK."""
9493
if self.model.get_relation(self.relation_name) is None:
9594
return (
@@ -120,7 +119,7 @@ def _can_initialise_stanza(self) -> bool:
120119
)
121120
)
122121

123-
def _can_unit_perform_backup(self) -> Tuple[bool, Optional[str]]:
122+
def _can_unit_perform_backup(self) -> tuple[bool, str | None]:
124123
"""Validates whether this unit can perform a backup."""
125124
if self.charm.is_blocked:
126125
return False, "Unit is in a blocking state"
@@ -152,7 +151,7 @@ def _can_unit_perform_backup(self) -> Tuple[bool, Optional[str]]:
152151

153152
return self._are_backup_settings_ok()
154153

155-
def can_use_s3_repository(self) -> Tuple[bool, Optional[str]]:
154+
def can_use_s3_repository(self) -> tuple[bool, str | None]:
156155
"""Returns whether the charm was configured to use another cluster repository."""
157156
# Check model uuid
158157
s3_parameters, _ = self._retrieve_s3_parameters()
@@ -196,7 +195,7 @@ def can_use_s3_repository(self) -> Tuple[bool, Optional[str]]:
196195
return False, ANOTHER_CLUSTER_REPOSITORY_ERROR_MESSAGE
197196
return True, None
198197

199-
def _construct_endpoint(self, s3_parameters: Dict) -> str:
198+
def _construct_endpoint(self, s3_parameters: dict) -> str:
200199
"""Construct the S3 service endpoint using the region.
201200
202201
This is needed when the provided endpoint is from AWS, and it doesn't contain the region.
@@ -278,8 +277,11 @@ def _change_connectivity_to_database(self, connectivity: bool) -> None:
278277
self.charm.update_config(is_creating_backup=True)
279278

280279
def _execute_command(
281-
self, command: List[str], timeout: Optional[float] = None, stream: bool = False
282-
) -> Tuple[Optional[str], Optional[str]]:
280+
self,
281+
command: list[str],
282+
timeout: float | None = None,
283+
stream: bool = False,
284+
) -> tuple[str | None, str | None]:
283285
"""Execute a command in the workload container."""
284286
try:
285287
logger.debug("Running command %s", " ".join(command))
@@ -504,7 +506,7 @@ def _parse_psql_timestamp(self, timestamp: str) -> datetime:
504506
dt = dt.astimezone(tz=timezone.utc)
505507
return dt.replace(tzinfo=None)
506508

507-
def _parse_backup_id(self, label) -> Tuple[str, str]:
509+
def _parse_backup_id(self, label) -> tuple[str, str]:
508510
"""Parse backup ID as a timestamp and its type."""
509511
if label[-1] == "F":
510512
timestamp = label
@@ -1221,7 +1223,7 @@ def _restart_database(self) -> None:
12211223
self.charm.update_config()
12221224
self.container.start(self.charm._postgresql_service)
12231225

1224-
def _retrieve_s3_parameters(self) -> Tuple[Dict, List[str]]:
1226+
def _retrieve_s3_parameters(self) -> tuple[dict, list[str]]:
12251227
"""Retrieve S3 parameters from the S3 integrator relation."""
12261228
s3_parameters = self.s3_client.get_s3_connection_info()
12271229
required_parameters = [

src/charm.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import sys
1414
import time
1515
from pathlib import Path
16-
from typing import Dict, List, Literal, Optional, Tuple, get_args
16+
from typing import Literal, get_args
1717

1818
# First platform-specific import, will fail on wrong architecture
1919
try:
@@ -254,7 +254,7 @@ def __init__(self, *args):
254254
)
255255

256256
@property
257-
def tracing_endpoint(self) -> Optional[str]:
257+
def tracing_endpoint(self) -> str | None:
258258
"""Otlp http endpoint for charm instrumentation."""
259259
if self.tracing.is_ready():
260260
return self.tracing.get_endpoint(TRACING_PROTOCOL)
@@ -267,7 +267,7 @@ def _pebble_log_forwarding_supported(self) -> bool:
267267
juju_version = JujuVersion.from_environ()
268268
return juju_version > JujuVersion(version="3.3")
269269

270-
def _generate_metrics_jobs(self, enable_tls: bool) -> Dict:
270+
def _generate_metrics_jobs(self, enable_tls: bool) -> dict:
271271
"""Generate spec for Prometheus scraping."""
272272
return [
273273
{"static_configs": [{"targets": [f"*:{METRICS_PORT}"]}]},
@@ -287,7 +287,7 @@ def app_units(self) -> set[Unit]:
287287
return {self.unit, *self._peers.units}
288288

289289
@property
290-
def app_peer_data(self) -> Dict:
290+
def app_peer_data(self) -> dict:
291291
"""Application peer relation data object."""
292292
relation = self.model.get_relation(PEER)
293293
if relation is None:
@@ -296,15 +296,15 @@ def app_peer_data(self) -> Dict:
296296
return relation.data[self.app]
297297

298298
@property
299-
def unit_peer_data(self) -> Dict:
299+
def unit_peer_data(self) -> dict:
300300
"""Unit peer relation data object."""
301301
relation = self.model.get_relation(PEER)
302302
if relation is None:
303303
return {}
304304

305305
return relation.data[self.unit]
306306

307-
def _peer_data(self, scope: Scopes) -> Dict:
307+
def _peer_data(self, scope: Scopes) -> dict:
308308
"""Return corresponding databag for app/unit."""
309309
relation = self.model.get_relation(PEER)
310310
if relation is None:
@@ -333,7 +333,7 @@ def _translate_field_to_secret_key(self, key: str) -> str:
333333
new_key = key.replace("_", "-")
334334
return new_key.strip("-")
335335

336-
def get_secret(self, scope: Scopes, key: str) -> Optional[str]:
336+
def get_secret(self, scope: Scopes, key: str) -> str | None:
337337
"""Get secret from the secret storage."""
338338
if scope not in get_args(Scopes):
339339
raise RuntimeError("Unknown secret scope.")
@@ -348,7 +348,7 @@ def get_secret(self, scope: Scopes, key: str) -> Optional[str]:
348348

349349
return self.peer_relation_data(scope).get_secret(peers.id, secret_key)
350350

351-
def set_secret(self, scope: Scopes, key: str, value: Optional[str]) -> Optional[str]:
351+
def set_secret(self, scope: Scopes, key: str, value: str | None) -> str | None:
352352
"""Set secret from the secret storage."""
353353
if scope not in get_args(Scopes):
354354
raise RuntimeError("Unknown secret scope.")
@@ -426,14 +426,14 @@ def get_hostname_by_unit(self, unit_name: str) -> str:
426426
unit_id = unit_name.split("/")[1]
427427
return f"{self.app.name}-{unit_id}.{self.app.name}-endpoints"
428428

429-
def _get_endpoints_to_remove(self) -> List[str]:
429+
def _get_endpoints_to_remove(self) -> list[str]:
430430
"""List the endpoints that were part of the cluster but departed."""
431431
old = self._endpoints
432432
current = [self._get_hostname_from_unit(member) for member in self._hosts]
433433
endpoints_to_remove = list(set(old) - set(current))
434434
return endpoints_to_remove
435435

436-
def get_unit_ip(self, unit: Unit) -> Optional[str]:
436+
def get_unit_ip(self, unit: Unit) -> str | None:
437437
"""Get the IP address of a specific unit."""
438438
# Check if host is current host.
439439
if unit == self.unit:
@@ -683,7 +683,7 @@ def _on_config_changed(self, event) -> None:
683683
)
684684
return
685685

686-
def enable_disable_extensions(self, database: Optional[str] = None) -> None:
686+
def enable_disable_extensions(self, database: str | None = None) -> None:
687687
"""Enable/disable PostgreSQL extensions set through config options.
688688
689689
Args:
@@ -1593,7 +1593,7 @@ def _endpoint(self) -> str:
15931593
return self._get_hostname_from_unit(self._unit_name_to_pod_name(self.unit.name))
15941594

15951595
@property
1596-
def _endpoints(self) -> List[str]:
1596+
def _endpoints(self) -> list[str]:
15971597
"""Cluster members hostnames."""
15981598
if self._peers:
15991599
return json.loads(self._peers.data[self.app].get("endpoints", "[]"))
@@ -1602,7 +1602,7 @@ def _endpoints(self) -> List[str]:
16021602
return [self._endpoint]
16031603

16041604
@property
1605-
def peer_members_endpoints(self) -> List[str]:
1605+
def peer_members_endpoints(self) -> list[str]:
16061606
"""Fetch current list of peer members endpoints.
16071607
16081608
Returns:
@@ -1621,14 +1621,14 @@ def _add_to_endpoints(self, endpoint) -> None:
16211621
"""Add one endpoint to the members list."""
16221622
self._update_endpoints(endpoint_to_add=endpoint)
16231623

1624-
def _remove_from_endpoints(self, endpoints: List[str]) -> None:
1624+
def _remove_from_endpoints(self, endpoints: list[str]) -> None:
16251625
"""Remove endpoints from the members list."""
16261626
self._update_endpoints(endpoints_to_remove=endpoints)
16271627

16281628
def _update_endpoints(
16291629
self,
1630-
endpoint_to_add: Optional[str] = None,
1631-
endpoints_to_remove: Optional[List[str]] = None,
1630+
endpoint_to_add: str | None = None,
1631+
endpoints_to_remove: list[str] | None = None,
16321632
) -> None:
16331633
"""Update members IPs."""
16341634
# Allow leader to reset which members are part of the cluster.
@@ -1643,7 +1643,7 @@ def _update_endpoints(
16431643
endpoints.remove(endpoint)
16441644
self._peers.data[self.app]["endpoints"] = json.dumps(endpoints)
16451645

1646-
def _generate_metrics_service(self) -> Dict:
1646+
def _generate_metrics_service(self) -> dict:
16471647
"""Generate the metrics service definition."""
16481648
return {
16491649
"override": "replace",
@@ -2012,7 +2012,7 @@ def _get_node_name_for_pod(self) -> str:
20122012
)
20132013
return pod.spec.nodeName
20142014

2015-
def get_resources_limits(self, container_name: str) -> Dict:
2015+
def get_resources_limits(self, container_name: str) -> dict:
20162016
"""Return resources limits for a given container.
20172017
20182018
Args:
@@ -2040,7 +2040,7 @@ def get_node_cpu_cores(self) -> int:
20402040
node = client.get(Node, name=self._get_node_name_for_pod(), namespace=self._namespace)
20412041
return any_cpu_to_cores(node.status.allocatable["cpu"])
20422042

2043-
def get_available_resources(self) -> Tuple[int, int]:
2043+
def get_available_resources(self) -> tuple[int, int]:
20442044
"""Get available CPU cores and memory (in bytes) for the container."""
20452045
cpu_cores = self.get_node_cpu_cores()
20462046
allocable_memory = self.get_node_allocable_memory()
@@ -2073,7 +2073,7 @@ def on_deployed_without_trust(self) -> None:
20732073
)
20742074

20752075
@property
2076-
def client_relations(self) -> List[Relation]:
2076+
def client_relations(self) -> list[Relation]:
20772077
"""Return the list of established client relations."""
20782078
relations = []
20792079
for relation_name in ["database", "db", "db-admin"]:
@@ -2150,15 +2150,15 @@ def restore_patroni_on_failure_condition(self) -> None:
21502150
else:
21512151
logger.warning("not restoring patroni on-failure condition as it's not overridden")
21522152

2153-
def is_pitr_failed(self, container: Container) -> Tuple[bool, bool]:
2153+
def is_pitr_failed(self, container: Container) -> tuple[bool, bool]:
21542154
"""Check if Patroni service failed to bootstrap cluster during point-in-time-recovery.
21552155
21562156
Typically, this means that database service failed to reach point-in-time-recovery target or has been
21572157
supplied with bad PITR parameter. Also, remembers last state and can provide info is it new event, or
21582158
it belongs to previous action. Executes only on current unit.
21592159
21602160
Returns:
2161-
Tuple[bool, bool]:
2161+
tuple[bool, bool]:
21622162
- Is patroni service failed to bootstrap cluster.
21632163
- Is it new fail, that wasn't observed previously.
21642164
"""
@@ -2228,7 +2228,7 @@ def log_pitr_last_transaction_time(self) -> None:
22282228
else:
22292229
logger.error("Can't tell last completed transaction time")
22302230

2231-
def get_plugins(self) -> List[str]:
2231+
def get_plugins(self) -> list[str]:
22322232
"""Return a list of installed plugins."""
22332233
plugins = [
22342234
"_".join(plugin.split("_")[1:-1])

0 commit comments

Comments
 (0)