Skip to content

Commit 5f4be34

Browse files
Enable ruff Formatter in CI (#1331)
* Update Megalinter config in CI to include ruff format and statuses * Drop missing file from manifest * Apply formatters * Fix linter issues --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
1 parent 07586bd commit 5f4be34

13 files changed

Lines changed: 125 additions & 353 deletions

File tree

.github/workflows/deploy-python.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ jobs:
154154
- name: Install Dependencies
155155
run: |
156156
pip install -U pip
157-
pip install -U wheel setuptools packaging twine
157+
pip install -U wheel setuptools packaging twine
158158
159159
- name: Download Artifacts
160160
uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # 4.1.4

.github/workflows/mega-linter.yml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ jobs:
2828
contents: write
2929
issues: write
3030
pull-requests: write
31+
statuses: write
3132
steps:
3233
# Git Checkout
3334
- name: Checkout Code
@@ -40,13 +41,15 @@ jobs:
4041
id: ml
4142
# You can override MegaLinter flavor used to have faster performances
4243
# More info at https://megalinter.io/flavors/
43-
uses: oxsecurity/megalinter/flavors/python@ec124f7998718d79379a3c5b39f5359952baf21d # 8.4.2
44+
uses: oxsecurity/megalinter/flavors/python@146333030da68e2e58c6ff826633824fabe01eaf # 8.5.0
4445
env:
4546
# All available variables are described in documentation
4647
# https://megalinter.io/configuration/
4748
VALIDATE_ALL_CODEBASE: "true"
4849
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
4950
# ADD YOUR CUSTOM ENV VARIABLES HERE OR DEFINE THEM IN A FILE .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
51+
GITHUB_STATUS_REPORTER: "true"
52+
GITHUB_COMMENT_REPORTER: "true"
5053
PYTHON_RUFF_ARGUMENTS: --config pyproject.toml --config 'output-format="github"'
5154
PYTHON_RUFF_FORMAT_ARGUMENTS: --config pyproject.toml --config 'output-format="github"'
5255

.mega-linter.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,9 @@ ENABLE_LINTERS: # If you use ENABLE_LINTERS variable, all other linters will be
1919
- YAML_V8R
2020
- YAML_YAMLLINT
2121

22+
PYTHON_DEFAULT_STYLE: ruff
2223
PYTHON_RUFF_CONFIG_FILE: pyproject.toml
23-
PYTHON_RUFF_CLI_LINT_MODE: project
2424
PYTHON_RUFF_FORMAT_CONFIG_FILE: pyproject.toml
25-
PYTHON_RUFF_FORMAT_CLI_LINT_MODE: project
2625
MARKDOWN_MARKDOWN_LINK_CHECK_FILTER_REGEX_EXCLUDE: "tests/.*"
2726
MARKDOWN_MARKDOWNLINT_FILTER_REGEX_EXCLUDE: "tests/.*"
2827
MARKDOWN_MARKDOWNLINT_ARGUMENTS: "--disable=MD041"

newrelic/config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3983,7 +3983,9 @@ def _process_module_builtin_defaults():
39833983
)
39843984
_process_module_definition("gearman.worker", "newrelic.hooks.application_gearman", "instrument_gearman_worker")
39853985

3986-
_process_module_definition("aiobotocore.client", "newrelic.hooks.external_aiobotocore", "instrument_aiobotocore_client")
3986+
_process_module_definition(
3987+
"aiobotocore.client", "newrelic.hooks.external_aiobotocore", "instrument_aiobotocore_client"
3988+
)
39873989

39883990
_process_module_definition(
39893991
"aiobotocore.endpoint", "newrelic.hooks.external_aiobotocore", "instrument_aiobotocore_endpoint"

newrelic/hooks/database_aiomysql.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,9 @@ def __await__(self):
5757
except StopIteration as e:
5858
# Catch the StopIteration and wrap the return value.
5959
cursor = e.value
60-
wrapped_cursor = self.__cursor_wrapper__(cursor, self._nr_dbapi2_module, self._nr_connect_params, self._nr_cursor_args)
60+
wrapped_cursor = self.__cursor_wrapper__(
61+
cursor, self._nr_dbapi2_module, self._nr_connect_params, self._nr_cursor_args
62+
)
6163
return wrapped_cursor # Return here instead of raising StopIteration to properly follow generator protocol
6264

6365

newrelic/hooks/external_aiobotocore.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# Copyright 2010 New Relic, Inc.
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,20 +12,21 @@
1312
# See the License for the specific language governing permissions and
1413
# limitations under the License.
1514
import logging
16-
import traceback
1715
import sys
18-
from aiobotocore.response import StreamingBody
16+
import traceback
1917
from io import BytesIO
2018

19+
from aiobotocore.response import StreamingBody
20+
2121
from newrelic.api.external_trace import ExternalTrace
2222
from newrelic.common.object_wrapper import wrap_function_wrapper
2323
from newrelic.hooks.external_botocore import (
24+
EMBEDDING_STREAMING_UNSUPPORTED_LOG_MESSAGE,
25+
RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE,
2426
AsyncEventStreamWrapper,
2527
handle_bedrock_exception,
26-
run_bedrock_response_extractor,
2728
run_bedrock_request_extractor,
28-
EMBEDDING_STREAMING_UNSUPPORTED_LOG_MESSAGE,
29-
RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE,
29+
run_bedrock_response_extractor,
3030
)
3131

3232
_logger = logging.getLogger(__name__)
@@ -160,7 +160,7 @@ async def wrap_client__make_api_call(wrapped, instance, args, kwargs):
160160
run_bedrock_response_extractor(response_extractor, response_body, bedrock_attrs, is_embedding, transaction)
161161

162162
except Exception:
163-
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
163+
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
164164

165165
return response
166166

newrelic/hooks/external_botocore.py

Lines changed: 26 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import json
1615
import inspect
16+
import json
1717
import logging
1818
import re
1919
import sys
@@ -30,11 +30,7 @@
3030
from newrelic.api.time_trace import current_trace, get_trace_linking_metadata
3131
from newrelic.api.transaction import current_transaction
3232
from newrelic.common.async_wrapper import async_wrapper as get_async_wrapper
33-
from newrelic.common.object_wrapper import (
34-
ObjectProxy,
35-
function_wrapper,
36-
wrap_function_wrapper,
37-
)
33+
from newrelic.common.object_wrapper import ObjectProxy, function_wrapper, wrap_function_wrapper
3834
from newrelic.common.package_version_utils import get_package_version
3935
from newrelic.common.signature import bind_args
4036
from newrelic.core.config import global_settings
@@ -141,9 +137,9 @@ def extract_firehose_agent_attrs(instance, *args, **kwargs):
141137
region = instance._client_config.region_name
142138
if account_id and region:
143139
agent_attrs["cloud.platform"] = "aws_kinesis_delivery_streams"
144-
agent_attrs[
145-
"cloud.resource_id"
146-
] = f"arn:aws:firehose:{region}:{account_id}:deliverystream/{stream_name}"
140+
agent_attrs["cloud.resource_id"] = (
141+
f"arn:aws:firehose:{region}:{account_id}:deliverystream/{stream_name}"
142+
)
147143
except Exception as e:
148144
_logger.debug("Failed to capture AWS Kinesis Delivery Stream (Firehose) info.", exc_info=True)
149145
return agent_attrs
@@ -501,18 +497,8 @@ def extract_bedrock_cohere_model_streaming_response(response_body, bedrock_attrs
501497

502498
NULL_EXTRACTOR = lambda *args: {} # Empty extractor that returns nothing
503499
MODEL_EXTRACTORS = [ # Order is important here, avoiding dictionaries
504-
(
505-
"amazon.titan-embed",
506-
extract_bedrock_titan_embedding_model_request,
507-
NULL_EXTRACTOR,
508-
NULL_EXTRACTOR,
509-
),
510-
(
511-
"cohere.embed",
512-
extract_bedrock_cohere_embedding_model_request,
513-
NULL_EXTRACTOR,
514-
NULL_EXTRACTOR,
515-
),
500+
("amazon.titan-embed", extract_bedrock_titan_embedding_model_request, NULL_EXTRACTOR, NULL_EXTRACTOR),
501+
("cohere.embed", extract_bedrock_cohere_embedding_model_request, NULL_EXTRACTOR, NULL_EXTRACTOR),
516502
(
517503
"amazon.titan",
518504
extract_bedrock_titan_text_model_request,
@@ -551,17 +537,13 @@ def handle_bedrock_exception(
551537
exc, is_embedding, model, span_id, trace_id, request_extractor, request_body, ft, transaction
552538
):
553539
try:
554-
bedrock_attrs = {
555-
"model": model,
556-
"span_id": span_id,
557-
"trace_id": trace_id,
558-
}
540+
bedrock_attrs = {"model": model, "span_id": span_id, "trace_id": trace_id}
559541
try:
560542
request_extractor(request_body, bedrock_attrs)
561543
except json.decoder.JSONDecodeError:
562544
pass
563545
except Exception:
564-
_logger.warning(REQUEST_EXTACTOR_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
546+
_logger.warning(REQUEST_EXTACTOR_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
565547

566548
error_attributes = bedrock_error_attributes(exc, bedrock_attrs)
567549
notice_error_attributes = {
@@ -576,9 +558,7 @@ def handle_bedrock_exception(
576558
notice_error_attributes.update({"completion_id": str(uuid.uuid4())})
577559

578560
if ft:
579-
ft.notice_error(
580-
attributes=notice_error_attributes,
581-
)
561+
ft.notice_error(attributes=notice_error_attributes)
582562

583563
ft.__exit__(*sys.exc_info())
584564
error_attributes["duration"] = ft.duration * 1000
@@ -588,7 +568,7 @@ def handle_bedrock_exception(
588568
else:
589569
handle_chat_completion_event(transaction, error_attributes)
590570
except Exception:
591-
_logger.warning(EXCEPTION_HANDLING_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
571+
_logger.warning(EXCEPTION_HANDLING_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
592572

593573
raise
594574

@@ -598,7 +578,7 @@ def run_bedrock_response_extractor(response_extractor, response_body, bedrock_at
598578
try:
599579
response_extractor(response_body, bedrock_attrs)
600580
except Exception:
601-
_logger.warning(RESPONSE_EXTRACTOR_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
581+
_logger.warning(RESPONSE_EXTRACTOR_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
602582

603583
if is_embedding:
604584
handle_embedding_event(transaction, bedrock_attrs)
@@ -612,7 +592,7 @@ def run_bedrock_request_extractor(request_extractor, request_body, bedrock_attrs
612592
except json.decoder.JSONDecodeError:
613593
pass
614594
except Exception:
615-
_logger.warning(REQUEST_EXTACTOR_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
595+
_logger.warning(REQUEST_EXTACTOR_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
616596

617597

618598
def wrap_bedrock_runtime_invoke_model(response_streaming=False):
@@ -739,7 +719,7 @@ def _wrap_bedrock_runtime_invoke_model(wrapped, instance, args, kwargs):
739719
run_bedrock_response_extractor(response_extractor, response_body, bedrock_attrs, is_embedding, transaction)
740720

741721
except Exception:
742-
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
722+
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
743723

744724
return response
745725

@@ -830,7 +810,7 @@ def record_stream_chunk(self, return_val, transaction):
830810
if _type == "content_block_stop":
831811
record_events_on_stop_iteration(self, transaction)
832812
except Exception:
833-
_logger.warning(RESPONSE_EXTRACTOR_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
813+
_logger.warning(RESPONSE_EXTRACTOR_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
834814

835815

836816
def record_events_on_stop_iteration(self, transaction):
@@ -846,7 +826,7 @@ def record_events_on_stop_iteration(self, transaction):
846826
bedrock_attrs["duration"] = self._nr_ft.duration * 1000
847827
handle_chat_completion_event(transaction, bedrock_attrs)
848828
except Exception:
849-
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
829+
_logger.warning(RESPONSE_PROCESSING_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
850830

851831
# Clear cached data as this can be very large.
852832
self._nr_bedrock_attrs.clear()
@@ -870,9 +850,7 @@ def record_error(self, transaction, exc):
870850
}
871851
notice_error_attributes.update({"completion_id": str(uuid.uuid4())})
872852

873-
ft.notice_error(
874-
attributes=notice_error_attributes,
875-
)
853+
ft.notice_error(attributes=notice_error_attributes)
876854

877855
ft.__exit__(*sys.exc_info())
878856
error_attributes["duration"] = ft.duration * 1000
@@ -882,7 +860,7 @@ def record_error(self, transaction, exc):
882860
# Clear cached data as this can be very large.
883861
error_attributes.clear()
884862
except Exception:
885-
_logger.warning(EXCEPTION_HANDLING_FAILURE_LOG_MESSAGE % traceback.format_exception(*sys.exc_info()))
863+
_logger.warning(EXCEPTION_HANDLING_FAILURE_LOG_MESSAGE, traceback.format_exception(*sys.exc_info()))
886864

887865

888866
def handle_embedding_event(transaction, bedrock_attrs):
@@ -898,7 +876,7 @@ def handle_embedding_event(transaction, bedrock_attrs):
898876
trace_id = bedrock_attrs.get("trace_id", None)
899877
request_id = bedrock_attrs.get("request_id", None)
900878
model = bedrock_attrs.get("model", None)
901-
input = bedrock_attrs.get("input")
879+
input_ = bedrock_attrs.get("input")
902880

903881
embedding_dict = {
904882
"vendor": "bedrock",
@@ -907,7 +885,7 @@ def handle_embedding_event(transaction, bedrock_attrs):
907885
"span_id": span_id,
908886
"trace_id": trace_id,
909887
"token_count": (
910-
settings.ai_monitoring.llm_token_count_callback(model, input)
888+
settings.ai_monitoring.llm_token_count_callback(model, input_)
911889
if settings.ai_monitoring.llm_token_count_callback
912890
else None
913891
),
@@ -920,7 +898,7 @@ def handle_embedding_event(transaction, bedrock_attrs):
920898
embedding_dict.update(llm_metadata_dict)
921899

922900
if settings.ai_monitoring.record_content.enabled:
923-
embedding_dict["input"] = input
901+
embedding_dict["input"] = input_
924902

925903
embedding_dict = {k: v for k, v in embedding_dict.items() if v is not None}
926904
transaction.record_custom_event("LlmEmbedding", embedding_dict)
@@ -987,13 +965,7 @@ def handle_chat_completion_event(transaction, bedrock_attrs):
987965

988966

989967
def dynamodb_datastore_trace(
990-
product,
991-
target,
992-
operation,
993-
host=None,
994-
port_path_or_id=None,
995-
database_name=None,
996-
async_wrapper=None,
968+
product, target, operation, host=None, port_path_or_id=None, database_name=None, async_wrapper=None
997969
):
998970
@function_wrapper
999971
def _nr_dynamodb_datastore_trace_wrapper_(wrapped, instance, args, kwargs):
@@ -1080,9 +1052,9 @@ def _nr_dynamodb_datastore_trace_wrapper_(wrapped, instance, args, kwargs):
10801052
partition = "aws-us-gov"
10811053

10821054
if partition and region and account_id and _target:
1083-
agent_attrs[
1084-
"cloud.resource_id"
1085-
] = f"arn:{partition}:dynamodb:{region}:{account_id:012d}:table/{_target}"
1055+
agent_attrs["cloud.resource_id"] = (
1056+
f"arn:{partition}:dynamodb:{region}:{account_id:012d}:table/{_target}"
1057+
)
10861058
agent_attrs["db.system"] = "DynamoDB"
10871059

10881060
except Exception as e:
@@ -1120,14 +1092,7 @@ def _nr_aws_function_trace_wrapper_(wrapped, instance, args, kwargs):
11201092
_destination_name = destination_name(*args, **kwargs) if destination_name is not None else None
11211093
name = f"{operation}/{_destination_name}" if _destination_name else operation
11221094

1123-
trace = FunctionTrace(
1124-
name=name,
1125-
group=library,
1126-
params=params,
1127-
terminal=terminal,
1128-
parent=parent,
1129-
source=wrapped,
1130-
)
1095+
trace = FunctionTrace(name=name, group=library, params=params, terminal=terminal, parent=parent, source=wrapped)
11311096

11321097
# Attach extracted agent attributes.
11331098
_agent_attrs = extract_agent_attrs(instance, *args, **kwargs) if extract_agent_attrs is not None else {}

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
output-format = "grouped"
33
line-length = 120
44
target-version = "py37"
5+
force-exclude = true # Fixes issue with megalinter config preventing exclusion of files
56
extend-exclude = [
67
"newrelic/packages/",
78
"setup.py",

0 commit comments

Comments
 (0)