healthycode 0.2.1__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.
@@ -0,0 +1,513 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) Bitergia
4
+ # Copyright (C) AboutCode
5
+ #
6
+ # This program is free software; you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation; either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime
23
+ import json
24
+ import logging
25
+ import re
26
+ import sys
27
+ import time
28
+ import typing
29
+
30
+ import click
31
+ import requests
32
+
33
+ from importlib.metadata import version
34
+
35
+ from pathlib import Path
36
+ from spdx_tools.spdx.model import SpdxNone, SpdxNoAssertion
37
+ from spdx_tools.spdx.parser.error import SPDXParsingError
38
+ from spdx_tools.spdx.parser.parse_anything import parse_file
39
+
40
+ from grimoirelab_metrics.metrics_model import npmModel
41
+ from grimoirelab_metrics.grimoirelab_client import GrimoireLabClient
42
+ from grimoirelab_metrics.metrics import get_repository_metrics, FILE_TYPE_CODE, FILE_TYPE_BINARY
43
+
44
+ if typing.TYPE_CHECKING:
45
+ from typing import Any
46
+
47
+ GIT_REPO_REGEX = r"((git|http(s)?)|(git@[\w\.]+))://?([\w\.@\:/\-~]+)(\.git)(/)?"
48
+
49
+ DEFAULT_DEV_CATEGORIES_THRESHOLDS = (0.8, 0.95)
50
+ DEFAULT_PONY_THRESHOLD = 0.5
51
+ DEFAULT_ELEPHANT_THRESHOLD = 0.5
52
+
53
+
54
+ @click.command()
55
+ @click.argument("source")
56
+ @click.option(
57
+ "--grimoirelab-url",
58
+ help="GrimoireLab URL server",
59
+ show_default=True,
60
+ )
61
+ @click.option("--grimoirelab-user", help="GrimoireLab API user")
62
+ @click.option("--grimoirelab-password", help="GrimoireLab API password")
63
+ @click.option("--grimoirelab-ecosystem", help="GrimoireLab will classify the data under this ecosystem name")
64
+ @click.option(
65
+ "--grimoirelab-project", help="GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem"
66
+ )
67
+ @click.option(
68
+ "--opensearch-url",
69
+ help="OpenSearch URL server",
70
+ default="http://localhost:9200/",
71
+ )
72
+ @click.option("--opensearch-index", help="OpenSearch index", default="events")
73
+ @click.option("--opensearch-user", type=str, help="OpenSearch user", default=None)
74
+ @click.option("--opensearch-password", type=str, help="OpenSearch password", default=None)
75
+ @click.option("--opensearch-ca-certs", type=str, help="OpenSearch CA certificate path (.pem file)", default=None)
76
+ @click.option("--opensearch-timeout", type=int, help="OpenSearch timeout in seconds", default=30)
77
+ @click.option("--output", help="File where the scores will be written", type=click.File("w"), default=sys.stdout)
78
+ @click.option(
79
+ "--repository-timeout",
80
+ type=int,
81
+ help="Timeout in seconds to wait for a repository to be analyzed",
82
+ default=3600,
83
+ )
84
+ @click.option(
85
+ "--from-date",
86
+ type=click.DateTime(formats=["%Y-%m-%d"]),
87
+ help="Start date, by default last year",
88
+ default=(datetime.datetime.today() - datetime.timedelta(days=365)).strftime("%Y-%m-%d"),
89
+ )
90
+ @click.option(
91
+ "--to-date",
92
+ type=click.DateTime(formats=["%Y-%m-%d"]),
93
+ help="End date, by default today",
94
+ default=datetime.datetime.today().strftime("%Y-%m-%d"),
95
+ )
96
+ @click.option("--verify-certs", is_flag=True, default=False, help="Verify SSL/TLS certificates")
97
+ @click.option("--verbose", is_flag=True, default=False, help="Increase output verbosity")
98
+ @click.option("--code-file-pattern", help="Regular expression to match code file types")
99
+ @click.option("--binary-file-pattern", help="Regular expression to match binary file types")
100
+ @click.option("--pony-threshold", type=click.FloatRange(0, 1), show_default=True, help="Pony factor threshold", default=0.5)
101
+ @click.option(
102
+ "--elephant-threshold", type=click.FloatRange(0, 1), show_default=True, help="Elephant factor threshold", default=0.5
103
+ )
104
+ @click.option(
105
+ "--dev-categories-thresholds",
106
+ type=(click.FloatRange(0, 1), click.FloatRange(0, 1)),
107
+ show_default=True,
108
+ help="Developer categories thresholds",
109
+ default=DEFAULT_DEV_CATEGORIES_THRESHOLDS,
110
+ )
111
+ def grimoirelab_metrics(
112
+ source: str,
113
+ grimoirelab_url: str,
114
+ grimoirelab_user: str,
115
+ grimoirelab_password: str,
116
+ grimoirelab_ecosystem: str,
117
+ grimoirelab_project: str,
118
+ opensearch_url: str,
119
+ opensearch_index: str,
120
+ opensearch_user: str | None = None,
121
+ opensearch_password: str | None = None,
122
+ opensearch_ca_certs: str | None = None,
123
+ opensearch_timeout: int = 30,
124
+ output: typing.TextIO = sys.stdout,
125
+ repository_timeout: int = 3600,
126
+ from_date: datetime.datetime | None = None,
127
+ to_date: datetime.datetime | None = None,
128
+ verify_certs: bool = False,
129
+ verbose: bool = False,
130
+ code_file_pattern: str | None = None,
131
+ binary_file_pattern: str | None = None,
132
+ pony_threshold: float = DEFAULT_PONY_THRESHOLD,
133
+ elephant_threshold: float = DEFAULT_ELEPHANT_THRESHOLD,
134
+ dev_categories_thresholds: tuple[float, float] = DEFAULT_DEV_CATEGORIES_THRESHOLDS,
135
+ ) -> None:
136
+ """Calculate metrics and the npm health score using GrimoireLab.
137
+
138
+ This tools generates a sets of project health metrics and a score using a
139
+ npm health model. As input it either receives a remote Git repository or a
140
+ local SPDX SBOM file with git repositories. The data collection is scheduled
141
+ by GrimoireLab and the health score is calculated on the fly.
142
+
143
+ The health score goes from 0 (healthy) to 1 (unhealthy).
144
+
145
+ SOURCE: remote git repository or SPDX SBoM file with git repositories
146
+ """
147
+ log_level = "DEBUG" if verbose else "INFO"
148
+ logging.basicConfig(level=log_level, format="%(asctime)s - %(levelname)s - %(message)s")
149
+
150
+ try:
151
+ start_date = datetime.datetime.now(datetime.UTC)
152
+ grimoirelab_client = GrimoireLabClient(grimoirelab_url, grimoirelab_user, grimoirelab_password, verify_certs)
153
+ grimoirelab_client.connect()
154
+
155
+ if is_sbom_file(source):
156
+ logging.debug(f"Source is a filepath: {source}")
157
+ packages = get_sbom_packages(source)
158
+ git_urls = list(set(repo for repo in packages.values() if is_valid(repo)))
159
+ elif is_git_repository(source):
160
+ logging.debug(f"Source is a Git repository: {source}")
161
+ packages = {"package0": source}
162
+ git_urls = [source]
163
+ else:
164
+ logging.debug(f"Source is a not either a filepath or Git repository: {source}. Exiting ...")
165
+ print("The source is not a file and does not end with .git ...")
166
+ sys.exit(0)
167
+
168
+ if len(git_urls) > 0:
169
+ logging.info(f"Found {len(git_urls)} git repositories")
170
+ else:
171
+ logging.info("Could not find any git repositories to analyze")
172
+ sys.exit(0)
173
+
174
+ schedule_repositories(git_urls, grimoirelab_client, grimoirelab_ecosystem, grimoirelab_project)
175
+
176
+ metrics = generate_metrics_when_ready(
177
+ grimoirelab_client=grimoirelab_client,
178
+ grimoirelab_ecosystem=grimoirelab_ecosystem,
179
+ grimoirelab_project=grimoirelab_project,
180
+ repositories=git_urls,
181
+ opensearch_url=opensearch_url,
182
+ opensearch_index=opensearch_index,
183
+ opensearch_user=opensearch_user,
184
+ opensearch_password=opensearch_password,
185
+ opensearch_ca_certs=opensearch_ca_certs,
186
+ opensearch_timeout=opensearch_timeout,
187
+ from_date=from_date,
188
+ to_date=to_date,
189
+ verify_certs=verify_certs,
190
+ timeout=repository_timeout,
191
+ code_file_pattern=code_file_pattern,
192
+ binary_file_pattern=binary_file_pattern,
193
+ pony_threshold=pony_threshold,
194
+ elephant_threshold=elephant_threshold,
195
+ dev_categories_thresholds=dev_categories_thresholds,
196
+ )
197
+
198
+ package_metrics = {"packages": {}}
199
+ npm_metrics_model = npmModel()
200
+ for package, repo in packages.items():
201
+ if repo and repo in metrics["repositories"]:
202
+ package_metrics["packages"][package] = metrics["repositories"][repo]
203
+ package_metrics["packages"][package]["repository"] = repo
204
+ logging.debug(f"npm Health Score calculated for {repo}")
205
+ unhealthy_score = npm_metrics_model.calculate_score(metrics["repositories"][repo]["metrics"])
206
+ package_metrics["packages"][package]["score"] = unhealthy_score
207
+ else:
208
+ package_metrics["packages"][package] = {"metrics": None}
209
+
210
+ package_metrics["metadata"] = {
211
+ "version": version("healthycode"),
212
+ "started_at": start_date.isoformat(),
213
+ "finished_at": datetime.datetime.now(datetime.UTC).isoformat(),
214
+ }
215
+ package_metrics["metadata"]["configuration"] = {
216
+ "from_date": from_date.isoformat(),
217
+ "to_date": to_date.isoformat(),
218
+ "code_file_pattern": code_file_pattern if code_file_pattern else FILE_TYPE_CODE,
219
+ "binary_file_pattern": binary_file_pattern if binary_file_pattern else FILE_TYPE_BINARY,
220
+ "pony_threshold": pony_threshold,
221
+ "elephant_threshold": elephant_threshold,
222
+ "dev_categories_thresholds": dev_categories_thresholds,
223
+ }
224
+ output.write(json.dumps(package_metrics, indent=4))
225
+ logging.info(f'Metrics and scores are calculated and written to file "{output.name}"')
226
+ except SPDXParsingError as e:
227
+ logging.error(e.messages[0])
228
+ sys.exit(1)
229
+ except OSError as e:
230
+ logging.error(e)
231
+ sys.exit(1)
232
+
233
+
234
+ def is_git_repository(value: str) -> bool:
235
+ """Return True if value looks like a Git repository URL."""
236
+ return re.match(GIT_REPO_REGEX, value) is not None
237
+
238
+
239
+ def is_sbom_file(value: str) -> bool:
240
+ """Return True if value is an existing file."""
241
+ return Path(value).is_file()
242
+
243
+
244
+ def get_repository(download_location: str) -> str | None:
245
+ if is_valid(download_location):
246
+ git_regex = re.search(GIT_REPO_REGEX, download_location)
247
+ if git_regex:
248
+ uri = f"https://{git_regex.group(5)}.git"
249
+ return uri
250
+ return None
251
+
252
+
253
+ def get_sbom_packages(file: str) -> dict[str, str]:
254
+ """Extract packages and git repositories from SPDX SBoM file.
255
+
256
+ :param file: SPDX SBoM file.
257
+
258
+ :return: Dict with package and repositories.
259
+ """
260
+ logging.info(f"Parsing file {file}")
261
+
262
+ packages = {}
263
+ document = parse_file(file)
264
+ for package in document.packages:
265
+ repository = get_repository(package.download_location)
266
+ if repository:
267
+ packages[package.spdx_id] = repository
268
+ else:
269
+ packages[package.spdx_id] = None
270
+ logging.warning(f"Could not find a git repository for {package.spdx_id} ({package.name})")
271
+
272
+ return packages
273
+
274
+
275
+ def schedule_repositories(
276
+ repositories: list[str], grimoirelab_client: GrimoireLabClient, grimoirelab_ecosystem: str, grimoirelab_project: str
277
+ ) -> None:
278
+ """Schedule tasks to collect data from a list of repositories.
279
+
280
+ :param repositories: List of git repositories.
281
+ :param grimoirelab_client: GrimoireLab API client.
282
+ :param grimoirelab_ecosystem: GrimoireLab will classify the data under this ecosystem name.
283
+ :param grimoirelab_project: GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem.
284
+
285
+ """
286
+ logging.info("Scheduling data collection tasks with GrimoireLab")
287
+ for package_url in repositories:
288
+ logging.debug(f"Scheduling task to fetch commits from {package_url}")
289
+ try:
290
+ schedule_repository(grimoirelab_client, grimoirelab_ecosystem, grimoirelab_project, package_url, "git", "commit")
291
+ except (requests.HTTPError, requests.ConnectionError) as e:
292
+ logging.error(f"Error scheduling task: {e}")
293
+ raise e
294
+
295
+
296
+ def generate_metrics_when_ready(
297
+ grimoirelab_client: GrimoireLabClient,
298
+ grimoirelab_ecosystem: str,
299
+ grimoirelab_project: str,
300
+ repositories: list[str],
301
+ opensearch_url: str,
302
+ opensearch_index: str,
303
+ opensearch_user: str | None = None,
304
+ opensearch_password: str | None = None,
305
+ opensearch_ca_certs: str | None = None,
306
+ opensearch_timeout: int = 30,
307
+ from_date: datetime.datetime | None = None,
308
+ to_date: datetime.datetime | None = None,
309
+ verify_certs: bool = False,
310
+ timeout: int = 3600,
311
+ code_file_pattern: str | None = None,
312
+ binary_file_pattern: str | None = None,
313
+ pony_threshold: float = 0.5,
314
+ elephant_threshold: float = 0.5,
315
+ dev_categories_thresholds: tuple[float, float] = (0.8, 0.95),
316
+ ) -> dict[str:Any]:
317
+ """Generate metrics once the repositories have finished the collection.
318
+
319
+ :param grimoirelab_client: GrimoireLab API client.
320
+ :param grimoirelab_ecosystem: GrimoireLab will classify the data under this ecosystem name
321
+ :param grimoirelab_project: GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem
322
+ :param repositories: List of repositories.
323
+ :param opensearch_url: OpenSearch URL.
324
+ :param opensearch_index: OpenSearch index.
325
+ :param opensearch_user: OpenSearch user.
326
+ :param opensearch_password: OpenSearch password.
327
+ :param opensearch_ca_certs: OpenSearch CA certificate.
328
+ :param opensearch_timeout: OpenSearch timeout.
329
+ :param from_date: Start date for metrics.
330
+ :param to_date: End date for metrics.
331
+ :param verify_certs: Verify SSL/TLS certificates.
332
+ :param timeout: Seconds to wait before failing getting metrics
333
+ :param code_file_pattern: Regular expression to match code file types.
334
+ :param binary_file_pattern: Regular expression to match binary file types.
335
+ :param pony_threshold: Pony Factor threshold.
336
+ :param elephant_threshold: Elephant Factor threshold.
337
+ :param dev_categories_thresholds: Developer Categories thresholds.
338
+ """
339
+
340
+ limit_time = time.time() + timeout
341
+
342
+ after_date = datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=30)
343
+ pending_repositories = set(repositories)
344
+ metrics = {"repositories": {}}
345
+
346
+ while pending_repositories:
347
+ processed = set()
348
+ for repository in pending_repositories:
349
+ if repository_ready(grimoirelab_client, grimoirelab_ecosystem, grimoirelab_project, repository, after_date):
350
+ metrics["repositories"][repository] = get_repository_metrics(
351
+ repository=repository,
352
+ opensearch_url=opensearch_url,
353
+ opensearch_index=opensearch_index,
354
+ opensearch_user=opensearch_user,
355
+ opensearch_password=opensearch_password,
356
+ opensearch_ca_certs=opensearch_ca_certs,
357
+ opensearch_timeout=opensearch_timeout,
358
+ from_date=from_date,
359
+ to_date=to_date,
360
+ verify_certs=verify_certs,
361
+ code_file_pattern=code_file_pattern,
362
+ binary_file_pattern=binary_file_pattern,
363
+ pony_threshold=pony_threshold,
364
+ elephant_threshold=elephant_threshold,
365
+ dev_categories_thresholds=dev_categories_thresholds,
366
+ )
367
+ processed.add(repository)
368
+
369
+ pending_repositories -= processed
370
+
371
+ if pending_repositories and time.time() < limit_time:
372
+ logging.info(f"Waiting for {len(pending_repositories)} repositories to be ready")
373
+ logging.debug(f"Repositories not ready: {pending_repositories}")
374
+ time.sleep(25)
375
+ else:
376
+ logging.info(f"Data collection finished for {len(processed)}/{len(repositories)} repositories")
377
+ break
378
+
379
+ for repository in pending_repositories:
380
+ logging.warning(f"Timeout waiting for repository {repository} to be ready")
381
+
382
+ return metrics
383
+
384
+
385
+ def repository_ready(
386
+ grimoirelab_client: GrimoireLabClient,
387
+ grimoirelab_ecosystem: str,
388
+ grimoirelab_project: str,
389
+ repository: str,
390
+ after_date: datetime.datetime,
391
+ ) -> bool:
392
+ """
393
+ Check if the task related to the repository has finished.
394
+
395
+ :param grimoirelab_client: GrimoireLab API client.
396
+ :param grimoirelab_ecosystem: GrimoireLab will classify the data under this ecosystem name
397
+ :param grimoirelab_project: GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem
398
+ :param repository: Repository URI
399
+ :param after_date: Date to check if the task has finished
400
+ """
401
+ endpoint = f"api/v1/ecosystems/{grimoirelab_ecosystem}/projects/{grimoirelab_project}/repos/"
402
+ try:
403
+ r = grimoirelab_client.get(endpoint, params={"uri": repository})
404
+ except requests.HTTPError as e:
405
+ logging.warning(f"Error checking repository status: {e}")
406
+ return False
407
+
408
+ repo_data = r.json()
409
+
410
+ if not repo_data.get("results"):
411
+ logging.warning(f"Repository '{repository}' not found in project")
412
+ return False
413
+
414
+ categories = repo_data["results"][0].get("categories", [])
415
+ if not categories:
416
+ return False
417
+ task = categories[0].get("task")
418
+ if task["status"] == "failed":
419
+ logging.warning(f"Data for '{repository}' might be incomplete, its last execution failed")
420
+ return True
421
+ elif task["last_run"]:
422
+ last_run_dt = datetime.datetime.fromisoformat(task["last_run"])
423
+ return last_run_dt > after_date
424
+
425
+ return False
426
+
427
+
428
+ def is_valid(repository: str) -> bool:
429
+ """Check that the value is not empty nor invalid."""
430
+
431
+ return repository and not isinstance(repository, SpdxNone) and not isinstance(repository, SpdxNoAssertion)
432
+
433
+
434
+ def schedule_repository(
435
+ grimoirelab_client: GrimoireLabClient,
436
+ grimoirelab_ecosystem: str,
437
+ grimoirelab_project: str,
438
+ uri: str,
439
+ datasource: str,
440
+ category: str,
441
+ ) -> Any:
442
+ """Schedule a task to fetch a Git repository.
443
+
444
+ :param grimoirelab_client: GrimoireLab API client.
445
+ :param grimoirelab_ecosystem: GrimoireLab will classify the data under this ecosystem name.
446
+ :param grimoirelab_project: GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem.
447
+ :param uri: Repository URI.
448
+ :param datasource: Data source type.
449
+ :param category: Data source category.
450
+
451
+ :return: Scheduled task.
452
+ """
453
+
454
+ data = {
455
+ "uri": uri,
456
+ "datasource_type": datasource,
457
+ "category": category,
458
+ "scheduler": {"job_interval": 86400, "job_max_retries": 3, "force_run": False},
459
+ }
460
+
461
+ if is_added(grimoirelab_client, grimoirelab_ecosystem, grimoirelab_project, uri):
462
+ return True
463
+
464
+ endpoint = f"api/v1/ecosystems/{grimoirelab_ecosystem}/projects/{grimoirelab_project}/repos/"
465
+ try:
466
+ res = grimoirelab_client.post(endpoint, json=data)
467
+ res.raise_for_status()
468
+ except requests.HTTPError as e:
469
+ if e.response is not None and e.response.status_code == 422:
470
+ logging.debug(f"payload:{data}")
471
+ logging.debug("DEBUG - Validation Error Details:", e.response.text)
472
+ logging.info(f"Repository {data.get('uri')} is already registered. Skipping.")
473
+ res = e.response
474
+ else:
475
+ # If it's a different HTTP error (500, 404, 403), re-raise it
476
+ raise e
477
+
478
+
479
+ def is_added(grimoirelab_client: GrimoireLabClient, grimoirelab_ecosystem: str, grimoirelab_project: str, uri: str) -> bool:
480
+ """Check if the repository is already scheduled
481
+
482
+ :param grimoirelab_client: GrimoireLab API client.
483
+ :param grimoirelab_ecosystem: GrimoireLab will classify the data under this ecosystem name.
484
+ :param grimoirelab_project: GrimoireLab will classify the data under this project name. Projects are grouped by ecosystem.
485
+ :param uri: Repository URI.
486
+
487
+ :return: Boolean.
488
+ """
489
+
490
+ endpoint = f"api/v1/ecosystems/{grimoirelab_ecosystem}/projects/{grimoirelab_project}/repos/"
491
+ params = {"uri": uri}
492
+
493
+ try:
494
+ res = grimoirelab_client.get(endpoint, params=params)
495
+ res.raise_for_status()
496
+ except requests.HTTPError as e:
497
+ raise e
498
+
499
+ data = res.json()
500
+ count_value = data["count"]
501
+
502
+ if count_value > 0:
503
+ uri_value = data["results"][0]["uri"]
504
+ last_run = data["results"][0]["categories"][-1]["task"]["last_run"]
505
+ logging.debug(f"Repository {uri_value} already added. Last run on {last_run}")
506
+ return True
507
+
508
+ else:
509
+ return False
510
+
511
+
512
+ if __name__ == "__main__":
513
+ grimoirelab_metrics()
@@ -0,0 +1,141 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) Bitergia
4
+ #
5
+ # This program is free software; you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation; either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # This program is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU General Public License
16
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+ #
18
+
19
+ import logging
20
+ import time
21
+
22
+ import requests
23
+
24
+
25
+ MAX_RETRIES = 5
26
+
27
+
28
+ class GrimoireLabClient:
29
+ """
30
+ Client to interact with GrimoireLab API.
31
+
32
+ :param url: GrimoireLab API URL.
33
+ :param user: Username to use when authentication is required.
34
+ :param password: Password to use when authentication is required.
35
+ :param verify_certs: Verify the server's SSL certificate.
36
+ """
37
+
38
+ def __init__(self, url: str, user: str = None, password: str = None, verify_certs: bool = True):
39
+ self.url = url
40
+ self.user = user
41
+ self.password = password
42
+ self.session = None
43
+ self._token = None
44
+ self._refresh_token = None
45
+ self._verify_certs = verify_certs
46
+
47
+ def connect(self):
48
+ """Establish a connection to the server, and create a token"""
49
+
50
+ self.session = requests.Session()
51
+ if not (self.user and self.password):
52
+ return
53
+
54
+ credentials = {"username": self.user, "password": self.password}
55
+ res = self.post("token/", json=credentials)
56
+ res.raise_for_status()
57
+ data = res.json()
58
+
59
+ self._token = data.get("access")
60
+ self._refresh_token = data.get("refresh")
61
+
62
+ self.session.headers.update({"Authorization": f"Bearer {self._token}"})
63
+
64
+ def _reconnect(self):
65
+ """Reconnect to the server using a new Session and the current token"""
66
+
67
+ logging.debug("Server closed the connection. Reconnecting to the server.")
68
+
69
+ self.session = requests.Session()
70
+ if self._token:
71
+ self.session.headers.update({"Authorization": f"Bearer {self._token}"})
72
+
73
+ def get(self, uri: str, *args, **kwargs) -> requests.Response:
74
+ """
75
+ Make a GET request to the GrimoireLab API.
76
+ Check if the token is still valid, if not, refresh it.
77
+
78
+ :param uri: URI to request.
79
+ """
80
+ return self._make_request("get", uri, *args, **kwargs)
81
+
82
+ def post(self, uri: str, *args, **kwargs) -> requests.Response:
83
+ """
84
+ Make a POST request to the GrimoireLab API.
85
+ Check if the token is still valid, if not, refresh it.
86
+
87
+ :param uri: URI to request.
88
+ """
89
+ return self._make_request("post", uri, *args, **kwargs)
90
+
91
+ def _make_request(self, method: str, uri: str, *args, **kwargs) -> requests.Response:
92
+ """
93
+ Make a request to the GrimoireLab API with retry and exponential backoff.
94
+ If the session is invalid or the token is expired, it attempts to reconnect and retry.
95
+
96
+ :param method: HTTP method to use (get or post).
97
+ :param uri: URI to request.
98
+ """
99
+ if not self.session:
100
+ raise ValueError("Session not connected. Call connect() first.")
101
+
102
+ url = f"{self.url}/{uri}"
103
+ last_exception = None
104
+
105
+ for attempt in range(MAX_RETRIES):
106
+ try:
107
+ response = self.session.request(method, url, *args, verify=self._verify_certs, **kwargs)
108
+ response.raise_for_status()
109
+ return response
110
+ except requests.HTTPError as e:
111
+ if e.response.status_code == 403 and self._refresh_token:
112
+ self._refresh_auth_token()
113
+ elif e.response.status_code == 405:
114
+ # This case is when the repository already exists
115
+ return e.response
116
+ else:
117
+ last_exception = e
118
+ except (requests.ConnectionError, requests.Timeout) as e:
119
+ self._reconnect()
120
+ last_exception = e
121
+
122
+ delay = 2**attempt
123
+ time.sleep(delay)
124
+
125
+ # If all retries fail, raise the last encountered exception
126
+ if last_exception:
127
+ raise last_exception
128
+
129
+ def _refresh_auth_token(self):
130
+ """Refresh the access token using the refresh token"""
131
+
132
+ logging.debug("Refreshing token...")
133
+
134
+ credentials = {"refresh": self._refresh_token}
135
+ response = self.post("token/refresh/", json=credentials)
136
+ response.raise_for_status()
137
+ data = response.json()
138
+
139
+ self._token = data.get("access")
140
+
141
+ self.session.headers.update({"Authorization": f"Bearer {self._token}"})