Skip to content

Commit b142e69

Browse files
committed
Formatting code using ruff
1 parent 39f5833 commit b142e69

File tree

30 files changed

+101
-124
lines changed

30 files changed

+101
-124
lines changed

src/aibs_informatics_aws_lambda/common/api/handler.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,15 @@
55
import logging
66
from dataclasses import dataclass, field
77
from datetime import datetime
8-
from types import ModuleType
9-
from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union, cast
8+
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union, cast
109

1110
from aibs_informatics_core.models.api.http_parameters import HTTPParameters
1211
from aibs_informatics_core.models.api.route import ApiRoute
1312
from aibs_informatics_core.models.base import ModelProtocol
1413
from aibs_informatics_core.utils.json import JSON
15-
from aibs_informatics_core.utils.modules import get_all_subclasses, load_all_modules_from_pkg
16-
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, content_types
1714
from aws_lambda_powertools.event_handler.api_gateway import BaseRouter
1815
from aws_lambda_powertools.logging import Logger
1916
from aws_lambda_powertools.metrics import EphemeralMetrics, Metrics
20-
from aws_lambda_powertools.tracing import Tracer
2117
from aws_lambda_powertools.utilities.data_classes.api_gateway_proxy_event import (
2218
APIGatewayEventRequestContext,
2319
APIGatewayProxyEvent,
@@ -28,11 +24,8 @@
2824
)
2925
from aws_lambda_powertools.utilities.typing import LambdaContext
3026

31-
from aibs_informatics_aws_lambda.common.base import HandlerMixins
3227
from aibs_informatics_aws_lambda.common.handler import LambdaHandler
33-
from aibs_informatics_aws_lambda.common.logging import LoggingMixins
3428
from aibs_informatics_aws_lambda.common.metrics import (
35-
MetricsMixins,
3629
add_duration_metric,
3730
add_failure_metric,
3831
add_success_metric,
@@ -101,7 +94,6 @@ def add_to_router(
10194
logger = logger or cls.get_logger(service=cls.service_name())
10295
metrics = metrics or cls.get_metrics()
10396

104-
# TODO: remove args once https://github.com/python/mypy/pull/15133 is released (should be mypy 1.2.1)
10597
@metrics.log_metrics
10698
@router.route(rule=cls.route_rule(), method=cls.route_method())
10799
def gateway_handler(logger=logger, metrics=metrics, **route_parameters) -> Any:
@@ -128,7 +120,7 @@ def gateway_handler(logger=logger, metrics=metrics, **route_parameters) -> Any:
128120
*args, _current_event=router.current_event, **kwargs
129121
)
130122

131-
logger.info(f"Route handler method constructed. Invoking")
123+
logger.info("Route handler method constructed. Invoking")
132124
response = lambda_handler(event, router.lambda_context)
133125
add_success_metric(metrics=metrics)
134126
add_duration_metric(start=start, metrics=metrics)
@@ -144,7 +136,7 @@ def gateway_handler(logger=logger, metrics=metrics, **route_parameters) -> Any:
144136
def _parse_event(
145137
cls, event: BaseProxyEvent, route_parameters: Dict[str, Any], logger: logging.Logger
146138
) -> API_REQUEST:
147-
logger.info(f"parsing event.")
139+
logger.info("parsing event.")
148140
stringified_route_params = route_parameters
149141
stringified_query_params = event.query_string_parameters
150142
stringified_request_body = event.json_body if event.body else None
@@ -162,7 +154,7 @@ def _parse_event(
162154
)
163155
logger.debug(f"Constructed following HTTP Parameters: {http_parameters}")
164156

165-
logger.debug(f"Converting HTTP Parameters to request object")
157+
logger.debug("Converting HTTP Parameters to request object")
166158
request = cls.get_request_from_http_parameters(http_parameters)
167159
return request
168160

src/aibs_informatics_aws_lambda/common/api/resolver.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
from aws_lambda_powertools.logging import Logger
1919
from aws_lambda_powertools.logging.correlation_paths import API_GATEWAY_REST
2020
from aws_lambda_powertools.metrics import EphemeralMetrics, Metrics
21-
from aws_lambda_powertools.tracing import Tracer
2221
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent
2322
from aws_lambda_powertools.utilities.typing import LambdaContext
2423

src/aibs_informatics_aws_lambda/common/handler.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,9 @@ def handler(event, context: LambdaContext):
244244
return handler # type: ignore
245245

246246
def __repr__(self) -> str:
247-
return f"{self.__class__.__name__}(request: {self.get_request_cls()}, response: {self.get_response_cls()})"
247+
return (
248+
f"{self.__class__.__name__}("
249+
f"request: {self.get_request_cls()}, "
250+
f"response: {self.get_response_cls()}"
251+
")"
252+
)

src/aibs_informatics_aws_lambda/common/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import inspect
22
from dataclasses import dataclass, field
3-
from typing import Optional, cast
3+
from typing import cast
44

55
import marshmallow as mm
66
from aibs_informatics_aws_utils.constants.lambda_ import (

src/aibs_informatics_aws_lambda/handlers/batch/model.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,16 @@ class CreateDefinitionAndPrepareArgsRequest(SchemaModel):
3333
command: List[str] = custom_field(default_factory=list)
3434
environment: Dict[str, str] = custom_field(default_factory=dict)
3535
job_definition_tags: Dict[str, str] = custom_field(default_factory=dict)
36-
resource_requirements: Union[
37-
List[ResourceRequirementTypeDef], ResourceRequirements
38-
] = custom_field(
39-
default_factory=list,
40-
mm_field=UnionField(
41-
[
42-
(list, ListField(DictField)),
43-
(ResourceRequirements, ResourceRequirements.as_mm_field()),
44-
]
45-
),
36+
resource_requirements: Union[List[ResourceRequirementTypeDef], ResourceRequirements] = (
37+
custom_field(
38+
default_factory=list,
39+
mm_field=UnionField(
40+
[
41+
(list, ListField(DictField)),
42+
(ResourceRequirements, ResourceRequirements.as_mm_field()),
43+
]
44+
),
45+
)
4646
)
4747
mount_points: List[MountPointTypeDef] = custom_field(default_factory=list)
4848
volumes: List[VolumeTypeDef] = custom_field(default_factory=list)

src/aibs_informatics_aws_lambda/handlers/data_sync/file_system.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from datetime import timedelta
33
from pathlib import Path
44
from typing import List, TypeVar
5-
from xml.etree.ElementInclude import include
65

76
from aibs_informatics_aws_utils.data_sync.file_system import BaseFileSystem, Node, get_file_system
87
from aibs_informatics_aws_utils.efs import detect_mount_points, get_local_path

src/aibs_informatics_aws_lambda/handlers/data_sync/model.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,18 @@
2424
from aibs_informatics_core.utils.time import get_current_time
2525

2626
DataPath = Union[S3Path, EFSPath, Path, str]
27-
DataPathField = lambda *args, **kwargs: UnionField(
28-
[
29-
(S3Path, S3Path.as_mm_field()),
30-
((EFSPath, str), EFSPath.as_mm_field()),
31-
((Path, str), PathField()),
32-
],
33-
*args,
34-
**kwargs,
35-
)
27+
28+
29+
def DataPathField(*args, **kwargs):
30+
return UnionField(
31+
[
32+
(S3Path, S3Path.as_mm_field()),
33+
((EFSPath, str), EFSPath.as_mm_field()),
34+
((Path, str), PathField()),
35+
],
36+
*args,
37+
**kwargs,
38+
)
3639

3740

3841
@dataclass

src/aibs_informatics_aws_lambda/handlers/data_sync/operations.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,10 @@ def handle(self, request: GetJSONFromFileRequest) -> GetJSONFromFileResponse:
7070

7171
self.logger.info(f"Fetching content from {path}")
7272
if isinstance(path, S3URI):
73-
self.logger.info(f"Downloading from S3")
73+
self.logger.info("Downloading from S3")
7474
content = download_to_json(s3_path=path)
7575
else:
76-
self.logger.info(f"Loading from path")
76+
self.logger.info("Loading from path")
7777
content = load_json(path)
7878
return GetJSONFromFileResponse(content=content)
7979
except Exception as e:
@@ -103,10 +103,10 @@ def handle(self, request: PutJSONToFileRequest) -> Optional[PutJSONToFileRespons
103103
self.logger.info(f"Writing content to {path}")
104104
self.logger.info(f"Content to write: {content}")
105105
if isinstance(path, S3URI):
106-
self.logger.info(f"Uploading to S3")
106+
self.logger.info("Uploading to S3")
107107
upload_json(content, s3_path=path, extra_args=SCRATCH_EXTRA_ARGS)
108108
else:
109-
self.logger.info(f"Writing to file")
109+
self.logger.info("Writing to file")
110110
path.parent.mkdir(parents=True, exist_ok=True)
111111
path.write_text(json.dumps(content, indent=4, sort_keys=True))
112112
return PutJSONToFileResponse(path=path)
@@ -136,7 +136,7 @@ def handle(self, request: BatchDataSyncRequest) -> BatchDataSyncResponse:
136136
for i, _ in enumerate(batch_requests):
137137
sync_operations = DataSyncOperations(_)
138138
self.logger.info(
139-
f"[{i+1}/{len(batch_requests)}] "
139+
f"[{i + 1}/{len(batch_requests)}] "
140140
f"Syncing content from {_.source_path} to {_.destination_path}"
141141
)
142142
try:
@@ -251,9 +251,9 @@ def build_destination_path(
251251
if node.has_children():
252252
relative_path += "/"
253253
if isinstance(request.destination_path, S3URI):
254-
return S3URI.build(
255-
bucket_name=request.destination_path.bucket,
256-
key=request.destination_path.key + relative_path,
254+
return S3URI(
255+
f"s3://{request.destination_path.bucket}/"
256+
f"{request.destination_path.key + relative_path}"
257257
)
258258
else:
259259
return Path(f"{request.destination_path}/{relative_path}")
@@ -283,10 +283,11 @@ def build_node_batches(
283283
## We will use a revised version of the bin packing problem:
284284
# https://en.wikipedia.org/wiki/Bin_packing_problem
285285

286-
# Step 1: and then sort the nodes by size (descending order)
286+
# Step 1: and then sort the nodes by size (descending order)
287287
unbatched_nodes = sorted(nodes, key=lambda node: node.size_bytes, reverse=True)
288288

289-
# Step 2: Group nodes in order to maximize the data synced per request (bin packing problem)
289+
# Step 2: Group nodes in order to maximize the data synced per request
290+
# (bin packing problem)
290291
node_batches: List[List[Node]] = []
291292

292293
# (Optimize) Convert all nodes that are larger than the threshold into single requests.

src/aibs_informatics_aws_lambda/handlers/demand/context_manager.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,12 @@ class BatchEFSConfiguration:
6565
volume: VolumeTypeDef = field(init=False)
6666

6767
def __post_init__(self) -> None:
68+
file_system = self.mount_point_config.file_system
69+
name_or_id = file_system.get("Name", file_system["FileSystemId"])
6870
volume_name = "-".join(
6971
[
70-
f'{self.mount_point_config.file_system.get("Name", self.mount_point_config.file_system["FileSystemId"])}',
71-
f'{str(self.mount_path).strip("/").replace("/","-")}-vol',
72+
f"{name_or_id}",
73+
f"{str(self.mount_path).strip('/').replace('/', '-')}-vol",
7274
]
7375
)
7476

@@ -293,7 +295,7 @@ def post_execution_data_sync_requests(self) -> List[PrepareBatchDataSyncRequest]
293295
)
294296
)
295297
logger.info(
296-
f"Generated {len(requests)} data sync requests for post-execution data sync: {requests}"
298+
f"Generated {len(requests)} data sync requests for post-execution data sync: {requests}" # noqa: E501
297299
)
298300
return requests
299301

@@ -488,7 +490,7 @@ def get_batch_efs_configuration(
488490
)
489491

490492

491-
def generate_batch_job_builder(
493+
def generate_batch_job_builder( # noqa: C901
492494
demand_execution: DemandExecution,
493495
env_base: EnvBase,
494496
working_path: EFSPath,
@@ -498,7 +500,7 @@ def generate_batch_job_builder(
498500
tmp_mount_point: Optional[MountPointConfiguration] = None,
499501
env_file_write_mode: EnvFileWriteMode = EnvFileWriteMode.ALWAYS,
500502
) -> BatchJobBuilder:
501-
logger.info(f"Constructing BatchJobBuilder instance")
503+
logger.info("Constructing BatchJobBuilder instance")
502504

503505
demand_execution = demand_execution.copy()
504506
efs_mount_points = [scratch_mount_point, shared_mount_point]
@@ -585,8 +587,9 @@ def generate_batch_job_builder(
585587

586588
if env_size > 8192 * 0.9:
587589
logger.info(
588-
f"Environment variables are too large to pass directly to container (> 90% of 8192). "
589-
f"Writing environment variables to file {efs_environment_file_uri}."
590+
f"Environment variables are too large to pass directly to container "
591+
"(> 90% of 8192). Writing environment variables to file "
592+
f"{efs_environment_file_uri}."
590593
)
591594
confirm_write = True
592595
else:
@@ -632,7 +635,7 @@ def generate_batch_job_builder(
632635
]
633636
if tmp_mount_point:
634637
vol_configurations.append(BatchEFSConfiguration(tmp_mount_point, read_only=False))
635-
logger.info(f"Constructing BatchJobBuilder instance...")
638+
logger.info("Constructing BatchJobBuilder instance...")
636639
return BatchJobBuilder(
637640
image=demand_execution.execution_image,
638641
job_definition_name=env_base.get_job_name(

src/aibs_informatics_aws_lambda/handlers/demand/scaffolding.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def setup_file_system(self, context_manager: DemandExecutionContextManager):
124124
Args:
125125
context_manager (DemandExecutionContextManager): context manager
126126
"""
127-
working_path = context_manager.container_working_path
127+
working_path = context_manager.container_working_path # noqa: F841
128128
# working_path.mkdir(parents=True, exist_ok=True)
129129

130130

0 commit comments

Comments
 (0)