Skip to content

Commit

Permalink
fix/Enhancement changes
Browse files Browse the repository at this point in the history
  • Loading branch information
athul-rs committed Jun 11, 2024
1 parent d0fdd4f commit 030ad01
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 24 deletions.
1 change: 1 addition & 0 deletions backend/feature_flag/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@

urlpatterns = [
path("evaluate/", views.evaluate_feature_flag, name="evaluate_feature_flag"),
path("flags/", views.list_feature_flags, name="list_feature_flags"),
]
6 changes: 3 additions & 3 deletions backend/feature_flag/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
from utils.request.feature_flag import check_feature_flag_status
from utils.request.feature_flag import check_feature_flag_status, list_all_flags

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -56,8 +56,8 @@ def list_feature_flags(request: Request) -> Response:
list of feature flags
"""
try:
namespace_key = request.data.get("namespace_key") or "default"
feature_flags = list_feature_flags(namespace_key)
namespace_key = request.data.get("namespace") or "default"
feature_flags = list_all_flags(namespace_key)
return Response({"feature_flags": feature_flags}, status=status.HTTP_200_OK)
except Exception as e:
logger.error("No response from server: %s", e)
Expand Down
7 changes: 4 additions & 3 deletions backend/utils/request/feature_flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Optional

from unstract.flags.clients.evaluation_client import EvaluationClient
from unstract.flags.clients.flipt_client import FliptClient


def check_feature_flag_status(
Expand Down Expand Up @@ -39,12 +40,12 @@ def check_feature_flag_status(
print(f"Error: {str(e)}")
return False

def list_feature_flags(
def list_all_flags(
namespace_key: str,
) -> dict:
try:
evaluation_client = EvaluationClient()
response = evaluation_client.list_feature_flags(
flipt_client = FliptClient()
response = flipt_client.list_feature_flags(
namespace_key=namespace_key,
)
return response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ try {
const SideNavBar = ({ collapsed }) => {
const navigate = useNavigate();
const { sessionDetails } = useSessionStore();
const { orgName, appDeployment } = sessionDetails;
const { orgName, flags } = sessionDetails;

const data = [
{
Expand Down Expand Up @@ -144,7 +144,7 @@ const SideNavBar = ({ collapsed }) => {
},
];

if (getMenuItem && appDeployment) {
if (getMenuItem && flags.app_deployment) {
data[0].subMenu.splice(1, 0, getMenuItem.default(orgName));
}

Expand Down
35 changes: 35 additions & 0 deletions frontend/src/helpers/FeatureFlagsData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import axios from "axios";

async function makeApiCall(url, data, csrfToken) {
const headers = {
"X-CSRFToken": csrfToken,
};

try {
const response = await axios.post(url, data, { headers });
return response?.data;
} catch (error) {
console.error(`Error making API call to ${url}: ${error}`);
return null;
}
}

export async function evaluateFeatureFlag(orgId, csrfToken, featureFlag) {
const url = `/api/v1/unstract/${orgId}/evaluate/`;
const data = {
flag_key: featureFlag,
};

const response = await makeApiCall(url, data, csrfToken);
return response?.flag_status ?? false;
}

export async function listFlags(orgId, csrfToken, namespace = "default") {
const url = `/api/v1/unstract/${orgId}/flags/`;
const data = {
namespace: namespace ?? null,
};

const response = await makeApiCall(url, data, csrfToken);
return response.feature_flags.flags ?? {};
}
2 changes: 1 addition & 1 deletion frontend/src/helpers/GetSessionData.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function getSessionData(sessionData) {
isPlatformAdmin: sessionData?.isPlatformAdmin,
loginOnboardingMessage: sessionData?.loginOnboardingMessage,
promptOnboardingMessage: sessionData?.promptOnboardingMessage,
appDeployment: sessionData?.appDeployment,
flags: sessionData?.flags,
};
}

Expand Down
13 changes: 3 additions & 10 deletions frontend/src/hooks/useSessionValid.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import { getSessionData } from "../helpers/GetSessionData";
import { useExceptionHandler } from "../hooks/useExceptionHandler.jsx";
import { useSessionStore } from "../store/session-store";
import { useUserSession } from "./useUserSession.js";
import { listFlags } from "../helpers/FeatureFlagsData.js";

let getTrialDetails;
let isPlatformAdmin;
let getFlagStatus;
try {
getTrialDetails = require("../plugins/subscription/trial-helper/fetchTrialDetails.jsx");
getFlagStatus = require("../plugins/enterprise-utils/fetchFeatureFlagStatus.jsx");
isPlatformAdmin =
require("../plugins/hooks/usePlatformAdmin.js").usePlatformAdmin();
} catch (err) {
Expand Down Expand Up @@ -107,14 +106,8 @@ function useSessionValid() {
userAndOrgDetails["remainingTrialDays"] = remainingTrialDays;
}

if (getFlagStatus) {
const appDeploymentFlag = await getFlagStatus.fetchFeatureFlags(
orgId,
csrfToken,
"app_deployment"
);
userAndOrgDetails["appDeployment"] = appDeploymentFlag;
}
const flags = await listFlags(orgId, csrfToken);
userAndOrgDetails["flags"] = flags;

userAndOrgDetails["allOrganization"] = orgs;
if (isPlatformAdmin) {
Expand Down
3 changes: 2 additions & 1 deletion unstract/flags/src/unstract/flags/clients/base_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import grpc

class BaseClient:
def __init__(self, stub_class) -> None:
Expand All @@ -11,4 +12,4 @@ def __init__(self, stub_class) -> None:
self.channel = grpc.insecure_channel(
f"{evaluation_server_ip}:{evaluation_server_port}"
)
self.stub = stub_class(self.channel)
self.stub = stub_class(self.channel)
35 changes: 31 additions & 4 deletions unstract/flags/src/unstract/flags/clients/flipt_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,42 @@
from ..generated import flipt_pb2, flipt_pb2_grpc

class FliptClient(BaseClient):
def __init__(self):
super().__init__(flipt_pb2_grpc.FliptStub())
def __init__(self) -> None:
super().__init__(flipt_pb2_grpc.FliptStub)

def parse_flag_list(self, response):
flags = response.flags
total_count = response.total_count

parsed_flags = {}
for flag in flags:
enabled_status = flag.enabled if hasattr(flag, 'enabled') else None
parsed_flags[flag.key] = enabled_status
return {
"flags": parsed_flags,
"total_count": total_count
}

def list_feature_flags(self, namespace_key: str) -> dict:
try:
request = flipt_pb2.ListFlagRequest(namespace_key=namespace_key)
response = self.stub.ListFlags(request)
logging.info(f"************* Evaluation Response : {response}")
return response
parsed_response = self.parse_flag_list(response)
return parsed_response
except grpc.RpcError as e:
logging.error(f"Error communicating with evaluation server: {e}")
return {}

def evaluate_feature_flag(self, namespace_key: str, flag_key: str, entity_id: str, context: dict = None) -> bool:
try:
request = flipt_pb2.EvaluationRequest(
namespace_key=namespace_key,
flag_key=flag_key,
entity_id=entity_id,
context=context or {}
)
response = self.stub.Evaluate(request)
return response.match
except grpc.RpcError as e:
logging.error(f"Error evaluating feature flag: {e}")
return False

0 comments on commit 030ad01

Please sign in to comment.