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 17, 2025
1 parent 804613e commit 7f3ad3a
Show file tree
Hide file tree
Showing 41 changed files with 766 additions and 59 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,9 +17,10 @@

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
from rest_framework.reverse import reverse as rest_reverse

import ansible_ai_connect.ai.feature_flags as feature_flags
from ansible_ai_connect.ai.api.permissions import (
Expand All @@ -39,11 +40,11 @@ def setUp(self):

def test_get_settings_authentication_error(self, *args):
# self.client.force_authenticate(user=self.user)
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.UNAUTHORIZED)

def test_permission_classes(self, *args):
url = reverse("telemetry_settings")
url = rest_reverse("ai:telemetry_settings")
view = resolve(url).func.view_class

required_permissions = [
Expand All @@ -61,7 +62,7 @@ def test_get_settings_without_org_id(self, *args):
self.client.force_authenticate(user=self.user)

with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.BAD_REQUEST)
self.assert_segment_log(log, "telemetrySettingsGet", None)

Expand All @@ -74,7 +75,7 @@ def test_get_settings_when_undefined(self, LDClient, *args):
self.client.force_authenticate(user=self.user)

with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.OK)
self.assertFalse(r.data["optOut"])
self.assert_segment_log(log, "telemetrySettingsGet", None, opt_out=False)
Expand All @@ -90,22 +91,22 @@ def test_get_settings_when_defined(self, LDClient, *args):
self.client.force_authenticate(user=self.user)

with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.OK)
self.assertTrue(r.data["optOut"])
self.assert_segment_log(log, "telemetrySettingsGet", None, opt_out=True)

def test_set_settings_authentication_error(self, *args):
# self.client.force_authenticate(user=self.user)
r = self.client.post(reverse("telemetry_settings"))
r = self.client.post(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.UNAUTHORIZED)

@override_settings(SEGMENT_WRITE_KEY="DUMMY_KEY_VALUE")
def test_set_settings_without_org_id(self, *args):
self.client.force_authenticate(user=self.user)

with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.post(reverse("telemetry_settings"))
r = self.client.post(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.BAD_REQUEST)
self.assert_segment_log(log, "telemetrySettingsSet", None)

Expand All @@ -118,15 +119,15 @@ def test_set_settings_with_valid_value(self, LDClient, *args):
self.client.force_authenticate(user=self.user)

# Settings should initially be False
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.OK)
self.assertFalse(r.data["optOut"])

# Set settings
with self.assertLogs(logger="ansible_ai_connect.users.signals", level="DEBUG") as signals:
with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.post(
reverse("telemetry_settings"),
rest_reverse("ai:telemetry_settings"),
data='{ "optOut": "True" }',
content_type="application/json",
)
Expand All @@ -141,7 +142,7 @@ def test_set_settings_with_valid_value(self, LDClient, *args):
)

# Check Settings were stored
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.OK)
self.assertTrue(r.data["optOut"])

Expand All @@ -156,7 +157,7 @@ def test_set_settings_throws_exception(self, LDClient, *args):
with patch("django.db.models.base.Model.save", side_effect=DatabaseError()):
with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.post(
reverse("telemetry_settings"),
rest_reverse("ai:telemetry_settings"),
data='{ "optOut": "False" }',
content_type="application/json",
)
Expand All @@ -173,7 +174,7 @@ def test_set_settings_throws_validation_exception(self, LDClient, *args):

with self.assertLogs(logger="root", level="DEBUG") as log:
r = self.client.post(
reverse("telemetry_settings"),
rest_reverse("ai:telemetry_settings"),
data='{ "unknown_json_field": "a-new-key" }',
content_type="application/json",
)
Expand All @@ -187,5 +188,5 @@ class TestTelemetrySettingsViewAsNonSubscriber(WisdomServiceAPITestCaseBase):
def test_get_settings_as_non_subscriber(self, *args):
self.user.organization = Organization.objects.get_or_create(id=123)[0]
self.client.force_authenticate(user=self.user)
r = self.client.get(reverse("telemetry_settings"))
r = self.client.get(rest_reverse("ai:telemetry_settings"))
self.assertEqual(r.status_code, HTTPStatus.FORBIDDEN)
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")),
]
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="summary"),
]
Loading

0 comments on commit 7f3ad3a

Please sign in to comment.