SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(preference): add support for objects and arrays (#8142)
Vibhu Pandeyeb94554f5a4b
diff --git a/frontend/src/AppRoutes/Private.tsx b/frontend/src/AppRoutes/Private.tsxindex e761c8cf43..c03fdd0c19 100644--- a/frontend/src/AppRoutes/Private.tsx+++ b/frontend/src/AppRoutes/Private.tsx@@ -95,7 +95,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {usersData.data) {const isOnboardingComplete = orgPreferences?.find(- (preference: Record<string, any>) => preference.key === 'ORG_ONBOARDING',+ (preference: Record<string, any>) => preference.name === 'org_onboarding',)?.value;const isFirstUser = checkFirstTimeUser();diff --git a/frontend/src/api/preferences/getAllOrgPreferences.ts b/frontend/src/api/preferences/getAllOrgPreferences.tsdeleted file mode 100644index 12f6497c0e..0000000000--- a/frontend/src/api/preferences/getAllOrgPreferences.ts+++ /dev/null@@ -1,18 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import { GetAllOrgPreferencesResponseProps } from 'types/api/preferences/userOrgPreferences';--const getAllOrgPreferences = async (): Promise<- SuccessResponse<GetAllOrgPreferencesResponseProps> | ErrorResponse-> => {- const response = await axios.get(`/org/preferences`);-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data,- };-};--export default getAllOrgPreferences;diff --git a/frontend/src/api/preferences/getAllUserPreference.ts b/frontend/src/api/preferences/getAllUserPreference.tsdeleted file mode 100644index f7e94f76cb..0000000000--- a/frontend/src/api/preferences/getAllUserPreference.ts+++ /dev/null@@ -1,18 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import { GetAllUserPreferencesResponseProps } from 'types/api/preferences/userOrgPreferences';--const getAllUserPreferences = async (): Promise<- SuccessResponse<GetAllUserPreferencesResponseProps> | ErrorResponse-> => {- const response = await axios.get(`/user/preferences`);-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data,- };-};--export default getAllUserPreferences;diff --git a/frontend/src/api/preferences/getOrgPreference.ts b/frontend/src/api/preferences/getOrgPreference.tsdeleted file mode 100644index 6a016ddd3a..0000000000--- a/frontend/src/api/preferences/getOrgPreference.ts+++ /dev/null@@ -1,20 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import { GetOrgPreferenceResponseProps } from 'types/api/preferences/userOrgPreferences';--const getOrgPreference = async ({- preferenceID,-}: {- preferenceID: string;-}): Promise<SuccessResponse<GetOrgPreferenceResponseProps> | ErrorResponse> => {- const response = await axios.get(`/org/preferences/${preferenceID}`);-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data,- };-};--export default getOrgPreference;diff --git a/frontend/src/api/preferences/getUserPreference.ts b/frontend/src/api/preferences/getUserPreference.tsdeleted file mode 100644index a750732a92..0000000000--- a/frontend/src/api/preferences/getUserPreference.ts+++ /dev/null@@ -1,22 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import { GetUserPreferenceResponseProps } from 'types/api/preferences/userOrgPreferences';--const getUserPreference = async ({- preferenceID,-}: {- preferenceID: string;-}): Promise<- SuccessResponse<GetUserPreferenceResponseProps> | ErrorResponse-> => {- const response = await axios.get(`/user/preferences/${preferenceID}`);-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data,- };-};--export default getUserPreference;diff --git a/frontend/src/api/preferences/updateOrgPreference.ts b/frontend/src/api/preferences/updateOrgPreference.tsdeleted file mode 100644index aae4d83ddf..0000000000--- a/frontend/src/api/preferences/updateOrgPreference.ts+++ /dev/null@@ -1,28 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import {- UpdateOrgPreferenceProps,- UpdateOrgPreferenceResponseProps,-} from 'types/api/preferences/userOrgPreferences';--const updateOrgPreference = async (- preferencePayload: UpdateOrgPreferenceProps,-): Promise<- SuccessResponse<UpdateOrgPreferenceResponseProps> | ErrorResponse-> => {- const response = await axios.put(- `/org/preferences/${preferencePayload.preferenceID}`,- {- preference_value: preferencePayload.value,- },- );-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data.data,- };-};--export default updateOrgPreference;diff --git a/frontend/src/api/preferences/updateUserPreference.ts b/frontend/src/api/preferences/updateUserPreference.tsdeleted file mode 100644index 3cf215993f..0000000000--- a/frontend/src/api/preferences/updateUserPreference.ts+++ /dev/null@@ -1,28 +0,0 @@-import axios from 'api';-import { ErrorResponse, SuccessResponse } from 'types/api';-import {- UpdateUserPreferenceProps,- UpdateUserPreferenceResponseProps,-} from 'types/api/preferences/userOrgPreferences';--const updateUserPreference = async (- preferencePayload: UpdateUserPreferenceProps,-): Promise<- SuccessResponse<UpdateUserPreferenceResponseProps> | ErrorResponse-> => {- const response = await axios.put(- `/user/preferences/${preferencePayload.preferenceID}`,- {- preference_value: preferencePayload.value,- },- );-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data.data,- };-};--export default updateUserPreference;diff --git a/frontend/src/api/v1/org/preferences/list.ts b/frontend/src/api/v1/org/preferences/list.tsnew file mode 100644index 0000000000..6864639908--- /dev/null+++ b/frontend/src/api/v1/org/preferences/list.ts@@ -0,0 +1,23 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { PayloadProps } from 'types/api/preferences/list';+import { OrgPreference } from 'types/api/preferences/preference';++const listPreference = async (): Promise<+ SuccessResponseV2<OrgPreference[]>+> => {+ try {+ const response = await axios.get<PayloadProps>(`/org/preferences`);++ return {+ httpStatusCode: response.status,+ data: response.data.data,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default listPreference;diff --git a/frontend/src/api/v1/org/preferences/name/get.ts b/frontend/src/api/v1/org/preferences/name/get.tsnew file mode 100644index 0000000000..48e746d2a1--- /dev/null+++ b/frontend/src/api/v1/org/preferences/name/get.ts@@ -0,0 +1,25 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { PayloadProps, Props } from 'types/api/preferences/get';+import { OrgPreference } from 'types/api/preferences/preference';++const getPreference = async (+ props: Props,+): Promise<SuccessResponseV2<OrgPreference>> => {+ try {+ const response = await axios.get<PayloadProps>(+ `/org/preferences/${props.name}`,+ );++ return {+ httpStatusCode: response.status,+ data: response.data.data,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default getPreference;diff --git a/frontend/src/api/v1/org/preferences/name/update.ts b/frontend/src/api/v1/org/preferences/name/update.tsnew file mode 100644index 0000000000..d226c9b96c--- /dev/null+++ b/frontend/src/api/v1/org/preferences/name/update.ts@@ -0,0 +1,22 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { Props } from 'types/api/preferences/update';++const update = async (props: Props): Promise<SuccessResponseV2<null>> => {+ try {+ const response = await axios.put(`/org/preferences/${props.name}`, {+ value: props.value,+ });++ return {+ httpStatusCode: response.status,+ data: null,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default update;diff --git a/frontend/src/api/v1/user/preferences/get.ts b/frontend/src/api/v1/user/preferences/get.tsdeleted file mode 100644index 5a29113fa4..0000000000--- a/frontend/src/api/v1/user/preferences/get.ts+++ /dev/null@@ -1,24 +0,0 @@-import axios from 'api';-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';-import { AxiosError } from 'axios';-import { ErrorResponse, SuccessResponse } from 'types/api';-import { PayloadProps } from 'types/api/user/getUserPreference';--const getPreference = async (): Promise<- SuccessResponse<PayloadProps> | ErrorResponse-> => {- try {- const response = await axios.get(`/user/preferences`);-- return {- statusCode: 200,- error: null,- message: response.data.status,- payload: response.data,- };- } catch (error) {- return ErrorResponseHandler(error as AxiosError);- }-};--export default getPreference;diff --git a/frontend/src/api/v1/user/preferences/list.ts b/frontend/src/api/v1/user/preferences/list.tsnew file mode 100644index 0000000000..f2af94c2c8--- /dev/null+++ b/frontend/src/api/v1/user/preferences/list.ts@@ -0,0 +1,21 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { PayloadProps } from 'types/api/preferences/list';+import { UserPreference } from 'types/api/preferences/preference';++const list = async (): Promise<SuccessResponseV2<UserPreference[]>> => {+ try {+ const response = await axios.get<PayloadProps>(`/user/preferences`);++ return {+ httpStatusCode: response.status,+ data: response.data.data,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default list;diff --git a/frontend/src/api/v1/user/preferences/name/get.ts b/frontend/src/api/v1/user/preferences/name/get.tsnew file mode 100644index 0000000000..941c96f849--- /dev/null+++ b/frontend/src/api/v1/user/preferences/name/get.ts@@ -0,0 +1,25 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { PayloadProps, Props } from 'types/api/preferences/get';+import { UserPreference } from 'types/api/preferences/preference';++const get = async (+ props: Props,+): Promise<SuccessResponseV2<UserPreference>> => {+ try {+ const response = await axios.get<PayloadProps>(+ `/user/preferences/${props.name}`,+ );++ return {+ httpStatusCode: response.status,+ data: response.data.data,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default get;diff --git a/frontend/src/api/v1/user/preferences/name/update.ts b/frontend/src/api/v1/user/preferences/name/update.tsnew file mode 100644index 0000000000..1f9605f877--- /dev/null+++ b/frontend/src/api/v1/user/preferences/name/update.ts@@ -0,0 +1,22 @@+import axios from 'api';+import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';+import { AxiosError } from 'axios';+import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';+import { Props } from 'types/api/preferences/update';++const update = async (props: Props): Promise<SuccessResponseV2<null>> => {+ try {+ const response = await axios.put(`/user/preferences/${props.name}`, {+ value: props.value,+ });++ return {+ httpStatusCode: response.status,+ data: null,+ };+ } catch (error) {+ ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);+ }+};++export default update;diff --git a/frontend/src/container/Home/Home.tsx b/frontend/src/container/Home/Home.tsxindex 89e69a1111..c471d8c376 100644--- a/frontend/src/container/Home/Home.tsx+++ b/frontend/src/container/Home/Home.tsx@@ -6,8 +6,8 @@ import { Alert, Button, Popover } from 'antd';import logEvent from 'api/common/logEvent';import { HostListPayload } from 'api/infraMonitoring/getHostLists';import { K8sPodsListPayload } from 'api/infraMonitoring/getK8sPodsList';-import getAllUserPreferences from 'api/preferences/getAllUserPreference';-import updateUserPreferenceAPI from 'api/preferences/updateUserPreference';+import listUserPreferences from 'api/v1/user/preferences/list';+import updateUserPreferenceAPI from 'api/v1/user/preferences/name/update';import Header from 'components/Header/Header';import { DEFAULT_ENTITY_VERSION } from 'constants/app';import { FeatureKeys } from 'constants/features';@@ -29,8 +29,8 @@ import Card from 'periscope/components/Card/Card';import { useAppContext } from 'providers/App/App';import { useCallback, useEffect, useMemo, useState } from 'react';import { useMutation, useQuery } from 'react-query';+import { UserPreference } from 'types/api/preferences/preference';import { DataSource } from 'types/common/queryBuilder';-import { UserPreference } from 'types/reducer/app';import { USER_ROLES } from 'types/roles';import { popupContainer } from 'utils/selectPopupContainer';@@ -185,7 +185,7 @@ export default function Home(): JSX.Element {const processUserPreferences = (userPreferences: UserPreference[]): void => {const checklistSkipped = userPreferences?.find(- (preference) => preference.key === 'WELCOME_CHECKLIST_DO_LATER',+ (preference) => preference.name === 'welcome_checklist_do_later',)?.value;const updatedChecklistItems = cloneDeep(checklistItems);@@ -194,7 +194,7 @@ export default function Home(): JSX.Element {const newItem = { ...item };newItem.isSkipped =userPreferences?.find(- (preference) => preference.key === item.skippedPreferenceKey,+ (preference) => preference.name === item.skippedPreferenceKey,)?.value || false;return newItem;});@@ -206,13 +206,13 @@ export default function Home(): JSX.Element {// Fetch User Preferencesconst { refetch: refetchUserPreferences } = useQuery({- queryFn: () => getAllUserPreferences(),+ queryFn: () => listUserPreferences(),queryKey: ['getUserPreferences'],enabled: true,refetchOnWindowFocus: false,onSuccess: (response) => {- if (response.payload && response.payload.data) {- processUserPreferences(response.payload.data);+ if (response.data) {+ processUserPreferences(response.data);}setLoadingUserPreferences(false);@@ -239,7 +239,7 @@ export default function Home(): JSX.Element {setUpdatingUserPreferences(true);updateUserPreference({- preferenceID: 'WELCOME_CHECKLIST_DO_LATER',+ name: 'welcome_checklist_do_later',value: true,});};@@ -249,7 +249,7 @@ export default function Home(): JSX.Element {setUpdatingUserPreferences(true);updateUserPreference({- preferenceID: item.skippedPreferenceKey,+ name: item.skippedPreferenceKey,value: true,});}diff --git a/frontend/src/container/Home/constants.ts b/frontend/src/container/Home/constants.tsindex c8fc044e6b..0844614a15 100644--- a/frontend/src/container/Home/constants.ts+++ b/frontend/src/container/Home/constants.ts@@ -3,15 +3,15 @@ import ROUTES from 'constants/routes';import { ChecklistItem } from './HomeChecklist/HomeChecklist';export const checkListStepToPreferenceKeyMap = {- WILL_DO_LATER: 'WELCOME_CHECKLIST_DO_LATER',- SEND_LOGS: 'WELCOME_CHECKLIST_SEND_LOGS_SKIPPED',- SEND_TRACES: 'WELCOME_CHECKLIST_SEND_TRACES_SKIPPED',- SEND_INFRA_METRICS: 'WELCOME_CHECKLIST_SEND_INFRA_METRICS_SKIPPED',- SETUP_DASHBOARDS: 'WELCOME_CHECKLIST_SETUP_DASHBOARDS_SKIPPED',- SETUP_ALERTS: 'WELCOME_CHECKLIST_SETUP_ALERTS_SKIPPED',- SETUP_SAVED_VIEWS: 'WELCOME_CHECKLIST_SETUP_SAVED_VIEW_SKIPPED',- SETUP_WORKSPACE: 'WELCOME_CHECKLIST_SETUP_WORKSPACE_SKIPPED',- ADD_DATA_SOURCE: 'WELCOME_CHECKLIST_ADD_DATA_SOURCE_SKIPPED',+ WILL_DO_LATER: 'welcome_checklist_do_later',+ SEND_LOGS: 'welcome_checklist_send_logs_skipped',+ SEND_TRACES: 'welcome_checklist_send_traces_skipped',+ SEND_INFRA_METRICS: 'welcome_checklist_send_infra_metrics_skipped',+ SETUP_DASHBOARDS: 'welcome_checklist_setup_dashboards_skipped',+ SETUP_ALERTS: 'welcome_checklist_setup_alerts_skipped',+ SETUP_SAVED_VIEWS: 'welcome_checklist_setup_saved_view_skipped',+ SETUP_WORKSPACE: 'welcome_checklist_setup_workspace_skipped',+ ADD_DATA_SOURCE: 'welcome_checklist_add_data_source_skipped',};export const DOCS_LINKS = {diff --git a/frontend/src/container/OnboardingQuestionaire/index.tsx b/frontend/src/container/OnboardingQuestionaire/index.tsxindex d57b4389a7..b550013993 100644--- a/frontend/src/container/OnboardingQuestionaire/index.tsx+++ b/frontend/src/container/OnboardingQuestionaire/index.tsx@@ -3,8 +3,8 @@ import './OnboardingQuestionaire.styles.scss';import { NotificationInstance } from 'antd/es/notification/interface';import logEvent from 'api/common/logEvent';import updateProfileAPI from 'api/onboarding/updateProfile';-import getAllOrgPreferences from 'api/preferences/getAllOrgPreferences';-import updateOrgPreferenceAPI from 'api/preferences/updateOrgPreference';+import listOrgPreferences from 'api/v1/org/preferences/list';+import updateOrgPreferenceAPI from 'api/v1/org/preferences/name/update';import { AxiosError } from 'axios';import { SOMETHING_WENT_WRONG } from 'constants/api';import { FeatureKeys } from 'constants/features';@@ -108,13 +108,13 @@ function OnboardingQuestionaire(): JSX.Element {}, []);const { refetch: refetchOrgPreferences } = useQuery({- queryFn: () => getAllOrgPreferences(),+ queryFn: () => listOrgPreferences(),queryKey: ['getOrgPreferences'],enabled: false,refetchOnWindowFocus: false,onSuccess: (response) => {- if (response.payload && response.payload.data) {- updateOrgPreferences(response.payload.data);+ if (response.data) {+ updateOrgPreferences(response.data);}setUpdatingOrgOnboardingStatus(false);@@ -196,7 +196,7 @@ function OnboardingQuestionaire(): JSX.Element {setUpdatingOrgOnboardingStatus(true);updateOrgPreference({- preferenceID: 'ORG_ONBOARDING',+ name: 'org_onboarding',value: true,});};diff --git a/frontend/src/providers/App/App.tsx b/frontend/src/providers/App/App.tsxindex e769592a97..b110c00096 100644--- a/frontend/src/providers/App/App.tsx+++ b/frontend/src/providers/App/App.tsx@@ -1,6 +1,6 @@import getLocalStorageApi from 'api/browser/localstorage/get';-import getAllOrgPreferences from 'api/preferences/getAllOrgPreferences';import { Logout } from 'api/utils';+import listOrgPreferences from 'api/v1/org/preferences/list';import getUserVersion from 'api/v1/version/getVersion';import { LOCALSTORAGE } from 'constants/localStorage';import dayjs from 'dayjs';@@ -25,8 +25,8 @@ import {LicenseState,TrialInfo,} from 'types/api/licensesV3/getActive';+import { OrgPreference } from 'types/api/preferences/preference';import { Organization } from 'types/api/user/getOrganization';-import { OrgPreference } from 'types/reducer/app';import { USER_ROLES } from 'types/roles';import { IAppContext, IUser } from './types';@@ -147,7 +147,7 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {isFetching: isFetchingOrgPreferences,error: orgPreferencesFetchError,} = useQuery({- queryFn: () => getAllOrgPreferences(),+ queryFn: () => listOrgPreferences(),queryKey: ['getOrgPreferences', 'app-context'],enabled: !!isLoggedIn && !!user.email && user.role === USER_ROLES.ADMIN,});@@ -162,9 +162,9 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {if (!isFetchingOrgPreferences &&orgPreferencesData &&- orgPreferencesData.payload+ orgPreferencesData.data) {- setOrgPreferences(orgPreferencesData.payload.data);+ setOrgPreferences(orgPreferencesData.data);}}, [orgPreferencesData, isFetchingOrgPreferences]);diff --git a/frontend/src/providers/App/types.ts b/frontend/src/providers/App/types.tsindex 6823b9d827..be72edfed0 100644--- a/frontend/src/providers/App/types.ts+++ b/frontend/src/providers/App/types.ts@@ -1,10 +1,10 @@import APIError from 'types/api/error';import { FeatureFlagProps as FeatureFlags } from 'types/api/features/getFeaturesFlags';import { LicenseResModel, TrialInfo } from 'types/api/licensesV3/getActive';+import { OrgPreference } from 'types/api/preferences/preference';import { Organization } from 'types/api/user/getOrganization';import { UserResponse as User } from 'types/api/user/getUser';import { PayloadProps } from 'types/api/user/getVersion';-import { OrgPreference } from 'types/reducer/app';export interface IAppContext {user: IUser;diff --git a/frontend/src/tests/test-utils.tsx b/frontend/src/tests/test-utils.tsxindex c07ae853ee..c3066a0c83 100644--- a/frontend/src/tests/test-utils.tsx+++ b/frontend/src/tests/test-utils.tsx@@ -217,13 +217,11 @@ export function getAppContextMock(featureFlagsFetchError: null,orgPreferences: [{- key: 'ORG_ONBOARDING',- name: 'Organisation Onboarding',+ name: 'org_onboarding',description: 'Organisation Onboarding',valueType: 'boolean',defaultValue: false,- allowedValues: [true, false],- isDiscreteValues: true,+ allowedValues: ['true', 'false'],allowedScopes: ['org'],value: false,},diff --git a/frontend/src/types/api/preferences/get.ts b/frontend/src/types/api/preferences/get.tsnew file mode 100644index 0000000000..83f3cdc3ad--- /dev/null+++ b/frontend/src/types/api/preferences/get.ts@@ -0,0 +1,10 @@+import { OrgPreference, UserPreference } from './preference';++export interface Props {+ name: string;+}++export interface PayloadProps {+ status: string;+ data: OrgPreference | UserPreference;+}diff --git a/frontend/src/types/api/preferences/list.ts b/frontend/src/types/api/preferences/list.tsnew file mode 100644index 0000000000..7ac4076fc3--- /dev/null+++ b/frontend/src/types/api/preferences/list.ts@@ -0,0 +1,6 @@+import { OrgPreference, UserPreference } from './preference';++export interface PayloadProps {+ status: string;+ data: OrgPreference[] | UserPreference[];+}diff --git a/frontend/src/types/api/preferences/preference.ts b/frontend/src/types/api/preferences/preference.tsnew file mode 100644index 0000000000..892ba423e6--- /dev/null+++ b/frontend/src/types/api/preferences/preference.ts@@ -0,0 +1,19 @@+export interface OrgPreference {+ name: string;+ description: string;+ valueType: string;+ defaultValue: boolean;+ allowedValues: string[];+ allowedScopes: string[];+ value: boolean;+}++export interface UserPreference {+ name: string;+ description: string;+ valueType: string;+ defaultValue: boolean;+ allowedValues: string[];+ allowedScopes: string[];+ value: boolean;+}diff --git a/frontend/src/types/api/preferences/update.ts b/frontend/src/types/api/preferences/update.tsnew file mode 100644index 0000000000..466c259432--- /dev/null+++ b/frontend/src/types/api/preferences/update.ts@@ -0,0 +1,4 @@+export interface Props {+ name: string;+ value: unknown;+}diff --git a/frontend/src/types/api/preferences/userOrgPreferences.ts b/frontend/src/types/api/preferences/userOrgPreferences.tsdeleted file mode 100644index f1384c5e75..0000000000--- a/frontend/src/types/api/preferences/userOrgPreferences.ts+++ /dev/null@@ -1,41 +0,0 @@-import { OrgPreference, UserPreference } from 'types/reducer/app';--export interface GetOrgPreferenceResponseProps {- status: string;- data: Record<string, unknown>;-}--export interface GetUserPreferenceResponseProps {- status: string;- data: Record<string, unknown>;-}--export interface GetAllOrgPreferencesResponseProps {- status: string;- data: OrgPreference[];-}--export interface GetAllUserPreferencesResponseProps {- status: string;- data: UserPreference[];-}--export interface UpdateOrgPreferenceProps {- preferenceID: string;- value: unknown;-}--export interface UpdateUserPreferenceProps {- preferenceID: string;- value: unknown;-}--export interface UpdateOrgPreferenceResponseProps {- status: string;- data: Record<string, unknown>;-}--export interface UpdateUserPreferenceResponseProps {- status: string;- data: Record<string, unknown>;-}diff --git a/frontend/src/types/api/user/getUserPreference.ts b/frontend/src/types/api/user/getUserPreference.tsdeleted file mode 100644index fe0a30bf41..0000000000--- a/frontend/src/types/api/user/getUserPreference.ts+++ /dev/null@@ -1,6 +0,0 @@-export interface PayloadProps {- hasOptedUpdates: boolean;- id: number;- isAnonymous: boolean;- uuid: string;-}diff --git a/frontend/src/types/reducer/app.ts b/frontend/src/types/reducer/app.tsindex 607a8fca79..0a2871a599 100644--- a/frontend/src/types/reducer/app.ts+++ b/frontend/src/types/reducer/app.ts@@ -9,30 +9,6 @@ export interface User {displayName: UserPayload['displayName'];}-export interface OrgPreference {- key: string;- name: string;- description: string;- valueType: string;- defaultValue: boolean;- allowedValues: any[];- isDiscreteValues: boolean;- allowedScopes: string[];- value: boolean;-}--export interface UserPreference {- key: string;- name: string;- description: string;- valueType: string;- defaultValue: boolean;- allowedValues: any[];- isDiscreteValues: boolean;- allowedScopes: string[];- value: boolean;-}-export default interface AppReducer {currentVersion: string;latestVersion: string;diff --git a/pkg/modules/preference/implpreference/handler.go b/pkg/modules/preference/implpreference/handler.goindex 9d96219f42..d73255ccdd 100644--- a/pkg/modules/preference/implpreference/handler.go+++ b/pkg/modules/preference/implpreference/handler.go@@ -11,6 +11,7 @@ import ("github.com/SigNoz/signoz/pkg/modules/preference""github.com/SigNoz/signoz/pkg/types/authtypes""github.com/SigNoz/signoz/pkg/types/preferencetypes"+ "github.com/SigNoz/signoz/pkg/valuer""github.com/gorilla/mux")@@ -22,7 +23,7 @@ func NewHandler(module preference.Module) preference.Handler {return &handler{module: module}}-func (handler *handler) GetOrg(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) ListByOrg(rw http.ResponseWriter, r *http.Request) {ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)defer cancel()@@ -32,13 +33,38 @@ func (handler *handler) GetOrg(rw http.ResponseWriter, r *http.Request) {return}- id, ok := mux.Vars(r)["preferenceId"]+ preferences, err := handler.module.ListByOrg(ctx, valuer.MustNewUUID(claims.OrgID))+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, preferences)+}++func (handler *handler) GetByOrg(rw http.ResponseWriter, r *http.Request) {+ ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ nameString, ok := mux.Vars(r)["name"]if !ok {- render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is required"))+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "name is required"))return}- preference, err := handler.module.GetOrg(ctx, id, claims.OrgID)+ name, err := preferencetypes.NewName(nameString)+ if err != nil {+ render.Error(rw, err)+ return+ }++ preference, err := handler.module.GetByOrg(ctx, valuer.MustNewUUID(claims.OrgID), name)if err != nil {render.Error(rw, err)return@@ -47,7 +73,7 @@ func (handler *handler) GetOrg(rw http.ResponseWriter, r *http.Request) {render.Success(rw, http.StatusOK, preference)}-func (handler *handler) UpdateOrg(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) UpdateByOrg(rw http.ResponseWriter, r *http.Request) {ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)defer cancel()@@ -57,21 +83,26 @@ func (handler *handler) UpdateOrg(rw http.ResponseWriter, r *http.Request) {return}- id, ok := mux.Vars(r)["preferenceId"]+ nameString, ok := mux.Vars(r)["name"]if !ok {- render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is required"))+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "name is required"))return}- req := new(preferencetypes.UpdatablePreference)+ name, err := preferencetypes.NewName(nameString)+ if err != nil {+ render.Error(rw, err)+ return+ }+ req := new(preferencetypes.UpdatablePreference)err = json.NewDecoder(r.Body).Decode(req)if err != nil {render.Error(rw, err)return}- err = handler.module.UpdateOrg(ctx, id, req.PreferenceValue, claims.OrgID)+ err = handler.module.UpdateByOrg(ctx, valuer.MustNewUUID(claims.OrgID), name, req.Value)if err != nil {render.Error(rw, err)return@@ -80,7 +111,7 @@ func (handler *handler) UpdateOrg(rw http.ResponseWriter, r *http.Request) {render.Success(rw, http.StatusNoContent, nil)}-func (handler *handler) GetAllOrg(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) ListByUser(rw http.ResponseWriter, r *http.Request) {ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)defer cancel()@@ -90,7 +121,7 @@ func (handler *handler) GetAllOrg(rw http.ResponseWriter, r *http.Request) {return}- preferences, err := handler.module.GetAllOrg(ctx, claims.OrgID)+ preferences, err := handler.module.ListByUser(ctx, valuer.MustNewUUID(claims.UserID))if err != nil {render.Error(rw, err)return@@ -99,7 +130,7 @@ func (handler *handler) GetAllOrg(rw http.ResponseWriter, r *http.Request) {render.Success(rw, http.StatusOK, preferences)}-func (handler *handler) GetUser(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) GetByUser(rw http.ResponseWriter, r *http.Request) {ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)defer cancel()@@ -109,13 +140,19 @@ func (handler *handler) GetUser(rw http.ResponseWriter, r *http.Request) {return}- id, ok := mux.Vars(r)["preferenceId"]+ nameString, ok := mux.Vars(r)["name"]if !ok {- render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is required"))+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "name is required"))+ return+ }++ name, err := preferencetypes.NewName(nameString)+ if err != nil {+ render.Error(rw, err)return}- preference, err := handler.module.GetUser(ctx, id, claims.OrgID, claims.UserID)+ preference, err := handler.module.GetByUser(ctx, valuer.MustNewUUID(claims.UserID), name)if err != nil {render.Error(rw, err)return@@ -124,7 +161,7 @@ func (handler *handler) GetUser(rw http.ResponseWriter, r *http.Request) {render.Success(rw, http.StatusOK, preference)}-func (handler *handler) UpdateUser(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) UpdateByUser(rw http.ResponseWriter, r *http.Request) {ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)defer cancel()@@ -134,43 +171,30 @@ func (handler *handler) UpdateUser(rw http.ResponseWriter, r *http.Request) {return}- id, ok := mux.Vars(r)["preferenceId"]+ nameString, ok := mux.Vars(r)["name"]if !ok {- render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is required"))+ render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "name is required"))return}- req := new(preferencetypes.UpdatablePreference)- err = json.NewDecoder(r.Body).Decode(req)+ name, err := preferencetypes.NewName(nameString)if err != nil {render.Error(rw, err)return}- err = handler.module.UpdateUser(ctx, id, req.PreferenceValue, claims.UserID)- if err != nil {- render.Error(rw, err)- return- }-- render.Success(rw, http.StatusNoContent, nil)-}--func (handler *handler) GetAllUser(rw http.ResponseWriter, r *http.Request) {- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)- defer cancel()-- claims, err := authtypes.ClaimsFromContext(ctx)+ req := new(preferencetypes.UpdatablePreference)+ err = json.NewDecoder(r.Body).Decode(req)if err != nil {render.Error(rw, err)return}- preferences, err := handler.module.GetAllUser(ctx, claims.OrgID, claims.UserID)+ err = handler.module.UpdateByUser(ctx, valuer.MustNewUUID(claims.UserID), name, req.Value)if err != nil {render.Error(rw, err)return}- render.Success(rw, http.StatusOK, preferences)+ render.Success(rw, http.StatusNoContent, nil)}diff --git a/pkg/modules/preference/implpreference/module.go b/pkg/modules/preference/implpreference/module.goindex b00261e706..6f2808cb77 100644--- a/pkg/modules/preference/implpreference/module.go+++ b/pkg/modules/preference/implpreference/module.go@@ -2,8 +2,6 @@ package implpreferenceimport ("context"- "database/sql"- "encoding/json""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/modules/preference"@@ -11,268 +9,226 @@ import ("github.com/SigNoz/signoz/pkg/valuer")-// Do not take inspiration from this code, it is a work in progress. See Organization module for a better implementation.type module struct {- store preferencetypes.Store- defaultMap map[string]preferencetypes.Preference+ store preferencetypes.Store+ available map[preferencetypes.Name]preferencetypes.Preference}-func NewModule(store preferencetypes.Store, defaultMap map[string]preferencetypes.Preference) preference.Module {- return &module{store: store, defaultMap: defaultMap}+func NewModule(store preferencetypes.Store, available map[preferencetypes.Name]preferencetypes.Preference) preference.Module {+ return &module{+ store: store,+ available: available,+ }}-func (module *module) GetOrg(ctx context.Context, preferenceID string, orgID string) (*preferencetypes.GettablePreference, error) {- preference, seen := module.defaultMap[preferenceID]- if !seen {- return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot find preference with id: %s", preferenceID)+func (module *module) ListByOrg(ctx context.Context, orgID valuer.UUID) ([]*preferencetypes.Preference, error) {+ storableOrgPreferences, err := module.store.ListByOrg(ctx, orgID)+ if err != nil {+ return nil, err+ }++ preferences := make([]*preferencetypes.Preference, 0)+ for _, availablePreference := range module.available {+ preference, err := preferencetypes.NewPreference(availablePreference.Name, preferencetypes.ScopeOrg, module.available)+ if err != nil {+ continue+ }++ // update the preference value from the storable preference+ for _, storableOrgPreference := range storableOrgPreferences {+ if storableOrgPreference.Name == preference.Name {+ value, err := preferencetypes.NewValueFromString(storableOrgPreference.Value, preference.ValueType)+ if err != nil {+ return nil, err+ }++ err = preference.UpdateValue(value)+ if err != nil {+ return nil, err+ }+ }+ }++ preferences = append(preferences, preference)}- isEnabled := preference.IsEnabledForScope(preferencetypes.OrgAllowedScope)- if !isEnabled {- return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "preference is not enabled at org scope: %s", preferenceID)+ return preferences, nil+}++func (module *module) GetByOrg(ctx context.Context, orgID valuer.UUID, name preferencetypes.Name) (*preferencetypes.Preference, error) {+ preference, err := preferencetypes.NewPreference(name, preferencetypes.ScopeOrg, module.available)+ if err != nil {+ return nil, err}- org, err := module.store.GetOrg(ctx, orgID, preferenceID)+ storableOrgPreference, err := module.store.GetByOrg(ctx, orgID, name)if err != nil {- if err == sql.ErrNoRows {- return &preferencetypes.GettablePreference{- PreferenceID: preferenceID,- PreferenceValue: preference.DefaultValue,- }, nil+ if !errors.Ast(err, errors.TypeNotFound) {+ return nil, err}- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in fetching the org preference: %s", preferenceID)}- return &preferencetypes.GettablePreference{- PreferenceID: preferenceID,- PreferenceValue: preference.SanitizeValue(org.PreferenceValue),- }, nil-}+ if storableOrgPreference != nil {+ value, err := preferencetypes.NewValueFromString(storableOrgPreference.Value, preference.ValueType)+ if err != nil {+ return nil, err+ }-func (module *module) UpdateOrg(ctx context.Context, preferenceID string, preferenceValue interface{}, orgID string) error {- preference, seen := module.defaultMap[preferenceID]- if !seen {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot find preference with id: %s", preferenceID)+ err = preference.UpdateValue(value)+ if err != nil {+ return nil, err+ }}- isEnabled := preference.IsEnabledForScope(preferencetypes.OrgAllowedScope)- if !isEnabled {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "preference is not enabled at org scope: %s", preferenceID)+ return preference, nil+}++func (module *module) UpdateByOrg(ctx context.Context, orgID valuer.UUID, name preferencetypes.Name, input any) error {+ preference, err := preferencetypes.NewPreference(name, preferencetypes.ScopeOrg, module.available)+ if err != nil {+ return err}- err := preference.IsValidValue(preferenceValue)+ value, err := preferencetypes.NewValue(input, preference.ValueType)if err != nil {return err}- storableValue, encodeErr := json.Marshal(preferenceValue)- if encodeErr != nil {- return errors.Wrapf(encodeErr, errors.TypeInvalidInput, errors.CodeInvalidInput, "error in encoding the preference value")+ err = preference.UpdateValue(value)+ if err != nil {+ return err}- org, dberr := module.store.GetOrg(ctx, orgID, preferenceID)- if dberr != nil && dberr != sql.ErrNoRows {- return errors.Wrapf(dberr, errors.TypeInternal, errors.CodeInternal, "error in getting the preference value")+ storableOrgPreference, err := module.store.GetByOrg(ctx, orgID, name)+ if err != nil {+ if !errors.Ast(err, errors.TypeNotFound) {+ return err+ }}- if dberr != nil {- org.ID = valuer.GenerateUUID()- org.PreferenceID = preferenceID- org.PreferenceValue = string(storableValue)- org.OrgID = orgID+ if storableOrgPreference == nil {+ storableOrgPreference, err = preferencetypes.NewStorableOrgPreference(preference, value, orgID)+ if err != nil {+ return err+ }} else {- org.PreferenceValue = string(storableValue)+ err = storableOrgPreference.UpdateValue(value)+ if err != nil {+ return err+ }}- dberr = module.store.UpsertOrg(ctx, org)- if dberr != nil {- return errors.Wrapf(dberr, errors.TypeInternal, errors.CodeInternal, "error in setting the preference value")+ err = module.store.UpsertByOrg(ctx, storableOrgPreference)+ if err != nil {+ return err}return nil}-func (module *module) GetAllOrg(ctx context.Context, orgID string) ([]*preferencetypes.PreferenceWithValue, error) {- allOrgs := []*preferencetypes.PreferenceWithValue{}- orgs, err := module.store.GetAllOrg(ctx, orgID)+func (module *module) ListByUser(ctx context.Context, userID valuer.UUID) ([]*preferencetypes.Preference, error) {+ storableUserPreferences, err := module.store.ListByUser(ctx, userID)if err != nil {- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in setting all org preference values")+ return nil, err}- preferenceValueMap := map[string]interface{}{}- for _, preferenceValue := range orgs {- preferenceValueMap[preferenceValue.PreferenceID] = preferenceValue.PreferenceValue- }+ preferences := make([]*preferencetypes.Preference, 0)+ for _, availablePreference := range module.available {+ preference, err := preferencetypes.NewPreference(availablePreference.Name, preferencetypes.ScopeUser, module.available)+ if err != nil {+ continue+ }- for _, preference := range module.defaultMap {- isEnabledForOrgScope := preference.IsEnabledForScope(preferencetypes.OrgAllowedScope)- if isEnabledForOrgScope {- preferenceWithValue := &preferencetypes.PreferenceWithValue{}- preferenceWithValue.Key = preference.Key- preferenceWithValue.Name = preference.Name- preferenceWithValue.Description = preference.Description- preferenceWithValue.AllowedScopes = preference.AllowedScopes- preferenceWithValue.AllowedValues = preference.AllowedValues- preferenceWithValue.DefaultValue = preference.DefaultValue- preferenceWithValue.Range = preference.Range- preferenceWithValue.ValueType = preference.ValueType- preferenceWithValue.IsDiscreteValues = preference.IsDiscreteValues- value, seen := preferenceValueMap[preference.Key]-- if seen {- preferenceWithValue.Value = value- } else {- preferenceWithValue.Value = preference.DefaultValue- }+ // update the preference value from the storable preference+ for _, storableUserPreference := range storableUserPreferences {+ if storableUserPreference.Name == preference.Name {+ value, err := preferencetypes.NewValueFromString(storableUserPreference.Value, preference.ValueType)+ if err != nil {+ return nil, err+ }- preferenceWithValue.Value = preference.SanitizeValue(preferenceWithValue.Value)- allOrgs = append(allOrgs, preferenceWithValue)+ err = preference.UpdateValue(value)+ if err != nil {+ return nil, err+ }+ }}- }- return allOrgs, nil-}-func (module *module) GetUser(ctx context.Context, preferenceID string, orgID string, userID string) (*preferencetypes.GettablePreference, error) {- preference, seen := module.defaultMap[preferenceID]- if !seen {- return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot find preference with id: %s", preferenceID)+ preferences = append(preferences, preference)}- preferenceValue := preferencetypes.GettablePreference{- PreferenceID: preferenceID,- PreferenceValue: preference.DefaultValue,- }+ return preferences, nil+}- isEnabledAtUserScope := preference.IsEnabledForScope(preferencetypes.UserAllowedScope)- if !isEnabledAtUserScope {- return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "preference is not enabled at user scope: %s", preferenceID)+func (module *module) GetByUser(ctx context.Context, userID valuer.UUID, name preferencetypes.Name) (*preferencetypes.Preference, error) {+ preference, err := preferencetypes.NewPreference(name, preferencetypes.ScopeUser, module.available)+ if err != nil {+ return nil, err}- isEnabledAtOrgScope := preference.IsEnabledForScope(preferencetypes.OrgAllowedScope)- if isEnabledAtOrgScope {- org, err := module.store.GetOrg(ctx, orgID, preferenceID)- if err != nil && err != sql.ErrNoRows {- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in fetching the org preference: %s", preferenceID)- }- if err == nil {- preferenceValue.PreferenceValue = org.PreferenceValue+ storableUserPreference, err := module.store.GetByUser(ctx, userID, name)+ if err != nil {+ if !errors.Ast(err, errors.TypeNotFound) {+ return nil, err}- }-- user, err := module.store.GetUser(ctx, userID, preferenceID)- if err != nil && err != sql.ErrNoRows {- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in fetching the user preference: %s", preferenceID)- }- if err == nil {- preferenceValue.PreferenceValue = user.PreferenceValue+ return nil, err}- return &preferencetypes.GettablePreference{- PreferenceID: preferenceValue.PreferenceID,- PreferenceValue: preference.SanitizeValue(preferenceValue.PreferenceValue),- }, nil-}+ if storableUserPreference != nil {+ value, err := preferencetypes.NewValueFromString(storableUserPreference.Value, preference.ValueType)+ if err != nil {+ return nil, err+ }-func (module *module) UpdateUser(ctx context.Context, preferenceID string, preferenceValue interface{}, userID string) error {- preference, seen := module.defaultMap[preferenceID]- if !seen {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot find preference with id: %s", preferenceID)+ err = preference.UpdateValue(value)+ if err != nil {+ return nil, err+ }}- isEnabledAtUserScope := preference.IsEnabledForScope(preferencetypes.UserAllowedScope)- if !isEnabledAtUserScope {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "preference is not enabled at user scope: %s", preferenceID)- }+ return preference, nil+}- err := preference.IsValidValue(preferenceValue)+func (module *module) UpdateByUser(ctx context.Context, userID valuer.UUID, name preferencetypes.Name, input any) error {+ preference, err := preferencetypes.NewPreference(name, preferencetypes.ScopeUser, module.available)if err != nil {return err}- storableValue, encodeErr := json.Marshal(preferenceValue)- if encodeErr != nil {- return errors.Wrapf(encodeErr, errors.TypeInvalidInput, errors.CodeInvalidInput, "error in encoding the preference value")- }-- user, dberr := module.store.GetUser(ctx, userID, preferenceID)- if dberr != nil && dberr != sql.ErrNoRows {- return errors.Wrapf(dberr, errors.TypeInternal, errors.CodeInternal, "error in getting the preference value")- }-- if dberr != nil {- user.ID = valuer.GenerateUUID()- user.PreferenceID = preferenceID- user.PreferenceValue = string(storableValue)- user.UserID = userID- } else {- user.PreferenceValue = string(storableValue)+ value, err := preferencetypes.NewValue(input, preference.ValueType)+ if err != nil {+ return err}- dberr = module.store.UpsertUser(ctx, user)- if dberr != nil {- return errors.Wrapf(dberr, errors.TypeInternal, errors.CodeInternal, "error in setting the preference value")+ err = preference.UpdateValue(value)+ if err != nil {+ return err}- return nil-}--func (module *module) GetAllUser(ctx context.Context, orgID string, userID string) ([]*preferencetypes.PreferenceWithValue, error) {- allUsers := []*preferencetypes.PreferenceWithValue{}-- orgs, err := module.store.GetAllOrg(ctx, orgID)+ storableUserPreference, err := module.store.GetByUser(ctx, userID, name)if err != nil {- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in setting all org preference values")+ if !errors.Ast(err, errors.TypeNotFound) {+ return err+ }}- preferenceOrgValueMap := map[string]interface{}{}- for _, preferenceValue := range orgs {- preferenceOrgValueMap[preferenceValue.PreferenceID] = preferenceValue.PreferenceValue+ if storableUserPreference == nil {+ storableUserPreference, err = preferencetypes.NewStorableUserPreference(preference, value, userID)+ if err != nil {+ return err+ }+ } else {+ err = storableUserPreference.UpdateValue(value)+ if err != nil {+ return err+ }}- users, err := module.store.GetAllUser(ctx, userID)+ err = module.store.UpsertByUser(ctx, storableUserPreference)if err != nil {- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "error in setting all user preference values")- }-- preferenceUserValueMap := map[string]interface{}{}- for _, preferenceValue := range users {- preferenceUserValueMap[preferenceValue.PreferenceID] = preferenceValue.PreferenceValue+ return err}- for _, preference := range module.defaultMap {- isEnabledForUserScope := preference.IsEnabledForScope(preferencetypes.UserAllowedScope)-- if isEnabledForUserScope {- preferenceWithValue := &preferencetypes.PreferenceWithValue{}- preferenceWithValue.Key = preference.Key- preferenceWithValue.Name = preference.Name- preferenceWithValue.Description = preference.Description- preferenceWithValue.AllowedScopes = preference.AllowedScopes- preferenceWithValue.AllowedValues = preference.AllowedValues- preferenceWithValue.DefaultValue = preference.DefaultValue- preferenceWithValue.Range = preference.Range- preferenceWithValue.ValueType = preference.ValueType- preferenceWithValue.IsDiscreteValues = preference.IsDiscreteValues- preferenceWithValue.Value = preference.DefaultValue-- isEnabledForOrgScope := preference.IsEnabledForScope(preferencetypes.OrgAllowedScope)- if isEnabledForOrgScope {- value, seen := preferenceOrgValueMap[preference.Key]- if seen {- preferenceWithValue.Value = value- }- }-- value, seen := preferenceUserValueMap[preference.Key]-- if seen {- preferenceWithValue.Value = value- }-- preferenceWithValue.Value = preference.SanitizeValue(preferenceWithValue.Value)- allUsers = append(allUsers, preferenceWithValue)- }- }- return allUsers, nil+ return nil}diff --git a/pkg/modules/preference/implpreference/store.go b/pkg/modules/preference/implpreference/store.goindex 9ac8734a22..2be7275b2a 100644--- a/pkg/modules/preference/implpreference/store.go+++ b/pkg/modules/preference/implpreference/store.go@@ -3,56 +3,58 @@ package implpreferenceimport ("context"+ "github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/sqlstore""github.com/SigNoz/signoz/pkg/types/preferencetypes"+ "github.com/SigNoz/signoz/pkg/valuer")type store struct {- store sqlstore.SQLStore+ sqlstore sqlstore.SQLStore}-func NewStore(db sqlstore.SQLStore) preferencetypes.Store {- return &store{store: db}+func NewStore(sqlstore sqlstore.SQLStore) preferencetypes.Store {+ return &store{sqlstore: sqlstore}}-func (store *store) GetOrg(ctx context.Context, orgID string, preferenceID string) (*preferencetypes.StorableOrgPreference, error) {+func (store *store) GetByOrg(ctx context.Context, orgID valuer.UUID, name preferencetypes.Name) (*preferencetypes.StorableOrgPreference, error) {orgPreference := new(preferencetypes.StorableOrgPreference)+err := store.- store.+ sqlstore.BunDB().NewSelect().Model(orgPreference).- Where("preference_id = ?", preferenceID).+ Where("preference_id = ?", name).Where("org_id = ?", orgID).Scan(ctx)-if err != nil {- return orgPreference, err+ return nil, store.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "preference with name %s not found", name)}return orgPreference, nil}-func (store *store) GetAllOrg(ctx context.Context, orgID string) ([]*preferencetypes.StorableOrgPreference, error) {+func (store *store) ListByOrg(ctx context.Context, orgID valuer.UUID) ([]*preferencetypes.StorableOrgPreference, error) {orgPreferences := make([]*preferencetypes.StorableOrgPreference, 0)+err := store.- store.+ sqlstore.BunDB().NewSelect().Model(&orgPreferences).Where("org_id = ?", orgID).Scan(ctx)-if err != nil {- return orgPreferences, err+ return nil, err}return orgPreferences, nil}-func (store *store) UpsertOrg(ctx context.Context, orgPreference *preferencetypes.StorableOrgPreference) error {+func (store *store) UpsertByOrg(ctx context.Context, orgPreference *preferencetypes.StorableOrgPreference) error {_, err := store.- store.+ sqlstore.BunDB().NewInsert().Model(orgPreference).@@ -65,44 +67,44 @@ func (store *store) UpsertOrg(ctx context.Context, orgPreference *preferencetypereturn nil}-func (store *store) GetUser(ctx context.Context, userID string, preferenceID string) (*preferencetypes.StorableUserPreference, error) {+func (store *store) GetByUser(ctx context.Context, userID valuer.UUID, name preferencetypes.Name) (*preferencetypes.StorableUserPreference, error) {userPreference := new(preferencetypes.StorableUserPreference)+err := store.- store.+ sqlstore.BunDB().NewSelect().Model(userPreference).- Where("preference_id = ?", preferenceID).+ Where("preference_id = ?", name).Where("user_id = ?", userID).Scan(ctx)-if err != nil {- return userPreference, err+ return nil, store.sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "preference with name %s not found", name)}return userPreference, nil}-func (store *store) GetAllUser(ctx context.Context, userID string) ([]*preferencetypes.StorableUserPreference, error) {+func (store *store) ListByUser(ctx context.Context, userID valuer.UUID) ([]*preferencetypes.StorableUserPreference, error) {userPreferences := make([]*preferencetypes.StorableUserPreference, 0)+err := store.- store.+ sqlstore.BunDB().NewSelect().Model(&userPreferences).Where("user_id = ?", userID).Scan(ctx)-if err != nil {- return userPreferences, err+ return nil, err}return userPreferences, nil}-func (store *store) UpsertUser(ctx context.Context, userPreference *preferencetypes.StorableUserPreference) error {+func (store *store) UpsertByUser(ctx context.Context, userPreference *preferencetypes.StorableUserPreference) error {_, err := store.- store.+ sqlstore.BunDB().NewInsert().Model(userPreference).diff --git a/pkg/modules/preference/preference.go b/pkg/modules/preference/preference.goindex e740634466..2b7442d14e 100644--- a/pkg/modules/preference/preference.go+++ b/pkg/modules/preference/preference.go@@ -5,44 +5,45 @@ import ("net/http""github.com/SigNoz/signoz/pkg/types/preferencetypes"+ "github.com/SigNoz/signoz/pkg/valuer")type Module interface {- // Returns the preference for the given organization- GetOrg(ctx context.Context, preferenceId string, orgId string) (*preferencetypes.GettablePreference, error)+ // Returns all preferences for the given organization+ ListByOrg(context.Context, valuer.UUID) ([]*preferencetypes.Preference, error)- // Returns the preference for the given user- GetUser(ctx context.Context, preferenceId string, orgId string, userId string) (*preferencetypes.GettablePreference, error)+ // Returns the preference for the given organization by name.+ GetByOrg(context.Context, valuer.UUID, preferencetypes.Name) (*preferencetypes.Preference, error)- // Returns all preferences for the given organization- GetAllOrg(ctx context.Context, orgId string) ([]*preferencetypes.PreferenceWithValue, error)+ // Updates the preference for the given organization+ UpdateByOrg(context.Context, valuer.UUID, preferencetypes.Name, any) error// Returns all preferences for the given user- GetAllUser(ctx context.Context, orgId string, userId string) ([]*preferencetypes.PreferenceWithValue, error)+ ListByUser(context.Context, valuer.UUID) ([]*preferencetypes.Preference, error)- // Updates the preference for the given organization- UpdateOrg(ctx context.Context, preferenceId string, preferenceValue interface{}, orgId string) error+ // Returns the preference for the given user by name.+ GetByUser(context.Context, valuer.UUID, preferencetypes.Name) (*preferencetypes.Preference, error)// Updates the preference for the given user- UpdateUser(ctx context.Context, preferenceId string, preferenceValue interface{}, userId string) error+ UpdateByUser(context.Context, valuer.UUID, preferencetypes.Name, any) error}type Handler interface {// Returns the preference for the given organization- GetOrg(http.ResponseWriter, *http.Request)+ GetByOrg(http.ResponseWriter, *http.Request)// Updates the preference for the given organization- UpdateOrg(http.ResponseWriter, *http.Request)+ UpdateByOrg(http.ResponseWriter, *http.Request)// Returns all preferences for the given organization- GetAllOrg(http.ResponseWriter, *http.Request)+ ListByOrg(http.ResponseWriter, *http.Request)// Returns the preference for the given user- GetUser(http.ResponseWriter, *http.Request)+ GetByUser(http.ResponseWriter, *http.Request)// Updates the preference for the given user- UpdateUser(http.ResponseWriter, *http.Request)+ UpdateByUser(http.ResponseWriter, *http.Request)// Returns all preferences for the given user- GetAllUser(http.ResponseWriter, *http.Request)+ ListByUser(http.ResponseWriter, *http.Request)}diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.goindex 30cd18d274..f70d45c3c0 100644--- a/pkg/query-service/app/http_handler.go+++ b/pkg/query-service/app/http_handler.go@@ -561,12 +561,12 @@ func (aH *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {router.HandleFunc("/api/v1/disks", am.ViewAccess(aH.getDisks)).Methods(http.MethodGet)- router.HandleFunc("/api/v1/user/preferences", am.ViewAccess(aH.Signoz.Handlers.Preference.GetAllUser)).Methods(http.MethodGet)- router.HandleFunc("/api/v1/user/preferences/{preferenceId}", am.ViewAccess(aH.Signoz.Handlers.Preference.GetUser)).Methods(http.MethodGet)- router.HandleFunc("/api/v1/user/preferences/{preferenceId}", am.ViewAccess(aH.Signoz.Handlers.Preference.UpdateUser)).Methods(http.MethodPut)- router.HandleFunc("/api/v1/org/preferences", am.AdminAccess(aH.Signoz.Handlers.Preference.GetAllOrg)).Methods(http.MethodGet)- router.HandleFunc("/api/v1/org/preferences/{preferenceId}", am.AdminAccess(aH.Signoz.Handlers.Preference.GetOrg)).Methods(http.MethodGet)- router.HandleFunc("/api/v1/org/preferences/{preferenceId}", am.AdminAccess(aH.Signoz.Handlers.Preference.UpdateOrg)).Methods(http.MethodPut)+ router.HandleFunc("/api/v1/user/preferences", am.ViewAccess(aH.Signoz.Handlers.Preference.ListByUser)).Methods(http.MethodGet)+ router.HandleFunc("/api/v1/user/preferences/{name}", am.ViewAccess(aH.Signoz.Handlers.Preference.GetByUser)).Methods(http.MethodGet)+ router.HandleFunc("/api/v1/user/preferences/{name}", am.ViewAccess(aH.Signoz.Handlers.Preference.UpdateByUser)).Methods(http.MethodPut)+ router.HandleFunc("/api/v1/org/preferences", am.AdminAccess(aH.Signoz.Handlers.Preference.ListByOrg)).Methods(http.MethodGet)+ router.HandleFunc("/api/v1/org/preferences/{name}", am.AdminAccess(aH.Signoz.Handlers.Preference.GetByOrg)).Methods(http.MethodGet)+ router.HandleFunc("/api/v1/org/preferences/{name}", am.AdminAccess(aH.Signoz.Handlers.Preference.UpdateByOrg)).Methods(http.MethodPut)// Quick Filtersrouter.HandleFunc("/api/v1/orgs/me/filters", am.ViewAccess(aH.Signoz.Handlers.QuickFilter.GetQuickFilters)).Methods(http.MethodGet)diff --git a/pkg/signoz/module.go b/pkg/signoz/module.goindex bda2fcb702..25b10f5312 100644--- a/pkg/signoz/module.go+++ b/pkg/signoz/module.go@@ -34,7 +34,7 @@ type Modules struct {Apdex apdex.ModuleDashboard dashboard.ModuleQuickFilter quickfilter.Module- TraceFunnel tracefunnel.Module+ TraceFunnel tracefunnel.Module}func NewModules(@@ -51,12 +51,12 @@ func NewModules(return Modules{OrgGetter: orgGetter,OrgSetter: orgSetter,- Preference: implpreference.NewModule(implpreference.NewStore(sqlstore), preferencetypes.NewDefaultPreferenceMap()),+ Preference: implpreference.NewModule(implpreference.NewStore(sqlstore), preferencetypes.NewAvailablePreference()),SavedView: implsavedview.NewModule(sqlstore),Apdex: implapdex.NewModule(sqlstore),Dashboard: impldashboard.NewModule(sqlstore, providerSettings),User: user,QuickFilter: quickfilter,- TraceFunnel: impltracefunnel.NewModule(impltracefunnel.NewStore(sqlstore)),+ TraceFunnel: impltracefunnel.NewModule(impltracefunnel.NewStore(sqlstore)),}}diff --git a/pkg/types/preferencetypes/name.go b/pkg/types/preferencetypes/name.gonew file mode 100644index 0000000000..2ff280e0fe--- /dev/null+++ b/pkg/types/preferencetypes/name.go@@ -0,0 +1,46 @@+package preferencetypes++import (+ "slices"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/valuer"+)++var (+ NameOrgOnboarding = Name{valuer.NewString("org_onboarding")}+ NameWelcomeChecklistDoLater = Name{valuer.NewString("welcome_checklist_do_later")}+ NameWelcomeChecklistSendLogsSkipped = Name{valuer.NewString("welcome_checklist_send_logs_skipped")}+ NameWelcomeChecklistSendTracesSkipped = Name{valuer.NewString("welcome_checklist_send_traces_skipped")}+ NameWelcomeChecklistSendInfraMetricsSkipped = Name{valuer.NewString("welcome_checklist_send_infra_metrics_skipped")}+ NameWelcomeChecklistSetupDashboardsSkipped = Name{valuer.NewString("welcome_checklist_setup_dashboards_skipped")}+ NameWelcomeChecklistSetupAlertsSkipped = Name{valuer.NewString("welcome_checklist_setup_alerts_skipped")}+ NameWelcomeChecklistSetupSavedViewSkipped = Name{valuer.NewString("welcome_checklist_setup_saved_view_skipped")}+ NameSidenavPinned = Name{valuer.NewString("sidenav_pinned")}+ NameNavShortcuts = Name{valuer.NewString("nav_shortcuts")}+)++type Name struct{ valuer.String }++func NewName(name string) (Name, error) {+ ok := slices.Contains(+ []string{+ NameOrgOnboarding.StringValue(),+ NameWelcomeChecklistDoLater.StringValue(),+ NameWelcomeChecklistSendLogsSkipped.StringValue(),+ NameWelcomeChecklistSendTracesSkipped.StringValue(),+ NameWelcomeChecklistSendInfraMetricsSkipped.StringValue(),+ NameWelcomeChecklistSetupDashboardsSkipped.StringValue(),+ NameWelcomeChecklistSetupAlertsSkipped.StringValue(),+ NameWelcomeChecklistSetupSavedViewSkipped.StringValue(),+ NameSidenavPinned.StringValue(),+ NameNavShortcuts.StringValue(),+ },+ name,+ )+ if !ok {+ return Name{}, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid name: %s", name)+ }++ return Name{valuer.NewString(name)}, nil+}diff --git a/pkg/types/preferencetypes/preference.go b/pkg/types/preferencetypes/preference.goindex 16d7365675..d1461797f2 100644--- a/pkg/types/preferencetypes/preference.go+++ b/pkg/types/preferencetypes/preference.go@@ -2,298 +2,220 @@ package preferencetypesimport ("context"- "strings"+ "slices""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/types"+ "github.com/SigNoz/signoz/pkg/valuer""github.com/uptrace/bun")-type GettablePreference struct {- PreferenceID string `json:"preference_id" db:"preference_id"`- PreferenceValue interface{} `json:"preference_value" db:"preference_value"`+type Preference struct {+ // name of the preference+ Name Name `json:"name"`++ // description of the preference, will be shown to the user+ Description string `json:"description"`++ // type of the preference value+ ValueType ValueType `json:"valueType"`++ // default value of the preference+ DefaultValue Value `json:"defaultValue"`++ // Allowed scopes of the preference, can be scoped to org or user+ AllowedScopes []Scope `json:"allowedScopes"`++ // allowed values of the preference, applicable only to string value type+ AllowedValues []string `json:"allowedValues"`++ // actual value of the preference, equal to the default value initially+ Value Value `json:"value"`}type UpdatablePreference struct {- PreferenceValue interface{} `json:"preference_value" db:"preference_value"`+ Value any `json:"value"`}type StorableOrgPreference struct {bun.BaseModel `bun:"table:org_preference"`types.Identifiable- PreferenceID string `bun:"preference_id,type:text,notnull"`- PreferenceValue string `bun:"preference_value,type:text,notnull"`- OrgID string `bun:"org_id,type:text,notnull"`+ Name Name `bun:"preference_id,type:text,notnull"`+ Value string `bun:"preference_value,type:text,notnull"`+ OrgID valuer.UUID `bun:"org_id,type:text,notnull"`}type StorableUserPreference struct {bun.BaseModel `bun:"table:user_preference"`types.Identifiable- PreferenceID string `bun:"preference_id,type:text,notnull"`- PreferenceValue string `bun:"preference_value,type:text,notnull"`- UserID string `bun:"user_id,type:text,notnull"`+ Name Name `bun:"preference_id,type:text,notnull"`+ Value string `bun:"preference_value,type:text,notnull"`+ UserID valuer.UUID `bun:"user_id,type:text,notnull"`}-type Preference struct {- Key string `json:"key"`- Name string `json:"name"`- Description string `json:"description"`- ValueType string `json:"valueType"`- DefaultValue interface{} `json:"defaultValue"`- AllowedValues []interface{} `json:"allowedValues"`- IsDiscreteValues bool `json:"isDiscreteValues"`- Range Range `json:"range"`- AllowedScopes []string `json:"allowedScopes"`-}--func NewDefaultPreferenceMap() map[string]Preference {- return map[string]Preference{- "ORG_ONBOARDING": {- Key: "ORG_ONBOARDING",- Name: "Organisation Onboarding",- Description: "Organisation Onboarding",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"org"},+func NewAvailablePreference() map[Name]Preference {+ return map[Name]Preference{+ NameOrgOnboarding: {+ Name: NameOrgOnboarding,+ Description: "Organisation Onboarding",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeOrg},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),+ },+ NameWelcomeChecklistDoLater: {+ Name: NameWelcomeChecklistDoLater,+ Description: "Welcome Checklist Do Later",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_DO_LATER": {- Key: "WELCOME_CHECKLIST_DO_LATER",- Name: "Welcome Checklist Do Later",- Description: "Welcome Checklist Do Later",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSendLogsSkipped: {+ Name: NameWelcomeChecklistSendLogsSkipped,+ Description: "Welcome Checklist Send Logs Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SEND_LOGS_SKIPPED": {- Key: "WELCOME_CHECKLIST_SEND_LOGS_SKIPPED",- Name: "Welcome Checklist Send Logs Skipped",- Description: "Welcome Checklist Send Logs Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSendTracesSkipped: {+ Name: NameWelcomeChecklistSendTracesSkipped,+ Description: "Welcome Checklist Send Traces Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SEND_TRACES_SKIPPED": {- Key: "WELCOME_CHECKLIST_SEND_TRACES_SKIPPED",- Name: "Welcome Checklist Send Traces Skipped",- Description: "Welcome Checklist Send Traces Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSendInfraMetricsSkipped: {+ Name: NameWelcomeChecklistSendInfraMetricsSkipped,+ Description: "Welcome Checklist Send Infra Metrics Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SEND_INFRA_METRICS_SKIPPED": {- Key: "WELCOME_CHECKLIST_SEND_INFRA_METRICS_SKIPPED",- Name: "Welcome Checklist Send Infra Metrics Skipped",- Description: "Welcome Checklist Send Infra Metrics Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSetupDashboardsSkipped: {+ Name: NameWelcomeChecklistSetupDashboardsSkipped,+ Description: "Welcome Checklist Setup Dashboards Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SETUP_DASHBOARDS_SKIPPED": {- Key: "WELCOME_CHECKLIST_SETUP_DASHBOARDS_SKIPPED",- Name: "Welcome Checklist Setup Dashboards Skipped",- Description: "Welcome Checklist Setup Dashboards Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSetupAlertsSkipped: {+ Name: NameWelcomeChecklistSetupAlertsSkipped,+ Description: "Welcome Checklist Setup Alerts Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SETUP_ALERTS_SKIPPED": {- Key: "WELCOME_CHECKLIST_SETUP_ALERTS_SKIPPED",- Name: "Welcome Checklist Setup Alerts Skipped",- Description: "Welcome Checklist Setup Alerts Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameWelcomeChecklistSetupSavedViewSkipped: {+ Name: NameWelcomeChecklistSetupSavedViewSkipped,+ Description: "Welcome Checklist Setup Saved View Skipped",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "WELCOME_CHECKLIST_SETUP_SAVED_VIEW_SKIPPED": {- Key: "WELCOME_CHECKLIST_SETUP_SAVED_VIEW_SKIPPED",- Name: "Welcome Checklist Setup Saved View Skipped",- Description: "Welcome Checklist Setup Saved View Skipped",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameSidenavPinned: {+ Name: NameSidenavPinned,+ Description: "Controls whether the primary sidenav remains expanded or can be collapsed. When enabled, the sidenav will stay open and pinned to provide constant visibility of navigation options.",+ ValueType: ValueTypeBoolean,+ DefaultValue: MustNewValue(false, ValueTypeBoolean),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue(false, ValueTypeBoolean),},- "SIDENAV_PINNED": {- Key: "SIDENAV_PINNED",- Name: "Keep the primary sidenav always open",- Description: "Controls whether the primary sidenav remains expanded or can be collapsed. When enabled, the sidenav will stay open and pinned to provide constant visibility of navigation options.",- ValueType: "boolean",- DefaultValue: false,- AllowedValues: []interface{}{true, false},- IsDiscreteValues: true,- AllowedScopes: []string{"user"},+ NameNavShortcuts: {+ Name: NameNavShortcuts,+ Description: "A list of shortcuts to be shown in the navigation.",+ ValueType: ValueTypeArray,+ DefaultValue: MustNewValue([]any{}, ValueTypeArray),+ AllowedScopes: []Scope{ScopeUser},+ AllowedValues: []string{},+ Value: MustNewValue([]any{}, ValueTypeArray),},}}-func (p *Preference) ErrorValueTypeMismatch() error {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "the preference value is not of expected type: %s", p.ValueType)-}--func (p *Preference) checkIfInAllowedValues(preferenceValue interface{}) (bool, error) {-- switch p.ValueType {- case PreferenceValueTypeInteger:- _, ok := preferenceValue.(int64)- if !ok {- return false, p.ErrorValueTypeMismatch()- }- case PreferenceValueTypeFloat:- _, ok := preferenceValue.(float64)- if !ok {- return false, p.ErrorValueTypeMismatch()- }- case PreferenceValueTypeString:- _, ok := preferenceValue.(string)- if !ok {- return false, p.ErrorValueTypeMismatch()- }- case PreferenceValueTypeBoolean:- _, ok := preferenceValue.(bool)- if !ok {- return false, p.ErrorValueTypeMismatch()- }+func NewPreference(name Name, scope Scope, available map[Name]Preference) (*Preference, error) {+ preference, ok := available[name]+ if !ok {+ return nil, errors.Newf(errors.TypeNotFound, errors.CodeNotFound, "the preference does not exist: %s", name)}- isInAllowedValues := false- for _, value := range p.AllowedValues {- switch p.ValueType {- case PreferenceValueTypeInteger:- allowedValue, ok := value.(int64)- if !ok {- return false, p.ErrorValueTypeMismatch()- }-- if allowedValue == preferenceValue {- isInAllowedValues = true- }- case PreferenceValueTypeFloat:- allowedValue, ok := value.(float64)- if !ok {- return false, p.ErrorValueTypeMismatch()- }-- if allowedValue == preferenceValue {- isInAllowedValues = true- }- case PreferenceValueTypeString:- allowedValue, ok := value.(string)- if !ok {- return false, p.ErrorValueTypeMismatch()- }-- if allowedValue == preferenceValue {- isInAllowedValues = true- }- case PreferenceValueTypeBoolean:- allowedValue, ok := value.(bool)- if !ok {- return false, p.ErrorValueTypeMismatch()- }- if allowedValue == preferenceValue {- isInAllowedValues = true- }- }+ if !slices.Contains(preference.AllowedScopes, scope) {+ return nil, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "the preference is not allowed for the given scope: %s", scope)}- return isInAllowedValues, nil-}-func (p *Preference) IsValidValue(preferenceValue interface{}) error {- typeSafeValue := preferenceValue- switch p.ValueType {- case PreferenceValueTypeInteger:- val, ok := preferenceValue.(int64)- if !ok {- floatVal, ok := preferenceValue.(float64)- if !ok || floatVal != float64(int64(floatVal)) {- return p.ErrorValueTypeMismatch()- }- val = int64(floatVal)- typeSafeValue = val- }- if !p.IsDiscreteValues {- if val < p.Range.Min || val > p.Range.Max {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "the preference value is not in the range specified, min: %v , max: %v", p.Range.Min, p.Range.Max)- }- }- case PreferenceValueTypeString:- _, ok := preferenceValue.(string)- if !ok {- return p.ErrorValueTypeMismatch()- }- case PreferenceValueTypeFloat:- _, ok := preferenceValue.(float64)- if !ok {- return p.ErrorValueTypeMismatch()- }- case PreferenceValueTypeBoolean:- _, ok := preferenceValue.(bool)- if !ok {- return p.ErrorValueTypeMismatch()- }- }+ return &Preference{+ Name: name,+ Description: preference.Description,+ ValueType: preference.ValueType,+ DefaultValue: preference.DefaultValue,+ AllowedScopes: preference.AllowedScopes,+ Value: preference.DefaultValue,+ }, nil+}- // check the validity of the value being part of allowed values or the range specified if any- if p.IsDiscreteValues {- if p.AllowedValues != nil {- isInAllowedValues, valueMisMatchErr := p.checkIfInAllowedValues(typeSafeValue)+func NewStorableOrgPreference(preference *Preference, value Value, orgID valuer.UUID) (*StorableOrgPreference, error) {+ return &StorableOrgPreference{+ Identifiable: types.Identifiable{+ ID: valuer.GenerateUUID(),+ },+ Name: preference.Name,+ Value: value.stringValue,+ OrgID: orgID,+ }, nil+}- if valueMisMatchErr != nil {- return valueMisMatchErr- }- if !isInAllowedValues {- return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "the preference value is not in the list of allowedValues: %v", p.AllowedValues)- }- }- }- return nil+func NewStorableUserPreference(preference *Preference, value Value, userID valuer.UUID) (*StorableUserPreference, error) {+ return &StorableUserPreference{+ Identifiable: types.Identifiable{+ ID: valuer.GenerateUUID(),+ },+ Name: preference.Name,+ Value: value.stringValue,+ UserID: userID,+ }, nil}-func (p *Preference) IsEnabledForScope(scope string) bool {- isPreferenceEnabledForGivenScope := false- if p.AllowedScopes != nil {- for _, allowedScope := range p.AllowedScopes {- if allowedScope == strings.ToLower(scope) {- isPreferenceEnabledForGivenScope = true- }- }- }- return isPreferenceEnabledForGivenScope+func (storablePreference *StorableOrgPreference) UpdateValue(value Value) error {+ storablePreference.Value = value.stringValue+ return nil}-func (p *Preference) SanitizeValue(preferenceValue interface{}) interface{} {- switch p.ValueType {- case PreferenceValueTypeBoolean:- if preferenceValue == "1" || preferenceValue == true || preferenceValue == "true" {- return true- } else {- return false- }- default:- return preferenceValue- }+func (storablePreference *StorableUserPreference) UpdateValue(value Value) error {+ storablePreference.Value = value.stringValue+ return nil}type Store interface {- GetOrg(context.Context, string, string) (*StorableOrgPreference, error)- GetAllOrg(context.Context, string) ([]*StorableOrgPreference, error)- UpsertOrg(context.Context, *StorableOrgPreference) error- GetUser(context.Context, string, string) (*StorableUserPreference, error)- GetAllUser(context.Context, string) ([]*StorableUserPreference, error)- UpsertUser(context.Context, *StorableUserPreference) error+ // Returns the preference for the given organization and name.+ GetByOrg(context.Context, valuer.UUID, Name) (*StorableOrgPreference, error)++ // Returns all preferences for the given organization.+ ListByOrg(context.Context, valuer.UUID) ([]*StorableOrgPreference, error)++ // Upserts the preference for the given organization.+ UpsertByOrg(context.Context, *StorableOrgPreference) error++ // Returns the preference for the given user and name.+ GetByUser(context.Context, valuer.UUID, Name) (*StorableUserPreference, error)++ // Returns all preferences for the given user.+ ListByUser(context.Context, valuer.UUID) ([]*StorableUserPreference, error)++ // Upserts the preference for the given user.+ UpsertByUser(context.Context, *StorableUserPreference) error}diff --git a/pkg/types/preferencetypes/preference_test.go b/pkg/types/preferencetypes/preference_test.gonew file mode 100644index 0000000000..af8249d9a6--- /dev/null+++ b/pkg/types/preferencetypes/preference_test.go@@ -0,0 +1,14 @@+package preferencetypes++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestNewAvailablePreference(t *testing.T) {+ assert.NotPanics(t, func() {+ available := NewAvailablePreference()+ assert.NotNil(t, available)+ })+}diff --git a/pkg/types/preferencetypes/scope.go b/pkg/types/preferencetypes/scope.gonew file mode 100644index 0000000000..ccd14d6318--- /dev/null+++ b/pkg/types/preferencetypes/scope.go@@ -0,0 +1,10 @@+package preferencetypes++import "github.com/SigNoz/signoz/pkg/valuer"++var (+ ScopeOrg = Scope{valuer.NewString("org")}+ ScopeUser = Scope{valuer.NewString("user")}+)++type Scope struct{ valuer.String }diff --git a/pkg/types/preferencetypes/value.go b/pkg/types/preferencetypes/value.goindex c24b790a3c..d61f968f6a 100644--- a/pkg/types/preferencetypes/value.go+++ b/pkg/types/preferencetypes/value.go@@ -1,23 +1,133 @@package preferencetypes-const (- PreferenceValueTypeInteger string = "integer"- PreferenceValueTypeFloat string = "float"- PreferenceValueTypeString string = "string"- PreferenceValueTypeBoolean string = "boolean"+import (+ "encoding/json"+ "reflect"+ "slices"+ "strconv"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/valuer")-const (- OrgAllowedScope string = "org"- UserAllowedScope string = "user"+var (+ ValueTypeInteger = ValueType{valuer.NewString("integer")}+ ValueTypeFloat = ValueType{valuer.NewString("float")}+ ValueTypeString = ValueType{valuer.NewString("string")}+ ValueTypeBoolean = ValueType{valuer.NewString("boolean")}+ ValueTypeArray = ValueType{valuer.NewString("array")}+ ValueTypeObject = ValueType{valuer.NewString("object")})-type Range struct {- Min int64 `json:"min"`- Max int64 `json:"max"`+type ValueType struct{ valuer.String }++type Value struct {+ goValue any+ stringValue string+ valueType ValueType}-type PreferenceWithValue struct {- Preference- Value interface{} `json:"value"`+func NewValue(input any, valueType ValueType) (Value, error) {+ marshalledInput, err := json.Marshal(input)+ if err != nil {+ return Value{}, err+ }++ stringValue := string(marshalledInput)++ switch valueType {+ case ValueTypeInteger:+ val, err := strconv.ParseInt(stringValue, 10, 64)+ if err != nil {+ return Value{}, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "value is not an integer")+ }++ return Value{goValue: val, stringValue: stringValue, valueType: valueType}, nil++ case ValueTypeFloat:+ val, err := strconv.ParseFloat(stringValue, 64)+ if err != nil {+ return Value{}, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "value is not a float")+ }++ return Value{goValue: val, stringValue: stringValue, valueType: valueType}, nil++ case ValueTypeString:+ val, ok := input.(string)+ if !ok {+ return Value{}, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value is not a string")+ }++ return Value{goValue: val, stringValue: stringValue, valueType: valueType}, nil++ case ValueTypeBoolean:+ val, err := strconv.ParseBool(stringValue)+ if err != nil {+ return Value{}, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "value is not a boolean")+ }++ return Value{goValue: val, stringValue: stringValue, valueType: valueType}, nil++ case ValueTypeArray:+ valType := reflect.TypeOf(input)+ if valType.Kind() != reflect.Slice && valType.Kind() != reflect.Array {+ return Value{}, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value is not an array")+ }++ return Value{goValue: reflect.ValueOf(input).Interface(), stringValue: stringValue, valueType: valueType}, nil++ case ValueTypeObject:+ valType := reflect.TypeOf(input)+ if valType.Kind() != reflect.Map {+ return Value{}, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value is not an object")+ }++ return Value{goValue: reflect.ValueOf(input).Interface(), stringValue: stringValue, valueType: valueType}, nil++ default:+ return Value{}, errors.Newf(errors.TypeUnsupported, errors.CodeUnsupported, "value type is not supported: %s", valueType)+ }+}++func MustNewValue(input any, valueType ValueType) Value {+ value, err := NewValue(input, valueType)+ if err != nil {+ panic(err)+ }++ return value+}++func NewValueFromString(stringValue string, valueType ValueType) (Value, error) {+ var value any+ err := json.Unmarshal([]byte(stringValue), &value)+ if err != nil {+ return Value{}, errors.WrapInvalidInputf(err, errors.CodeInvalidInput, "value cannot be marshalled to JSON")+ }++ return NewValue(value, valueType)+}++func (value Value) MarshalJSON() ([]byte, error) {+ return []byte(value.stringValue), nil+}++func (preference *Preference) UpdateValue(value Value) error {+ if preference.ValueType != value.valueType {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value type does not match preference value type: %s", preference.ValueType)+ }++ if preference.ValueType == ValueTypeString && len(preference.AllowedValues) > 0 {+ goStringValue, ok := value.goValue.(string)+ if !ok {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value %v is not a string", value.goValue)+ }++ if !slices.Contains(preference.AllowedValues, goStringValue) {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "value %s is not in the allowed values: %v", goStringValue, preference.AllowedValues)+ }+ }++ preference.Value = value+ return nil}diff --git a/pkg/types/preferencetypes/value_test.go b/pkg/types/preferencetypes/value_test.gonew file mode 100644index 0000000000..58cd48f342--- /dev/null+++ b/pkg/types/preferencetypes/value_test.go@@ -0,0 +1,74 @@+package preferencetypes++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestNewValue(t *testing.T) {+ testCases := []struct {+ name string+ input any+ valueType ValueType+ expectedValue Value+ pass bool+ }{+ {+ name: "SimpleInteger",+ input: 1,+ valueType: ValueTypeInteger,+ expectedValue: Value{goValue: int64(1), stringValue: "1", valueType: ValueTypeInteger},+ pass: true,+ },+ {+ name: "SimpleFloat",+ input: 1.1,+ valueType: ValueTypeFloat,+ expectedValue: Value{goValue: float64(1.1), stringValue: "1.1", valueType: ValueTypeFloat},+ pass: true,+ },+ {+ name: "SimpleString",+ input: "test",+ valueType: ValueTypeString,+ expectedValue: Value{goValue: "test", stringValue: "\"test\"", valueType: ValueTypeString},+ pass: true,+ },+ {+ name: "SimpleBoolean",+ input: true,+ valueType: ValueTypeBoolean,+ expectedValue: Value{goValue: true, stringValue: "true", valueType: ValueTypeBoolean},+ pass: true,+ },+ {+ name: "SimpleArray",+ input: []any{1, 2, 3},+ valueType: ValueTypeArray,+ expectedValue: Value{goValue: []any{1, 2, 3}, stringValue: "[1,2,3]", valueType: ValueTypeArray},+ pass: true,+ },+ {+ name: "SimpleObject",+ input: map[string]any{"a": 1, "b": 2, "c": 3},+ valueType: ValueTypeObject,+ expectedValue: Value{goValue: map[string]any{"a": 1, "b": 2, "c": 3}, stringValue: `{"a":1,"b":2,"c":3}`, valueType: ValueTypeObject},+ pass: true,+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ value, err := NewValue(testCase.input, testCase.valueType)++ if !testCase.pass {+ assert.Error(t, err)+ return+ }++ assert.NoError(t, err)+ assert.Equal(t, testCase.expectedValue, value)+ })+ }+}