quant-ranger 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.
- quant_ranger/__init__.py +59 -0
- quant_ranger/__main__.py +4 -0
- quant_ranger/_impl/__init__.py +1 -0
- quant_ranger/_impl/_plugins.py +180 -0
- quant_ranger/_impl/aggregators/__init__.py +11 -0
- quant_ranger/_impl/aggregators/_base.py +82 -0
- quant_ranger/_impl/aggregators/_incident_io/__init__.py +3 -0
- quant_ranger/_impl/aggregators/_incident_io/_aggregator.py +254 -0
- quant_ranger/_impl/aggregators/_incident_io/_client.py +136 -0
- quant_ranger/_impl/aggregators/_log_failures.py +67 -0
- quant_ranger/_impl/artifacts.py +86 -0
- quant_ranger/_impl/cli/__init__.py +3 -0
- quant_ranger/_impl/cli/_aggregate.py +149 -0
- quant_ranger/_impl/cli/_app.py +355 -0
- quant_ranger/_impl/cli/_helpers.py +95 -0
- quant_ranger/_impl/cli/_update.py +374 -0
- quant_ranger/_impl/cli_options.py +44 -0
- quant_ranger/_impl/git.py +122 -0
- quant_ranger/_impl/github.py +681 -0
- quant_ranger/_impl/helpers.py +263 -0
- quant_ranger/_impl/logger.py +178 -0
- quant_ranger/_impl/models.py +238 -0
- quant_ranger/_impl/runtime.py +17 -0
- quant_ranger/_impl/sandbox.py +183 -0
- quant_ranger/_impl/scanners/__init__.py +10 -0
- quant_ranger/_impl/scanners/_base.py +119 -0
- quant_ranger/_impl/scanners/_repositories.py +19 -0
- quant_ranger/_impl/scanners/_repository_file.py +43 -0
- quant_ranger/_impl/site_config.py +220 -0
- quant_ranger/_impl/testing.py +360 -0
- quant_ranger/_impl/updaters/__init__.py +23 -0
- quant_ranger/_impl/updaters/_base.py +214 -0
- quant_ranger/_impl/updaters/_copier/__init__.py +7 -0
- quant_ranger/_impl/updaters/_copier/_common.py +228 -0
- quant_ranger/_impl/updaters/_copier/_migration.py +304 -0
- quant_ranger/_impl/updaters/_copier/_update.py +254 -0
- quant_ranger/_impl/updaters/_custom.py +130 -0
- quant_ranger/_impl/updaters/_github_app_token.py +243 -0
- quant_ranger/_impl/updaters/_node_dependency_cooldown.py +669 -0
- quant_ranger/_impl/updaters/_pixi_update/__init__.py +3 -0
- quant_ranger/_impl/updaters/_pixi_update/_auth.py +273 -0
- quant_ranger/_impl/updaters/_pixi_update/_update.py +595 -0
- quant_ranger/_impl/updaters/_pixi_version.py +288 -0
- quant_ranger/_impl/updaters/_zizmor.py +112 -0
- quant_ranger/_impl/updaters/zizmor.yml +69 -0
- quant_ranger/aggregators.py +6 -0
- quant_ranger/cli.py +3 -0
- quant_ranger/py.typed +0 -0
- quant_ranger/scanners.py +10 -0
- quant_ranger/site_config.py +23 -0
- quant_ranger/updaters.py +8 -0
- quant_ranger-0.1.0.dist-info/METADATA +89 -0
- quant_ranger-0.1.0.dist-info/RECORD +56 -0
- quant_ranger-0.1.0.dist-info/WHEEL +4 -0
- quant_ranger-0.1.0.dist-info/entry_points.txt +2 -0
- quant_ranger-0.1.0.dist-info/licenses/LICENSE +28 -0
quant_ranger/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import warnings as _warnings
|
|
2
|
+
from importlib import metadata as _metadata
|
|
3
|
+
|
|
4
|
+
from quant_ranger._impl.git import RepositoryCheckout
|
|
5
|
+
from quant_ranger._impl.github import GitHubClient, GitHubError, PullRequestOptions
|
|
6
|
+
from quant_ranger._impl.helpers import (
|
|
7
|
+
CommandError,
|
|
8
|
+
ExecOutput,
|
|
9
|
+
get_exec_output_silently,
|
|
10
|
+
)
|
|
11
|
+
from quant_ranger._impl.logger import Logger
|
|
12
|
+
from quant_ranger._impl.models import (
|
|
13
|
+
Diagnostics,
|
|
14
|
+
PathUpdateItem,
|
|
15
|
+
RepositoryRef,
|
|
16
|
+
ScanFailure,
|
|
17
|
+
Schedule,
|
|
18
|
+
ScheduledPathUpdateItem,
|
|
19
|
+
ScheduledUpdateItem,
|
|
20
|
+
Status,
|
|
21
|
+
UpdateItem,
|
|
22
|
+
UpdateOptions,
|
|
23
|
+
UpdateOutcome,
|
|
24
|
+
UpdateOutput,
|
|
25
|
+
UpdateResult,
|
|
26
|
+
)
|
|
27
|
+
from quant_ranger._impl.runtime import RunContext
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"CommandError",
|
|
31
|
+
"Diagnostics",
|
|
32
|
+
"ExecOutput",
|
|
33
|
+
"GitHubClient",
|
|
34
|
+
"GitHubError",
|
|
35
|
+
"Logger",
|
|
36
|
+
"PathUpdateItem",
|
|
37
|
+
"PullRequestOptions",
|
|
38
|
+
"RepositoryCheckout",
|
|
39
|
+
"RepositoryRef",
|
|
40
|
+
"RunContext",
|
|
41
|
+
"ScanFailure",
|
|
42
|
+
"Schedule",
|
|
43
|
+
"ScheduledPathUpdateItem",
|
|
44
|
+
"ScheduledUpdateItem",
|
|
45
|
+
"Status",
|
|
46
|
+
"UpdateItem",
|
|
47
|
+
"UpdateOptions",
|
|
48
|
+
"UpdateOutcome",
|
|
49
|
+
"UpdateOutput",
|
|
50
|
+
"UpdateResult",
|
|
51
|
+
"__version__",
|
|
52
|
+
"get_exec_output_silently",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
__version__ = _metadata.version(__name__)
|
|
57
|
+
except _metadata.PackageNotFoundError as e: # pragma: no cover
|
|
58
|
+
_warnings.warn(f"Could not determine version of {__name__}\n{e!s}", stacklevel=2)
|
|
59
|
+
__version__ = "unknown"
|
quant_ranger/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal implementation details for quant-ranger."""
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
from importlib.metadata import EntryPoint, entry_points
|
|
2
|
+
from typing import ClassVar, Protocol
|
|
3
|
+
|
|
4
|
+
from quant_ranger._impl.aggregators import Aggregator, AnyAggregator
|
|
5
|
+
from quant_ranger._impl.helpers import CliError
|
|
6
|
+
from quant_ranger._impl.logger import Logger
|
|
7
|
+
from quant_ranger._impl.site_config import SiteConfig
|
|
8
|
+
from quant_ranger._impl.updaters import AnyUpdater, Updater
|
|
9
|
+
|
|
10
|
+
_UPDATER_ENTRY_POINT_GROUP = "quant_ranger.updaters"
|
|
11
|
+
_AGGREGATOR_ENTRY_POINT_GROUP = "quant_ranger.aggregators"
|
|
12
|
+
_SITE_CONFIG_ENTRY_POINT_GROUP = "quant_ranger.site_config"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _NamedCommand(Protocol):
|
|
16
|
+
name: ClassVar[str]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def available_updater_types(
|
|
20
|
+
*,
|
|
21
|
+
builtin_types: tuple[type[AnyUpdater], ...],
|
|
22
|
+
logger: Logger,
|
|
23
|
+
load_plugins: bool = True,
|
|
24
|
+
) -> tuple[type[AnyUpdater], ...]:
|
|
25
|
+
_check_unique_builtin_names(builtin_types)
|
|
26
|
+
if not load_plugins:
|
|
27
|
+
return builtin_types
|
|
28
|
+
|
|
29
|
+
logger.debug("Loading updater plugins:")
|
|
30
|
+
plugin_types = _discover_plugin_types(
|
|
31
|
+
group=_UPDATER_ENTRY_POINT_GROUP,
|
|
32
|
+
base_type=Updater,
|
|
33
|
+
taken_names={builtin_type.name for builtin_type in builtin_types},
|
|
34
|
+
logger=logger,
|
|
35
|
+
)
|
|
36
|
+
return (*builtin_types, *plugin_types)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def available_aggregator_types(
|
|
40
|
+
*,
|
|
41
|
+
builtin_types: tuple[type[AnyAggregator], ...],
|
|
42
|
+
logger: Logger,
|
|
43
|
+
load_plugins: bool = True,
|
|
44
|
+
) -> tuple[type[AnyAggregator], ...]:
|
|
45
|
+
_check_unique_builtin_names(builtin_types)
|
|
46
|
+
if not load_plugins:
|
|
47
|
+
return builtin_types
|
|
48
|
+
|
|
49
|
+
logger.debug("Loading aggregator plugins:")
|
|
50
|
+
plugin_types = _discover_plugin_types(
|
|
51
|
+
group=_AGGREGATOR_ENTRY_POINT_GROUP,
|
|
52
|
+
base_type=Aggregator,
|
|
53
|
+
taken_names={builtin_type.name for builtin_type in builtin_types},
|
|
54
|
+
logger=logger,
|
|
55
|
+
)
|
|
56
|
+
return (*builtin_types, *plugin_types)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load_site_config(
|
|
60
|
+
*,
|
|
61
|
+
logger: Logger,
|
|
62
|
+
load_plugins: bool = True,
|
|
63
|
+
) -> SiteConfig:
|
|
64
|
+
if not load_plugins:
|
|
65
|
+
return SiteConfig()
|
|
66
|
+
|
|
67
|
+
site_config_entry_points = entry_points(group=_SITE_CONFIG_ENTRY_POINT_GROUP)
|
|
68
|
+
if len(site_config_entry_points) > 1:
|
|
69
|
+
# Sorted so the error message is deterministic.
|
|
70
|
+
names = ", ".join(
|
|
71
|
+
f"{entry_point.name!r} ({entry_point.value!r})"
|
|
72
|
+
for entry_point in sorted(
|
|
73
|
+
site_config_entry_points,
|
|
74
|
+
key=lambda entry_point: entry_point.name,
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
raise CliError(
|
|
78
|
+
f"Multiple site config plugins are installed: {names}. Install exactly one."
|
|
79
|
+
)
|
|
80
|
+
if not site_config_entry_points:
|
|
81
|
+
return SiteConfig()
|
|
82
|
+
|
|
83
|
+
(entry_point,) = site_config_entry_points
|
|
84
|
+
try:
|
|
85
|
+
value = entry_point.load()
|
|
86
|
+
except (SystemExit, Exception) as error:
|
|
87
|
+
raise CliError(
|
|
88
|
+
f"Site config plugin {entry_point.name!r} ({entry_point.value!r}) "
|
|
89
|
+
f"failed to load: {error}."
|
|
90
|
+
) from error
|
|
91
|
+
|
|
92
|
+
if not isinstance(value, SiteConfig):
|
|
93
|
+
raise CliError(
|
|
94
|
+
f"Site config plugin {entry_point.name!r} ({entry_point.value!r}) "
|
|
95
|
+
f"must load a SiteConfig instance, got {value!r}."
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
package = entry_point.module.partition(".")[0]
|
|
99
|
+
logger.debug(f"Loaded site config {entry_point.name!r} ({package}).")
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _check_unique_builtin_names(builtin_types: tuple[type[_NamedCommand], ...]) -> None:
|
|
104
|
+
seen_types: dict[str, type[_NamedCommand]] = {}
|
|
105
|
+
for builtin_type in builtin_types:
|
|
106
|
+
if builtin_type.name in seen_types:
|
|
107
|
+
msg = (
|
|
108
|
+
f"Duplicate builtin command name {builtin_type.name!r}: "
|
|
109
|
+
f"{seen_types[builtin_type.name].__name__} and "
|
|
110
|
+
f"{builtin_type.__name__}."
|
|
111
|
+
)
|
|
112
|
+
raise ValueError(msg)
|
|
113
|
+
seen_types[builtin_type.name] = builtin_type
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _discover_plugin_types[T: _NamedCommand](
|
|
117
|
+
*,
|
|
118
|
+
group: str,
|
|
119
|
+
base_type: type[T],
|
|
120
|
+
taken_names: set[str],
|
|
121
|
+
logger: Logger,
|
|
122
|
+
) -> tuple[type[T], ...]:
|
|
123
|
+
discovered_types: list[type[T]] = []
|
|
124
|
+
sorted_entry_points = sorted(
|
|
125
|
+
entry_points(group=group),
|
|
126
|
+
key=lambda entry_point: entry_point.name,
|
|
127
|
+
)
|
|
128
|
+
for entry_point in sorted_entry_points:
|
|
129
|
+
try:
|
|
130
|
+
value = entry_point.load()
|
|
131
|
+
# SystemExit is not an Exception: a plugin calling sys.exit() at
|
|
132
|
+
# import time must not kill the CLI.
|
|
133
|
+
except (SystemExit, Exception) as error:
|
|
134
|
+
_report_plugin_error(
|
|
135
|
+
logger,
|
|
136
|
+
entry_point,
|
|
137
|
+
f"failed to load: {error}",
|
|
138
|
+
)
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
if not isinstance(value, type) or not issubclass(value, base_type):
|
|
142
|
+
_report_plugin_error(
|
|
143
|
+
logger,
|
|
144
|
+
entry_point,
|
|
145
|
+
f"must load a subclass of {base_type.__name__}, got {value!r}",
|
|
146
|
+
)
|
|
147
|
+
continue
|
|
148
|
+
|
|
149
|
+
if not isinstance(getattr(value, "name", None), str):
|
|
150
|
+
_report_plugin_error(
|
|
151
|
+
logger,
|
|
152
|
+
entry_point,
|
|
153
|
+
f"must define a `name` string class attribute, got {value!r}",
|
|
154
|
+
)
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
if value.name in taken_names:
|
|
158
|
+
_report_plugin_error(
|
|
159
|
+
logger,
|
|
160
|
+
entry_point,
|
|
161
|
+
f"command name {value.name!r} duplicates an existing command",
|
|
162
|
+
)
|
|
163
|
+
continue
|
|
164
|
+
|
|
165
|
+
taken_names.add(value.name)
|
|
166
|
+
discovered_types.append(value)
|
|
167
|
+
package = value.__module__.partition(".")[0]
|
|
168
|
+
logger.debug(f" {value.name} ({package})")
|
|
169
|
+
return tuple(discovered_types)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _report_plugin_error(
|
|
173
|
+
logger: Logger,
|
|
174
|
+
entry_point: EntryPoint,
|
|
175
|
+
reason: str,
|
|
176
|
+
) -> None:
|
|
177
|
+
logger.warning(
|
|
178
|
+
f"Skipping plugin entry point {entry_point.name!r} "
|
|
179
|
+
f"from group {entry_point.group!r} ({entry_point.value!r}): {reason}."
|
|
180
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from ._base import Aggregator, AggregatorOptions, AnyAggregator
|
|
2
|
+
from ._incident_io import IncidentIoAlertsAggregator
|
|
3
|
+
from ._log_failures import LogFailuresAggregator
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"Aggregator",
|
|
7
|
+
"AggregatorOptions",
|
|
8
|
+
"AnyAggregator",
|
|
9
|
+
"IncidentIoAlertsAggregator",
|
|
10
|
+
"LogFailuresAggregator",
|
|
11
|
+
]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from typing import Any, ClassVar, get_args, get_origin
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict
|
|
6
|
+
|
|
7
|
+
from quant_ranger._impl.logger import Logger
|
|
8
|
+
from quant_ranger._impl.models import (
|
|
9
|
+
ScanFailure,
|
|
10
|
+
UpdateItem,
|
|
11
|
+
UpdateItemTypeMixin,
|
|
12
|
+
UpdateOutput,
|
|
13
|
+
UpdateOutputTypeMixin,
|
|
14
|
+
UpdateResult,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AggregatorOptions(BaseModel):
|
|
19
|
+
"""Typed CLI/runtime options for an aggregator."""
|
|
20
|
+
|
|
21
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Aggregator[
|
|
25
|
+
ItemT: UpdateItem = UpdateItem,
|
|
26
|
+
OutputT: UpdateOutput = UpdateOutput,
|
|
27
|
+
OptionsT: AggregatorOptions = AggregatorOptions,
|
|
28
|
+
](UpdateItemTypeMixin, UpdateOutputTypeMixin, ABC):
|
|
29
|
+
"""Post-process the structured results of an updater run."""
|
|
30
|
+
|
|
31
|
+
name: ClassVar[str]
|
|
32
|
+
description: ClassVar[str] = ""
|
|
33
|
+
options_type: ClassVar[type[AggregatorOptions]] = AggregatorOptions
|
|
34
|
+
|
|
35
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
36
|
+
super().__init_subclass__(**kwargs)
|
|
37
|
+
if "options_type" not in cls.__dict__:
|
|
38
|
+
setattr(
|
|
39
|
+
cls,
|
|
40
|
+
"options_type",
|
|
41
|
+
_infer_aggregator_options_type(cls),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def __init__(self, options: OptionsT) -> None:
|
|
45
|
+
self.options: OptionsT = options
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def aggregate(
|
|
49
|
+
self,
|
|
50
|
+
results: Sequence[UpdateResult[OutputT, ItemT]],
|
|
51
|
+
logger: Logger,
|
|
52
|
+
scan_failures: Sequence[ScanFailure],
|
|
53
|
+
updater_name: str,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""Consume all updater results after the update run completes."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
type AnyAggregator = Aggregator[Any, Any, Any]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _infer_aggregator_options_type(cls: type[Any]) -> type[AggregatorOptions]:
|
|
62
|
+
aggregator_base = next(
|
|
63
|
+
(base for base in cls.__orig_bases__ if _is_aggregator_base(base)),
|
|
64
|
+
None,
|
|
65
|
+
)
|
|
66
|
+
if aggregator_base is None:
|
|
67
|
+
msg = f"{cls.__name__} must inherit from Aggregator[...] or set options_type."
|
|
68
|
+
raise TypeError(msg)
|
|
69
|
+
|
|
70
|
+
options_type = get_args(aggregator_base)[2]
|
|
71
|
+
if not isinstance(options_type, type) or not issubclass(
|
|
72
|
+
options_type,
|
|
73
|
+
AggregatorOptions,
|
|
74
|
+
):
|
|
75
|
+
msg = f"{cls.__name__} options type must be a subclass of AggregatorOptions."
|
|
76
|
+
raise TypeError(msg)
|
|
77
|
+
return options_type
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _is_aggregator_base(base: Any) -> bool:
|
|
81
|
+
origin = get_origin(base)
|
|
82
|
+
return isinstance(origin, type) and issubclass(origin, Aggregator)
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Annotated, Any, NamedTuple, override
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from quant_ranger._impl.helpers import CliError
|
|
8
|
+
from quant_ranger._impl.logger import Logger
|
|
9
|
+
from quant_ranger._impl.models import (
|
|
10
|
+
Diagnostics,
|
|
11
|
+
RepositoryRef,
|
|
12
|
+
ScanFailure,
|
|
13
|
+
Status,
|
|
14
|
+
UpdateItem,
|
|
15
|
+
UpdateOutput,
|
|
16
|
+
UpdateResult,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from .._base import Aggregator, AggregatorOptions
|
|
20
|
+
from ._client import IncidentIoClient
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _AlertEvent(NamedTuple):
|
|
24
|
+
"""An alert event payload with the note to attach, or None when resolved."""
|
|
25
|
+
|
|
26
|
+
repository: str
|
|
27
|
+
deduplication_key: str
|
|
28
|
+
payload: dict[str, Any]
|
|
29
|
+
note: str | None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class IncidentIoAlertsOptions(AggregatorOptions):
|
|
33
|
+
alert_source_config_id: Annotated[
|
|
34
|
+
str,
|
|
35
|
+
typer.Option(
|
|
36
|
+
"--alert-source-config-id",
|
|
37
|
+
help="ID of the incident.io HTTP alert source to send events to.",
|
|
38
|
+
),
|
|
39
|
+
]
|
|
40
|
+
token: Annotated[
|
|
41
|
+
str,
|
|
42
|
+
typer.Option(
|
|
43
|
+
"--token",
|
|
44
|
+
envvar="INCIDENT_IO_TOKEN",
|
|
45
|
+
help="incident.io alert source bearer token.",
|
|
46
|
+
),
|
|
47
|
+
]
|
|
48
|
+
management_token: Annotated[
|
|
49
|
+
str,
|
|
50
|
+
typer.Option(
|
|
51
|
+
"--management-token",
|
|
52
|
+
envvar="INCIDENT_IO_MANAGEMENT_TOKEN",
|
|
53
|
+
help=(
|
|
54
|
+
"incident.io API token with the alerts.view and alerts.edit "
|
|
55
|
+
"scopes (distinct from the alert source token)."
|
|
56
|
+
),
|
|
57
|
+
),
|
|
58
|
+
]
|
|
59
|
+
deduplication_key_prefix: Annotated[
|
|
60
|
+
str,
|
|
61
|
+
typer.Option(
|
|
62
|
+
"--deduplication-key-prefix",
|
|
63
|
+
help=(
|
|
64
|
+
"Prefix for per-repository alert deduplication keys. Use a "
|
|
65
|
+
"distinct prefix per updater pipeline (e.g. "
|
|
66
|
+
"`quant-ranger/pixi-update`) so pipelines do not resolve each "
|
|
67
|
+
"other's alerts."
|
|
68
|
+
),
|
|
69
|
+
),
|
|
70
|
+
] = "quant-ranger"
|
|
71
|
+
source_url: Annotated[
|
|
72
|
+
str,
|
|
73
|
+
typer.Option(
|
|
74
|
+
"--source-url",
|
|
75
|
+
help=(
|
|
76
|
+
"Link attached to each alert, e.g. the GitHub Actions run "
|
|
77
|
+
"that produced the results file."
|
|
78
|
+
),
|
|
79
|
+
),
|
|
80
|
+
]
|
|
81
|
+
team: Annotated[
|
|
82
|
+
str,
|
|
83
|
+
typer.Option(
|
|
84
|
+
"--team",
|
|
85
|
+
help=(
|
|
86
|
+
"Team name sent as `team` metadata, for alert sources that "
|
|
87
|
+
"route alerts by a team attribute."
|
|
88
|
+
),
|
|
89
|
+
),
|
|
90
|
+
]
|
|
91
|
+
api_url: Annotated[
|
|
92
|
+
str,
|
|
93
|
+
typer.Option(
|
|
94
|
+
"--api-url",
|
|
95
|
+
help="incident.io API base URL.",
|
|
96
|
+
),
|
|
97
|
+
] = "https://api.incident.io"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class IncidentIoAlertsAggregator(
|
|
101
|
+
Aggregator[UpdateItem, UpdateOutput, IncidentIoAlertsOptions]
|
|
102
|
+
):
|
|
103
|
+
name = "incident-io-alerts"
|
|
104
|
+
description = (
|
|
105
|
+
"Send a per-repository incident.io alert event for failed update "
|
|
106
|
+
"tasks and scan failures; repositories without failures send a "
|
|
107
|
+
"resolved event."
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
@override
|
|
111
|
+
def aggregate(
|
|
112
|
+
self,
|
|
113
|
+
results: Sequence[UpdateResult[UpdateOutput, UpdateItem]],
|
|
114
|
+
logger: Logger,
|
|
115
|
+
scan_failures: Sequence[ScanFailure],
|
|
116
|
+
updater_name: str,
|
|
117
|
+
) -> None:
|
|
118
|
+
events = _build_alert_events(
|
|
119
|
+
results,
|
|
120
|
+
scan_failures,
|
|
121
|
+
updater_name=updater_name,
|
|
122
|
+
deduplication_key_prefix=self.options.deduplication_key_prefix,
|
|
123
|
+
source_url=self.options.source_url,
|
|
124
|
+
team=self.options.team,
|
|
125
|
+
)
|
|
126
|
+
if not events:
|
|
127
|
+
logger.info("No repositories in results; no alert events to send.")
|
|
128
|
+
return
|
|
129
|
+
|
|
130
|
+
failed_repositories: list[str] = []
|
|
131
|
+
with IncidentIoClient(
|
|
132
|
+
api_url=self.options.api_url,
|
|
133
|
+
alert_source_config_id=self.options.alert_source_config_id,
|
|
134
|
+
alert_source_token=self.options.token,
|
|
135
|
+
management_token=self.options.management_token,
|
|
136
|
+
) as client:
|
|
137
|
+
for alert in events:
|
|
138
|
+
if not _send_alert_event(client, alert, logger):
|
|
139
|
+
failed_repositories.append(alert.repository)
|
|
140
|
+
|
|
141
|
+
if failed_repositories:
|
|
142
|
+
raise CliError(
|
|
143
|
+
"Failed to send incident.io alert events for: "
|
|
144
|
+
+ ", ".join(failed_repositories)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _send_alert_event(
|
|
149
|
+
client: IncidentIoClient,
|
|
150
|
+
alert: _AlertEvent,
|
|
151
|
+
logger: Logger,
|
|
152
|
+
) -> bool:
|
|
153
|
+
"""Send one alert event and return whether all client operations succeeded."""
|
|
154
|
+
try:
|
|
155
|
+
response = client.send_alert_event(alert.payload)
|
|
156
|
+
logger.debug(f"incident.io response for {alert.repository}: {response}")
|
|
157
|
+
if alert.note is not None:
|
|
158
|
+
alert_id = client.find_firing_alert_id(alert.deduplication_key)
|
|
159
|
+
if alert_id is None:
|
|
160
|
+
logger.warning(
|
|
161
|
+
f"No firing alert found for {alert.deduplication_key!r}; "
|
|
162
|
+
"skipping note."
|
|
163
|
+
)
|
|
164
|
+
else:
|
|
165
|
+
client.attach_note(alert_id, alert.note)
|
|
166
|
+
except requests.exceptions.HTTPError as error:
|
|
167
|
+
body = (
|
|
168
|
+
error.response.text.strip() if error.response is not None else ""
|
|
169
|
+
) or "[empty body]"
|
|
170
|
+
logger.error(
|
|
171
|
+
f"Failed to send alert event for {alert.repository}: {error}: {body}"
|
|
172
|
+
)
|
|
173
|
+
return False
|
|
174
|
+
except requests.exceptions.RequestException as error:
|
|
175
|
+
# Transport failures would affect every remaining repository the same way,
|
|
176
|
+
# so abort instead of continuing per repository.
|
|
177
|
+
raise CliError(f"Could not reach incident.io: {error}") from error
|
|
178
|
+
logger.info(f"Sent {alert.payload['status']} alert event for {alert.repository}.")
|
|
179
|
+
return True
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _build_alert_events(
|
|
183
|
+
results: Sequence[UpdateResult[UpdateOutput, UpdateItem]],
|
|
184
|
+
scan_failures: Sequence[ScanFailure],
|
|
185
|
+
*,
|
|
186
|
+
updater_name: str,
|
|
187
|
+
deduplication_key_prefix: str,
|
|
188
|
+
source_url: str | None,
|
|
189
|
+
team: str | None,
|
|
190
|
+
) -> list[_AlertEvent]:
|
|
191
|
+
"""Build one alert event and an optional note per repository.
|
|
192
|
+
|
|
193
|
+
Repositories with failed update tasks or scan failures get a firing event; all other
|
|
194
|
+
repositories in the results get a resolved event so a previously fired alert with
|
|
195
|
+
the same deduplication key auto-resolves. The event itself carries no failure
|
|
196
|
+
content: all failure messages and details go into a markdown note. incident.io
|
|
197
|
+
never updates an already-firing alert from a deduplicated event, but the note is
|
|
198
|
+
appended on every run.
|
|
199
|
+
"""
|
|
200
|
+
# The failed activity and diagnostics per repository; repositories
|
|
201
|
+
# without failures map to an empty list. A repository can fail multiple
|
|
202
|
+
# times, e.g. for several update items.
|
|
203
|
+
failures: dict[RepositoryRef, list[tuple[str, Diagnostics]]] = {}
|
|
204
|
+
|
|
205
|
+
for result in results:
|
|
206
|
+
entries = failures.setdefault(result.item.repository_ref, [])
|
|
207
|
+
if result.result == Status.FAILURE:
|
|
208
|
+
entries.append(("updating", result))
|
|
209
|
+
for scan_failure in scan_failures:
|
|
210
|
+
failures.setdefault(scan_failure.repository_ref, []).append(
|
|
211
|
+
("scanning", scan_failure)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
events = []
|
|
215
|
+
for repository_ref in sorted(failures, key=lambda ref: ref.display_name):
|
|
216
|
+
display_name = repository_ref.display_name
|
|
217
|
+
entries = failures[repository_ref]
|
|
218
|
+
# The plain owner/name (no branch suffix) for incident.io
|
|
219
|
+
metadata: dict[str, Any] = {"repository": repository_ref.full_name}
|
|
220
|
+
if team is not None:
|
|
221
|
+
metadata["team"] = team
|
|
222
|
+
deduplication_key = f"{deduplication_key_prefix}/{display_name}"
|
|
223
|
+
event: dict[str, Any] = {
|
|
224
|
+
"title": f"Updater Failed: {updater_name} in {display_name}",
|
|
225
|
+
"deduplication_key": deduplication_key,
|
|
226
|
+
"status": "firing" if entries else "resolved",
|
|
227
|
+
"metadata": metadata,
|
|
228
|
+
}
|
|
229
|
+
if source_url is not None:
|
|
230
|
+
event["source_url"] = source_url
|
|
231
|
+
note = _note(repository_ref, entries) if entries else None
|
|
232
|
+
events.append(_AlertEvent(display_name, deduplication_key, event, note))
|
|
233
|
+
return events
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _note(
|
|
237
|
+
repository_ref: RepositoryRef,
|
|
238
|
+
failures: Sequence[tuple[str, Diagnostics]],
|
|
239
|
+
) -> str:
|
|
240
|
+
"""Render the failure messages and details as markdown."""
|
|
241
|
+
repository_link = (
|
|
242
|
+
f"[{repository_ref.display_name}]"
|
|
243
|
+
f"(https://github.com/{repository_ref.full_name})"
|
|
244
|
+
)
|
|
245
|
+
sections = []
|
|
246
|
+
for activity, diagnostics in failures:
|
|
247
|
+
section = (
|
|
248
|
+
f"Failed during {activity} {repository_link}: "
|
|
249
|
+
f"{diagnostics.message or 'No message'}"
|
|
250
|
+
)
|
|
251
|
+
if diagnostics.details:
|
|
252
|
+
section += f"\n```\n{diagnostics.details.rstrip()}\n```"
|
|
253
|
+
sections.append(section)
|
|
254
|
+
return "\n\n".join(sections)
|