divbase-cli 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.
- divbase_cli/__init__.py +1 -0
- divbase_cli/cli_commands/__init__.py +4 -0
- divbase_cli/cli_commands/auth_cli.py +188 -0
- divbase_cli/cli_commands/dimensions_cli.py +462 -0
- divbase_cli/cli_commands/file_cli.py +1188 -0
- divbase_cli/cli_commands/query_cli.py +413 -0
- divbase_cli/cli_commands/shared_args_options.py +33 -0
- divbase_cli/cli_commands/task_history_cli.py +126 -0
- divbase_cli/cli_commands/user_config_cli.py +161 -0
- divbase_cli/cli_commands/version_cli.py +202 -0
- divbase_cli/cli_config.py +80 -0
- divbase_cli/cli_exceptions.py +209 -0
- divbase_cli/config_resolver.py +87 -0
- divbase_cli/display_task_history.py +185 -0
- divbase_cli/divbase_cli.py +93 -0
- divbase_cli/retries.py +44 -0
- divbase_cli/services/__init__.py +0 -0
- divbase_cli/services/announcements.py +46 -0
- divbase_cli/services/pre_signed_urls.py +500 -0
- divbase_cli/services/project_versions.py +103 -0
- divbase_cli/services/s3_files.py +553 -0
- divbase_cli/user_auth.py +525 -0
- divbase_cli/user_config.py +177 -0
- divbase_cli/utils.py +28 -0
- divbase_cli-0.1.0.dist-info/METADATA +44 -0
- divbase_cli-0.1.0.dist-info/RECORD +28 -0
- divbase_cli-0.1.0.dist-info/WHEEL +4 -0
- divbase_cli-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions that resolve for the CLI commands things like:
|
|
3
|
+
- which project to use
|
|
4
|
+
- which download directory to use
|
|
5
|
+
- which DivBase API URL to use
|
|
6
|
+
Based on provided user input and their config file.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from divbase_cli.cli_config import cli_settings
|
|
12
|
+
from divbase_cli.cli_exceptions import AuthenticationError, ProjectNameNotSpecifiedError
|
|
13
|
+
from divbase_cli.user_auth import get_pat_for_authentication
|
|
14
|
+
from divbase_cli.user_config import ProjectConfig, load_user_config
|
|
15
|
+
|
|
16
|
+
AUTH_ERROR_MSG = (
|
|
17
|
+
"You are not logged in. Please log in with 'divbase-cli auth login [EMAIL]'. \n"
|
|
18
|
+
"Alternatively, you can use a personal access token (PAT) to authenticate yourself. \n"
|
|
19
|
+
f"See our guide here: {cli_settings.DIVBASE_DOCS_URL}/user-guides/account-management/#personal-access-tokens"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def resolve_and_authenticate_project(project_name: str | None) -> ProjectConfig:
|
|
24
|
+
"""
|
|
25
|
+
Helper function that resolves the project to use for a CLI command and ensures
|
|
26
|
+
the user is logged in to the correct DivBase API URL for that project.
|
|
27
|
+
|
|
28
|
+
Returns the ProjectConfig object for the resolved project, will raise errors otherwise.
|
|
29
|
+
"""
|
|
30
|
+
user_config = load_user_config()
|
|
31
|
+
if not project_name:
|
|
32
|
+
project_name = user_config.default_project
|
|
33
|
+
if not project_name:
|
|
34
|
+
raise ProjectNameNotSpecifiedError()
|
|
35
|
+
|
|
36
|
+
project_config = user_config.project_info(project_name)
|
|
37
|
+
|
|
38
|
+
if user_config.logged_in_url:
|
|
39
|
+
if project_config.divbase_url != user_config.logged_in_url:
|
|
40
|
+
raise AuthenticationError(
|
|
41
|
+
f"You are trying to run a command for the project '{project_name}' which has the DivBase URL: {project_config.divbase_url} \n"
|
|
42
|
+
f"You are however logged in to this URL: {user_config.logged_in_url} \n"
|
|
43
|
+
"Please log in again."
|
|
44
|
+
)
|
|
45
|
+
return project_config
|
|
46
|
+
|
|
47
|
+
if get_pat_for_authentication():
|
|
48
|
+
# if a user has a PAT, we will assume the PAT is for the correct URL
|
|
49
|
+
return project_config
|
|
50
|
+
|
|
51
|
+
raise AuthenticationError(AUTH_ERROR_MSG)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resolve_url_for_non_project_specific_commands() -> str:
|
|
55
|
+
"""
|
|
56
|
+
Resolve the DivBase API URL to use for CLI commands that are not project-specific.
|
|
57
|
+
|
|
58
|
+
Returns the url the user is either logged into or in the case of a user using a personal access token (PAT),
|
|
59
|
+
the default API URL, since PATs don't require login to be used.
|
|
60
|
+
Current examples: auth whoami and some task-history commands that are not project-specific.
|
|
61
|
+
|
|
62
|
+
Priority mirrors make_authenticated_request: active session first, PAT as fallback.
|
|
63
|
+
"""
|
|
64
|
+
config = load_user_config()
|
|
65
|
+
if config.logged_in_url:
|
|
66
|
+
return config.logged_in_url
|
|
67
|
+
|
|
68
|
+
if get_pat_for_authentication():
|
|
69
|
+
return cli_settings.DIVBASE_API_URL
|
|
70
|
+
|
|
71
|
+
raise AuthenticationError(AUTH_ERROR_MSG)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def resolve_download_dir(download_dir: str | None) -> Path:
|
|
75
|
+
"""
|
|
76
|
+
Helper function to resolve the download directory to use for a CLI command involving downloading files.
|
|
77
|
+
|
|
78
|
+
Priority given to `download_dir` argument, then if a default is set in the user config.
|
|
79
|
+
Note: "." or None should default to the current working directory.
|
|
80
|
+
"""
|
|
81
|
+
if not download_dir:
|
|
82
|
+
config = load_user_config()
|
|
83
|
+
download_dir = config.default_download_dir
|
|
84
|
+
|
|
85
|
+
if download_dir and download_dir != ".":
|
|
86
|
+
return Path(download_dir).expanduser()
|
|
87
|
+
return Path.cwd()
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from rich.console import Console
|
|
4
|
+
from rich.table import Table
|
|
5
|
+
|
|
6
|
+
from divbase_cli.utils import print_rich_table_as_tsv
|
|
7
|
+
from divbase_lib.api_schemas.task_history import (
|
|
8
|
+
BcftoolsQueryTaskResult,
|
|
9
|
+
DimensionUpdateTaskResult,
|
|
10
|
+
SampleMetadataQueryTaskResult,
|
|
11
|
+
TaskHistoryResult,
|
|
12
|
+
)
|
|
13
|
+
from divbase_lib.utils import format_datetime_for_cli
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TaskHistoryDisplayManager:
|
|
19
|
+
"""
|
|
20
|
+
A class that manages displaying task history results to the user's terminal.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
STATE_COLOURS = {
|
|
24
|
+
"SUCCESS": "green",
|
|
25
|
+
"FAILURE": "red",
|
|
26
|
+
"PENDING": "yellow",
|
|
27
|
+
"QUEUING": "yellow",
|
|
28
|
+
"STARTED": "blue",
|
|
29
|
+
"RETRY": "blue",
|
|
30
|
+
"REVOKED": "magenta",
|
|
31
|
+
}
|
|
32
|
+
# These are the states known by the worker. The state when a task is in the queue is handled by the broker and PENDING is typically used for that purpose.
|
|
33
|
+
# For user display purposes, we want to show QUEUING instead of PENDING for tasks that are not yet started.
|
|
34
|
+
# To avoid having separate CRUD logic for the enqueued state, check task status against the worker state and return QUEUING to user's terminal.
|
|
35
|
+
CELERY_STATES_EXCLUDING_PENDING = {"STARTED", "SUCCESS", "FAILURE", "RETRY", "REVOKED"}
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
task_items: list[TaskHistoryResult],
|
|
40
|
+
user_email: str | None,
|
|
41
|
+
project_name: str | None,
|
|
42
|
+
mode: str,
|
|
43
|
+
display_limit: int = 10,
|
|
44
|
+
format_output_as_tsv: bool = False,
|
|
45
|
+
):
|
|
46
|
+
self.task_items = task_items
|
|
47
|
+
self.user_email = user_email
|
|
48
|
+
self.project_name = project_name
|
|
49
|
+
self.mode = mode
|
|
50
|
+
self.display_limit = display_limit
|
|
51
|
+
self.format_output_as_tsv = format_output_as_tsv
|
|
52
|
+
|
|
53
|
+
def print_task_history(self) -> None:
|
|
54
|
+
"""Display the task history fetched from the results backend in a formatted table."""
|
|
55
|
+
|
|
56
|
+
sorted_tasks = sorted(self.task_items, key=lambda x: x.created_at, reverse=True)
|
|
57
|
+
display_limit = self.display_limit
|
|
58
|
+
limited_tasks = sorted_tasks[:display_limit]
|
|
59
|
+
|
|
60
|
+
table = self._create_task_history_table()
|
|
61
|
+
|
|
62
|
+
for task in limited_tasks:
|
|
63
|
+
raw_status = task.status
|
|
64
|
+
if raw_status and raw_status.upper() in self.CELERY_STATES_EXCLUDING_PENDING:
|
|
65
|
+
state = raw_status.upper()
|
|
66
|
+
else:
|
|
67
|
+
state = "QUEUING"
|
|
68
|
+
|
|
69
|
+
if self.format_output_as_tsv:
|
|
70
|
+
state_with_colour = state
|
|
71
|
+
else:
|
|
72
|
+
colour = self.STATE_COLOURS.get(state, "white")
|
|
73
|
+
state_with_colour = f"[{colour}]{state}[/{colour}]"
|
|
74
|
+
|
|
75
|
+
submitter = task.submitter_email
|
|
76
|
+
result = self._format_result(task, state)
|
|
77
|
+
|
|
78
|
+
table.add_row(
|
|
79
|
+
submitter,
|
|
80
|
+
str(task.id),
|
|
81
|
+
state_with_colour,
|
|
82
|
+
format_datetime_for_cli(task.started_at) if task.started_at else "N/A",
|
|
83
|
+
f"{task.runtime:.2f}" if task.runtime is not None else "N/A",
|
|
84
|
+
result,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
if self.format_output_as_tsv:
|
|
88
|
+
print_rich_table_as_tsv(table=table)
|
|
89
|
+
else:
|
|
90
|
+
console = Console()
|
|
91
|
+
console.print(table)
|
|
92
|
+
|
|
93
|
+
def _create_task_history_table(self) -> Table:
|
|
94
|
+
"""
|
|
95
|
+
Use the Rich library to initiate a table for displaying task history.
|
|
96
|
+
"""
|
|
97
|
+
title_prefix = "DivBase Task History"
|
|
98
|
+
if self.mode == "user":
|
|
99
|
+
title = f"{title_prefix} for User: {self.user_email or 'Unknown'}"
|
|
100
|
+
elif self.mode == "user_project":
|
|
101
|
+
title = (
|
|
102
|
+
f"{title_prefix} for User: {self.user_email or 'Unknown'} and Project: {self.project_name or 'Unknown'}"
|
|
103
|
+
)
|
|
104
|
+
elif self.mode == "id":
|
|
105
|
+
title = f"{title_prefix} for Task ID: {self.task_items[0].id if self.task_items else 'Unknown'}"
|
|
106
|
+
elif self.mode == "project":
|
|
107
|
+
title = f"{title_prefix} for Project: {self.project_name or 'Unknown'}"
|
|
108
|
+
else:
|
|
109
|
+
title = title_prefix
|
|
110
|
+
|
|
111
|
+
table = Table(title=title, show_lines=True)
|
|
112
|
+
table.add_column("Submitting user", no_wrap=False)
|
|
113
|
+
table.add_column("Task ID", style="cyan", no_wrap=True)
|
|
114
|
+
table.add_column("State", no_wrap=True)
|
|
115
|
+
table.add_column("Started at", style="yellow", no_wrap=False)
|
|
116
|
+
table.add_column("Runtime (s)", style="blue", no_wrap=False)
|
|
117
|
+
table.add_column("Result", style="white", no_wrap=False)
|
|
118
|
+
return table
|
|
119
|
+
|
|
120
|
+
def _format_result(self, task: TaskHistoryResult, state: str) -> str:
|
|
121
|
+
"""
|
|
122
|
+
Format the result message based on the task state and type.
|
|
123
|
+
"""
|
|
124
|
+
colour = self.STATE_COLOURS.get(state, "white")
|
|
125
|
+
|
|
126
|
+
if state == "QUEUING":
|
|
127
|
+
return self._colourize_if_enabled("Waiting for job to start", colour)
|
|
128
|
+
|
|
129
|
+
if state == "FAILURE":
|
|
130
|
+
if isinstance(task.result, dict):
|
|
131
|
+
error_msg = task.result.get("error")
|
|
132
|
+
if not error_msg:
|
|
133
|
+
exc_message = task.result.get("exc_message")
|
|
134
|
+
if isinstance(exc_message, list) and exc_message:
|
|
135
|
+
error_msg = " ".join(str(msg) for msg in exc_message)
|
|
136
|
+
elif exc_message:
|
|
137
|
+
error_msg = str(exc_message)
|
|
138
|
+
if not error_msg:
|
|
139
|
+
exc_type = task.result.get("exc_type")
|
|
140
|
+
error_msg = exc_type if exc_type else "Unknown error"
|
|
141
|
+
else:
|
|
142
|
+
error_msg = str(task.result) or "Unknown error"
|
|
143
|
+
|
|
144
|
+
return self._colourize_if_enabled(str(error_msg), colour)
|
|
145
|
+
|
|
146
|
+
if isinstance(task.result, BcftoolsQueryTaskResult):
|
|
147
|
+
result_message = f"Output file ready for download: {task.result.output_file}"
|
|
148
|
+
return self._colourize_if_enabled(result_message, colour)
|
|
149
|
+
|
|
150
|
+
elif isinstance(task.result, SampleMetadataQueryTaskResult):
|
|
151
|
+
result_message = (
|
|
152
|
+
f"Unique sample IDs:\n {task.result.unique_sample_ids}\n"
|
|
153
|
+
f"VCF files containing the sample IDs:\n {task.result.unique_filenames}\n"
|
|
154
|
+
f"Sample metadata query:\n {task.result.query_message}"
|
|
155
|
+
)
|
|
156
|
+
return self._colourize_if_enabled(result_message, colour)
|
|
157
|
+
|
|
158
|
+
elif isinstance(task.result, DimensionUpdateTaskResult):
|
|
159
|
+
result_message = (
|
|
160
|
+
f"VCF file dimensions cache added or updated:\n {task.result.VCF_files_added}\n"
|
|
161
|
+
f"VCF files skipped by this job (previous DivBase-generated result VCFs):\n {task.result.VCF_files_skipped}\n"
|
|
162
|
+
f"VCF files that have been deleted from the project and now are dropped from the index:\n {task.result.VCF_files_deleted}"
|
|
163
|
+
)
|
|
164
|
+
return self._colourize_if_enabled(result_message, colour)
|
|
165
|
+
|
|
166
|
+
if isinstance(task.result, dict) and ("exc_type" in task.result or "error" in task.result):
|
|
167
|
+
# Handle any remaining error dicts that weren't caught by FAILURE state check
|
|
168
|
+
error_msg = task.result.get("error")
|
|
169
|
+
if not error_msg:
|
|
170
|
+
exc_message = task.result.get("exc_message")
|
|
171
|
+
if isinstance(exc_message, list) and exc_message:
|
|
172
|
+
error_msg = " ".join(str(msg) for msg in exc_message)
|
|
173
|
+
elif exc_message:
|
|
174
|
+
error_msg = str(exc_message)
|
|
175
|
+
else:
|
|
176
|
+
error_msg = task.result.get("exc_type", "Unknown error")
|
|
177
|
+
return self._colourize_if_enabled(str(error_msg), colour)
|
|
178
|
+
|
|
179
|
+
result_message = str(task.result)
|
|
180
|
+
return self._colourize_if_enabled(result_message, colour)
|
|
181
|
+
|
|
182
|
+
def _colourize_if_enabled(self, text: str, colour: str) -> str:
|
|
183
|
+
if self.format_output_as_tsv:
|
|
184
|
+
return text
|
|
185
|
+
return f"[{colour}]{text}[/{colour}]"
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The entry point for the DivBase CLI tool that lets users interact with DivBase project.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich import print
|
|
11
|
+
|
|
12
|
+
from divbase_cli import __version__
|
|
13
|
+
from divbase_cli.cli_commands.auth_cli import auth_app
|
|
14
|
+
from divbase_cli.cli_commands.dimensions_cli import dimensions_app
|
|
15
|
+
from divbase_cli.cli_commands.file_cli import file_app
|
|
16
|
+
from divbase_cli.cli_commands.query_cli import query_app
|
|
17
|
+
from divbase_cli.cli_commands.task_history_cli import task_history_app
|
|
18
|
+
from divbase_cli.cli_commands.user_config_cli import config_app
|
|
19
|
+
from divbase_cli.cli_commands.version_cli import version_app
|
|
20
|
+
from divbase_cli.cli_config import cli_settings
|
|
21
|
+
from divbase_cli.cli_exceptions import DivBaseCLIError
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
app = typer.Typer(
|
|
27
|
+
help="""
|
|
28
|
+
This tool lets you interact with your DivBase project(s) in order to: \n
|
|
29
|
+
- Query the metadata for the VCF files stored in the project. \n
|
|
30
|
+
- Upload/download files to/from the project. \n
|
|
31
|
+
- Version the state of all files in the entire project at a given timestamp.
|
|
32
|
+
""",
|
|
33
|
+
no_args_is_help=True,
|
|
34
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def version_callback(show_version: bool) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Callback function to display the installed version of the divbase-cli package.
|
|
41
|
+
See https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager
|
|
42
|
+
"""
|
|
43
|
+
if show_version:
|
|
44
|
+
typer.echo(f"divbase-cli version: {__version__}")
|
|
45
|
+
raise typer.Exit(0)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@app.callback()
|
|
49
|
+
def show_installed_version(
|
|
50
|
+
show_version: bool = typer.Option(
|
|
51
|
+
None,
|
|
52
|
+
"--version",
|
|
53
|
+
"-v",
|
|
54
|
+
callback=version_callback,
|
|
55
|
+
is_eager=True,
|
|
56
|
+
help="Show the currently installed version of the divbase-cli package.",
|
|
57
|
+
),
|
|
58
|
+
) -> None:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
app.add_typer(auth_app, name="auth")
|
|
63
|
+
app.add_typer(config_app, name="config")
|
|
64
|
+
app.add_typer(dimensions_app, name="dimensions")
|
|
65
|
+
app.add_typer(file_app, name="files")
|
|
66
|
+
app.add_typer(query_app, name="query")
|
|
67
|
+
app.add_typer(task_history_app, name="task-history")
|
|
68
|
+
app.add_typer(version_app, name="version")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def main():
|
|
72
|
+
# auto-complete mode + logging does not work, as the log message gets included in the auto-complete output.
|
|
73
|
+
# so when running divbase-cli in auto-complete mode we should not log.
|
|
74
|
+
# (when any CLI command is actually run, you are not in_auto_complete_mode)
|
|
75
|
+
in_auto_complete_mode = "_DIVBASE_CLI_COMPLETE" in os.environ
|
|
76
|
+
if cli_settings.LOGGING_ON and not in_auto_complete_mode:
|
|
77
|
+
logging.basicConfig(level=cli_settings.LOG_LEVEL, handlers=[logging.StreamHandler(sys.stderr)])
|
|
78
|
+
logger.info(f"Starting divbase_cli CLI application with logging level: {cli_settings.LOG_LEVEL}")
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
app()
|
|
82
|
+
except DivBaseCLIError as exc:
|
|
83
|
+
if cli_settings.TRACEBACKS_ON:
|
|
84
|
+
raise
|
|
85
|
+
print(f"[red bold]Error:[/red bold] {str(exc)}")
|
|
86
|
+
print(
|
|
87
|
+
f"[dim]Tip: see our guide if you want to see the full traceback for debugging purposes: {cli_settings.DIVBASE_DOCS_URL}/user-guides/troubleshooting/ [/dim]"
|
|
88
|
+
)
|
|
89
|
+
sys.exit(1)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
main()
|
divbase_cli/retries.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Retry logic for the divbase-cli package.
|
|
3
|
+
|
|
4
|
+
Defines functions to determine whether to retry based on the type of exceptions raised.
|
|
5
|
+
Functions are used in stamina (package) decorators.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from divbase_cli.cli_exceptions import DivBaseAPIConnectionError, DivBaseAPIError, PolledTaskNotFinalError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def retry_only_on_retryable_http_errors(exc: Exception) -> bool:
|
|
14
|
+
"""
|
|
15
|
+
Used by stamina's (library for retries) decorators to determine whether to retry the function or not.
|
|
16
|
+
We avoid retrying on HTTPStatusError for 4xx errors as no point (e.g. 404 Not Found or 403 Forbidden etc...).
|
|
17
|
+
"""
|
|
18
|
+
if isinstance(exc, httpx.HTTPStatusError):
|
|
19
|
+
return exc.response.status_code >= 500
|
|
20
|
+
|
|
21
|
+
# Want to retry on other HTTPError (parent of HTTPStatusError),
|
|
22
|
+
# as this includes timeouts, connection errors, etc.
|
|
23
|
+
return isinstance(exc, httpx.HTTPError)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def retry_only_on_retryable_divbase_api_errors(exception: Exception) -> bool:
|
|
27
|
+
"""
|
|
28
|
+
Retry condition function for stamina to only retry on retryable DivBase API errors.
|
|
29
|
+
"""
|
|
30
|
+
if isinstance(exception, DivBaseAPIConnectionError):
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
# Retry only for server errors (5xx) and rate limiting (429)
|
|
34
|
+
return isinstance(exception, DivBaseAPIError) and (exception.status_code == 429 or exception.status_code >= 500)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def retry_only_while_polled_task_not_final(exc: Exception) -> bool:
|
|
38
|
+
"""Retry only while a polled celery task is not in a final state."""
|
|
39
|
+
return isinstance(exc, PolledTaskNotFinalError)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def retry_polling_until_final_or_retryable_api_errors(exc: Exception) -> bool:
|
|
43
|
+
"""Retry only while a polled celery task is not in a final state or on retryable DivBase API errors."""
|
|
44
|
+
return retry_only_while_polled_task_not_final(exc) or retry_only_on_retryable_divbase_api_errors(exc)
|
|
File without changes
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Get announcements from divbase API and display them to the user.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from rich import print
|
|
6
|
+
|
|
7
|
+
from divbase_cli.user_auth import make_unauthenticated_request
|
|
8
|
+
from divbase_lib.api_schemas.announcements import AnnouncementResponse
|
|
9
|
+
|
|
10
|
+
COLOR_MAPPING = {
|
|
11
|
+
"info": "blue",
|
|
12
|
+
"success": "green",
|
|
13
|
+
"warning": "yellow",
|
|
14
|
+
"danger": "red",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_and_display_announcements(divbase_base_url: str) -> None:
|
|
19
|
+
"""
|
|
20
|
+
Get announcements from the API and display them to the user.
|
|
21
|
+
Used when logging in to display any important messages to the user.
|
|
22
|
+
"""
|
|
23
|
+
response = make_unauthenticated_request(
|
|
24
|
+
method="GET",
|
|
25
|
+
divbase_base_url=divbase_base_url,
|
|
26
|
+
api_route="/v1/core/announcements",
|
|
27
|
+
)
|
|
28
|
+
announcements_data = response.json()
|
|
29
|
+
if not announcements_data:
|
|
30
|
+
return
|
|
31
|
+
announcements = [AnnouncementResponse.model_validate(ann) for ann in announcements_data]
|
|
32
|
+
|
|
33
|
+
if len(announcements) == 1:
|
|
34
|
+
print("[bold]An Announcement from DivBase Server:[/bold]")
|
|
35
|
+
color = COLOR_MAPPING.get(announcements[0].level)
|
|
36
|
+
print(f"[bold {color}]{announcements[0].heading}[/bold {color}]")
|
|
37
|
+
if announcements[0].message:
|
|
38
|
+
print(f"{announcements[0].message}\n")
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
print("[bold]Announcements from DivBase Server:[/bold]")
|
|
42
|
+
for idx, ann in enumerate(announcements, start=1):
|
|
43
|
+
color = COLOR_MAPPING.get(ann.level)
|
|
44
|
+
print(f"[bold {color}]{idx}) {ann.heading}[/bold {color}]")
|
|
45
|
+
if ann.message:
|
|
46
|
+
print(f"{ann.message}\n")
|