Skip to content

Commit

Permalink
API versioning strategy
Browse files Browse the repository at this point in the history
The intention of this PR is to build a concrete strategy to follow when versioning the project API.
issue: https://issues.redhat.com/browse/AAP-37993
  • Loading branch information
ldjebran committed Jan 20, 2025
1 parent 69b02b5 commit 1cb2795
Show file tree
Hide file tree
Showing 51 changed files with 817 additions and 90 deletions.
Empty file.
38 changes: 38 additions & 0 deletions ansible_ai_connect/ai/api/base/saas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf import settings

from ansible_ai_connect.ai.api import exceptions


class APIViewSaasMixin:

def initial(self, request, *args, **kwargs):
self.check_saas_settings(request)
return super().initial(request, *args, **kwargs)

def check_saas_settings(self, request):
"""call the correct error function when DEPLOYMENT_MODE is not saas
and not in DEBUG mode"""
if not settings.DEBUG and settings.DEPLOYMENT_MODE != "saas":
self.not_implemented_error(
request, message="This functionality is not available in the current environment"
)

def not_implemented_error(self, request, message=None, code=None):
"""
raise not implement exception when called
"""
raise exceptions.NotImplementedException(detail=message, code=code)
6 changes: 6 additions & 0 deletions ansible_ai_connect/ai/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ class InternalServerError(BaseWisdomAPIException):
default_detail = "An error occurred attempting to complete the request."


class NotImplementedException(BaseWisdomAPIException):
status_code = 501
default_code = "not_implemented"
default_detail = "This functionality is not implemented."


class FeedbackValidationException(WisdomBadRequest):
default_code = "error__feedback_validation"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from django.db.utils import DatabaseError
from django.test import override_settings
from django.urls import resolve, reverse
from django.urls import resolve
from oauth2_provider.contrib.rest_framework import IsAuthenticatedOrTokenHasScope
from rest_framework.permissions import IsAuthenticated

Expand All @@ -27,6 +27,7 @@
IsOrganisationLightspeedSubscriber,
)
from ansible_ai_connect.ai.api.tests.test_views import WisdomServiceAPITestCaseBase
from ansible_ai_connect.ai.api.utils.version import api_version_reverse as reverse
from ansible_ai_connect.organizations.models import Organization


Expand All @@ -49,6 +50,7 @@ def test_permission_classes(self, *args):
required_permissions = [
IsAuthenticated,
IsAuthenticatedOrTokenHasScope,
IsAuthenticatedOrTokenHasScope,
IsOrganisationAdministrator,
IsOrganisationLightspeedSubscriber,
]
Expand Down Expand Up @@ -116,7 +118,6 @@ def test_set_settings_with_valid_value(self, LDClient, *args):
LDClient.return_value.variation.return_value = True
self.user.organization = Organization.objects.get_or_create(id=123)[0]
self.client.force_authenticate(user=self.user)

# Settings should initially be False
r = self.client.get(reverse("telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.OK)
Expand Down
2 changes: 1 addition & 1 deletion ansible_ai_connect/ai/api/tests/test_api_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import grpc
from django.apps import apps
from django.test import override_settings
from django.urls import reverse
from requests.exceptions import ReadTimeout

from ansible_ai_connect.ai.api.exceptions import ModelTimeoutException
Expand All @@ -34,6 +33,7 @@
from ansible_ai_connect.ai.api.model_pipelines.wca.pipelines_saas import (
WCASaaSCompletionsPipeline,
)
from ansible_ai_connect.ai.api.utils.version import api_version_reverse as reverse

from ..model_pipelines.tests import mock_pipeline_config
from .test_views import WisdomServiceAPITestCaseBase
Expand Down
2 changes: 1 addition & 1 deletion ansible_ai_connect/ai/api/tests/test_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from unittest.mock import Mock, patch

from django.test import override_settings
from django.urls import reverse

from ansible_ai_connect.ai.api.permissions import (
BlockUserWithoutSeat,
Expand All @@ -28,6 +27,7 @@
IsWCASaaSModelPipeline,
)
from ansible_ai_connect.ai.api.tests.test_views import WisdomServiceAPITestCaseBase
from ansible_ai_connect.ai.api.utils.version import api_version_reverse as reverse
from ansible_ai_connect.test_utils import WisdomAppsBackendMocking
from ansible_ai_connect.users.models import Plan
from ansible_ai_connect.users.tests.test_users import create_user
Expand Down
2 changes: 1 addition & 1 deletion ansible_ai_connect/ai/api/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
from django.apps import apps
from django.contrib.auth import get_user_model
from django.test import modify_settings, override_settings
from django.urls import reverse
from langchain_core.runnables import Runnable, RunnableConfig
from langchain_core.runnables.utils import Input, Output
from requests.exceptions import ReadTimeout
Expand Down Expand Up @@ -123,6 +122,7 @@
CompletionsPromptType,
)
from ansible_ai_connect.ai.api.serializers import CompletionRequestSerializer
from ansible_ai_connect.ai.api.utils.version import api_version_reverse as reverse
from ansible_ai_connect.healthcheck.backends import HealthCheckSummary
from ansible_ai_connect.main.tests.test_views import create_user_with_provider
from ansible_ai_connect.organizations.models import Organization
Expand Down
24 changes: 5 additions & 19 deletions ansible_ai_connect/ai/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from django.urls import path
from django.urls import include, path

from .views import (
Chat,
Completions,
ContentMatches,
Explanation,
Feedback,
GenerationPlaybook,
GenerationRole,
)
from .versions.v0 import urls as v0_urls
from .versions.v1 import urls as v1_urls

urlpatterns = [
path("completions/", Completions.as_view(), name="completions"),
path("contentmatches/", ContentMatches.as_view(), name="contentmatches"),
path("explanations/", Explanation.as_view(), name="explanations"),
# Legacy
path("generations/", GenerationPlaybook.as_view(), name="generations"),
path("generations/playbook", GenerationPlaybook.as_view(), name="generations/playbook"),
path("generations/role", GenerationRole.as_view(), name="generations/role"),
path("feedback/", Feedback.as_view(), name="feedback"),
path("chat/", Chat.as_view(), name="chat"),
path("v0/", include((v0_urls, "ai"), namespace="v0")),
path("v1/", include((v1_urls, "ai"), namespace="v1")),
]
41 changes: 41 additions & 0 deletions ansible_ai_connect/ai/api/utils/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf import settings
from django.urls import reverse


def get_api_version_view_name(view_name: str, api_version: str | None = None) -> str:
"""
Get the view name with version, if no version supplied, use REST FRAMEWORK
default configured version
:param view_name: the registered view
:param api_version: the version requested the view name is registered
:return: view name of the version
"""
if not api_version:
api_version = getattr(settings, "REST_FRAMEWORK", {}).get("DEFAULT_VERSION")
if api_version:
view_name = f"{api_version}:{view_name}"
return view_name


def api_version_reverse(view_name: str, api_version: str | None = None, **kwargs) -> str:
"""
Return the django reverse of a versioned view name
:param view_name: the registered view
:param api_version: the version requested the view name is registered
:param kwargs: other django reverse kwargs
"""
return reverse(get_api_version_view_name(view_name, api_version=api_version), **kwargs)
31 changes: 31 additions & 0 deletions ansible_ai_connect/ai/api/versions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

## Versioning principles and restrictions:

The application API is organized by versions directory structure, that rely on some basic principles and restrictions:

- The views and serializers outside the versions directories is considered as base code,
in the future the related modules should be moved to a base directory.

- urls modules use views that are imported only from the same version directory hierarchy.
- urls modules use urls to include that are imported only from the same version directory hierarchy,
an exception is made for urls to include from external application.

- views modules can use serializers that are imported only from the same version directory hierarchy.

views modules of a version x can:
- reuse the base views, directly or modified (using inheritance).
- reuse the views only from the previous x-1 version, directly or modified (using inheritance).

serializers modules of a version x can:
- reuse the base serializers, directly or modified (using inheritance).
- reuse the serializers only from the previous x-1 version, directly or modified (using inheritance).

## Generate a concrete API schema version

```commandline
VERSION="v1" podman exec -it --user=0 docker-compose-django-1 wisdom-manage spectacular --api-version $VERSION --file /var/www/ansible-ai-connect-service/ansible_ai_connect/schema-$VERSION.yaml
```
This will generate a schema file with requested version at ansible_ai_connect directory

the default format is openapi (yaml file format)
but also openapi-json can be produced with "--format openapi-json" option
Empty file.
Empty file.
Empty file.
28 changes: 28 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/ai/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.urls import path

from . import views

urlpatterns = [
path("completions/", views.Completions.as_view(), name="completions"),
path("contentmatches/", views.ContentMatches.as_view(), name="contentmatches"),
path("explanations/", views.Explanation.as_view(), name="explanations"),
path("generations/", views.GenerationPlaybook.as_view(), name="generations"),
path("generations/playbook", views.GenerationPlaybook.as_view(), name="generations/playbook"),
path("generations/role", views.GenerationRole.as_view(), name="generations/role"),
path("feedback/", views.Feedback.as_view(), name="feedback"),
path("chat/", views.Chat.as_view(), name="chat"),
]
33 changes: 33 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/ai/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ansible_ai_connect.ai.api.views import (
Chat,
Completions,
ContentMatches,
Explanation,
Feedback,
GenerationPlaybook,
GenerationRole,
)

__all__ = [
Completions,
ContentMatches,
Explanation,
GenerationPlaybook,
GenerationRole,
Feedback,
Chat,
]
Empty file.
21 changes: 21 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/telemetry/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.urls import path

from . import views

urlpatterns = [
path("", views.TelemetrySettingsView.as_view(), name="telemetry_settings"),
]
19 changes: 19 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/telemetry/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ansible_ai_connect.ai.api.telemetry.api_telemetry_settings_views import (
TelemetrySettingsView,
)

__all__ = [TelemetrySettingsView]
32 changes: 32 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf import settings
from django.urls import include, path

from .ai import urls as ai_urls
from .telemetry import urls as telemetry_urls
from .users import urls as me_urls
from .wca import urls as wca_urls

urlpatterns = [
path("ai/", include(ai_urls)),
path("me/", include(me_urls)),
]

if settings.DEBUG or settings.DEPLOYMENT_MODE == "saas":
urlpatterns += [
path("telemetry/", include(telemetry_urls)),
path("wca/", include(wca_urls)),
]
Empty file.
22 changes: 22 additions & 0 deletions ansible_ai_connect/ai/api/versions/v0/users/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.urls import path

from . import views

urlpatterns = [
path("", views.CurrentUserView.as_view(), name="me"),
path("summary/", views.MarkdownCurrentUserView.as_view(), name="me_summary"),
]
Loading

0 comments on commit 1cb2795

Please sign in to comment.