Skip to content

Commit 670fe92

Browse files
authored
chore: Install Ariadne-codegen to generate a typed open hexa client (HEXA-1254) (#264)
1 parent 575f604 commit 670fe92

18 files changed

Lines changed: 2815 additions & 19 deletions

.github/workflows/ci.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ jobs:
1717
with:
1818
python-version: 3.13
1919

20+
- name: Install Ariadne-codegen
21+
run: pip install ariadne-codegen
22+
2023
- uses: pre-commit/action@v3.0.1
2124
test:
2225
name: Run test suite

.pre-commit-config.yaml

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,15 @@ repos:
44
hooks:
55
- id: ruff
66
args: [ --fix, --exit-non-zero-on-fix ]
7-
- id: ruff-format
7+
- id: ruff-format
8+
9+
- repo: local
10+
hooks:
11+
- id: ariadne-codegen
12+
name: ariadne-codegen
13+
entry: bash -c
14+
echo "Running ariadne-codegen" && \
15+
ariadne-codegen
16+
language: system
17+
types: [graphql]
18+
pass_filenames: false

openhexa/cli/api.py

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from graphql.utilities import find_breaking_changes
2222
from jinja2 import Template
2323

24+
from openhexa.cli.graphql.graphql_client import Client
2425
from openhexa.cli.settings import settings
2526
from openhexa.sdk.pipelines import get_local_workspace_config
2627
from openhexa.sdk.pipelines.runtime import get_pipeline
@@ -107,7 +108,16 @@ def get_library_versions() -> tuple[str, str]:
107108
return installed_version, installed_version
108109

109110

110-
def detect_graphql_breaking_changes(token):
111+
def _detect_graphql_breaking_changes_if_needed(token):
112+
"""Detect breaking changes if not done recently between the schema referenced in the SDK and the server using graphql-core."""
113+
ONE_HOUR = 60 * 60
114+
now_timestamp = int(datetime.now().timestamp())
115+
if not settings.last_breaking_change_check or now_timestamp - settings.last_breaking_change_check > ONE_HOUR:
116+
_detect_graphql_breaking_changes(token)
117+
settings.last_breaking_change_check = now_timestamp
118+
119+
120+
def _detect_graphql_breaking_changes(token):
111121
"""Detect breaking changes between the schema referenced in the SDK and the server using graphql-core."""
112122
stored_schema_obj = build_schema((Path(__file__).parent / "graphql" / "schema.generated.graphql").open().read())
113123
server_schema_obj = build_client_schema(
@@ -133,11 +143,7 @@ def detect_graphql_breaking_changes(token):
133143

134144
def graphql(query: str, variables=None, token=None):
135145
"""Check that there is no breaking change and perform a GraphQL request."""
136-
ONE_HOUR = 60 * 60
137-
now_timestamp = int(datetime.now().timestamp())
138-
if not settings.last_breaking_change_check or now_timestamp - settings.last_breaking_change_check > ONE_HOUR:
139-
detect_graphql_breaking_changes(token)
140-
settings.last_breaking_change_check = now_timestamp
146+
_detect_graphql_breaking_changes_if_needed(token)
141147
return _query_graphql(query, variables, token)
142148

143149

@@ -739,3 +745,47 @@ def is_dhis2_connection_up(workspace_slug: str, connection_slug: str) -> bool:
739745
},
740746
)
741747
return response["data"]["connectionBySlug"]["status"] == "UP"
748+
749+
750+
class OpenHexaClient(Client):
751+
"""OpenHexaClient is a class that provides methods to interact with the OpenHexa GraphQL API."""
752+
753+
def __init__(self, token=None):
754+
"""Initialize the OpenHexaClient with the OpenHexa API URL and headers."""
755+
self._url = settings.api_url + "/graphql/"
756+
self._token = token or settings.access_token
757+
758+
if not self._token:
759+
raise InvalidTokenError("No token found for workspace")
760+
761+
super().__init__(
762+
url=self._url,
763+
headers={
764+
"User-Agent": f"openhexa-cli/{version('openhexa.sdk')}",
765+
"Authorization": f"Bearer {self._token}",
766+
},
767+
)
768+
logging.getLogger("httpx").setLevel(
769+
logging.WARNING
770+
) # HTTPX logs queries by default, we disable them here with WARNING level
771+
772+
def execute(self, query, **kwargs):
773+
"""Decorate parent execute method to log the GraphQL query and response."""
774+
_detect_graphql_breaking_changes(token=self._token)
775+
776+
if settings.debug:
777+
click.echo("")
778+
click.echo("Graphql Query:")
779+
click.echo(f"URL: {self.url}")
780+
click.echo(f"Query: {query}")
781+
variables = kwargs.get("variables", {})
782+
click.echo(f"Variables: {variables}")
783+
784+
response = super().execute(query=query, **kwargs)
785+
786+
if settings.debug:
787+
click.echo("")
788+
click.echo("Graphql Response:")
789+
click.echo(f"Response: {response}")
790+
791+
return response

openhexa/cli/cli.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
DockerError,
1515
InvalidDefinitionError,
1616
NoActiveWorkspaceError,
17+
OpenHexaClient,
1718
OutputDirectoryError,
1819
PipelineDirectoryError,
1920
create_pipeline,
@@ -24,7 +25,6 @@
2425
ensure_is_pipeline_dir,
2526
get_library_versions,
2627
get_pipeline_from_code,
27-
get_pipelines,
2828
get_pipelines_pages,
2929
get_workspace,
3030
run_pipeline,
@@ -596,21 +596,19 @@ def pipelines_list():
596596
if settings.current_workspace is None:
597597
_terminate("No workspace activated", err=True)
598598

599-
workspace_pipelines = get_pipelines()
599+
workspace_pipelines = (
600+
OpenHexaClient().get_workspace_pipelines(workspace_slug=settings.current_workspace).pipelines.items
601+
)
600602
if len(workspace_pipelines) == 0:
601603
click.echo(f"No pipelines in workspace {settings.current_workspace}")
602604
return
603605
click.echo("Pipelines:")
604606
for pipeline in workspace_pipelines:
605-
if pipeline["type"] == "zipFile":
606-
current_version = pipeline["currentVersion"].get("number") if pipeline["currentVersion"] else None
607-
if current_version is not None:
608-
current_version = f"v{current_version}"
609-
else:
610-
current_version = "N/A"
607+
if pipeline.type == "zipFile":
608+
current_version = f"v{pipeline.current_version.version_number}" if pipeline.current_version else "N/A"
611609
else:
612610
current_version = "Jupyter notebook"
613-
click.echo(f"* {pipeline['code']} - {pipeline['name']} ({current_version})")
611+
click.echo(f"* {pipeline.code} - {pipeline.name} ({current_version})")
614612

615613

616614
def _terminate(message: str, exception: Exception = None, err: bool = False):

0 commit comments

Comments
 (0)