Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: feed counter #2587

Merged
merged 6 commits into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions keep-ui/app/(keep)/topology/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@ import { fetcher } from "@/utils/fetcher";
import { Session } from "next-auth";
import { TopologyApplication, TopologyService } from "../model/models";

export function buildTopologyUrl(
apiUrl: string,
{
providerIds,
services,
environment,
}: {
providerIds?: string[];
services?: string[];
environment?: string;
}
) {
const baseUrl = `${apiUrl}/topology`;
export function buildTopologyUrl({
providerIds,
services,
environment,
}: {
providerIds?: string[];
services?: string[];
environment?: string;
}) {
const baseUrl = `/topology`;

const params = new URLSearchParams();

Expand Down Expand Up @@ -57,6 +54,8 @@ export function getTopology(
if (!session) {
return null;
}
const url = buildTopologyUrl(apiUrl, { providerIds, services, environment });
return fetcher(url, session.accessToken) as Promise<TopologyService[]>;
const url = buildTopologyUrl({ providerIds, services, environment });
return fetcher(apiUrl + url, session.accessToken) as Promise<
TopologyService[]
>;
}
6 changes: 3 additions & 3 deletions keep-ui/app/(keep)/topology/model/useTopology.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { buildTopologyUrl } from "@/app/(keep)/topology/api";
import { useTopologyPollingContext } from "@/app/(keep)/topology/model/TopologyPollingContext";
import { useApiUrl } from "utils/hooks/useConfig";

export const useTopologyBaseKey = () => `${useApiUrl()}/topology`;
export const TOPOLOGY_URL = `/topology`;

type UseTopologyOptions = {
providerIds?: string[];
Expand Down Expand Up @@ -37,11 +37,11 @@ export const useTopology = (

const url = !session
? null
: buildTopologyUrl(apiUrl!, { providerIds, services, environment });
: buildTopologyUrl({ providerIds, services, environment });

const { data, error, mutate } = useSWR<TopologyService[]>(
url,
(url: string) => fetcher(url, session!.accessToken),
(url: string) => fetcher(apiUrl! + url, session!.accessToken),
{
fallbackData,
...options,
Expand Down
23 changes: 12 additions & 11 deletions keep-ui/app/(keep)/topology/model/useTopologyApplications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ import useSWR, { SWRConfiguration } from "swr";
import { fetcher } from "@/utils/fetcher";
import { useHydratedSession as useSession } from "@/shared/lib/hooks/useHydratedSession";
import { useCallback, useMemo } from "react";
import { useTopologyBaseKey, useTopology } from "./useTopology";
import { useTopology } from "./useTopology";
import { useRevalidateMultiple } from "@/utils/state";
import { TOPOLOGY_URL } from "./useTopology";

type UseTopologyApplicationsOptions = {
initialData?: TopologyApplication[];
options?: SWRConfiguration;
};

export const TOPOLOGY_APPLICATIONS_URL = `/topology/applications`;

export function useTopologyApplications(
{ initialData, options }: UseTopologyApplicationsOptions = {
options: {
Expand All @@ -21,13 +24,11 @@ export function useTopologyApplications(
) {
const apiUrl = useApiUrl();
const { data: session } = useSession();
const topologyBaseKey = useTopologyBaseKey();
const revalidateMultiple = useRevalidateMultiple();
const { topologyData, mutate: mutateTopology } = useTopology();
const topologyApplicationsKey = `${apiUrl}/topology/applications`;
const { data, error, isLoading, mutate } = useSWR<TopologyApplication[]>(
!session ? null : topologyApplicationsKey,
(url: string) => fetcher(url, session!.accessToken),
!session ? null : TOPOLOGY_APPLICATIONS_URL,
(url: string) => fetcher(apiUrl + url, session!.accessToken),
{
fallbackData: initialData,
...options,
Expand All @@ -48,7 +49,7 @@ export function useTopologyApplications(
});
if (response.ok) {
console.log("mutating on success");
revalidateMultiple([topologyBaseKey, topologyApplicationsKey]);
revalidateMultiple([TOPOLOGY_URL, TOPOLOGY_APPLICATIONS_URL]);
} else {
// Rollback optimistic update on error
throw new Error("Failed to add application", {
Expand All @@ -58,7 +59,7 @@ export function useTopologyApplications(
const json = await response.json();
return json as TopologyApplication;
},
[revalidateMultiple, session?.accessToken, topologyApplicationsKey]
[apiUrl, revalidateMultiple, session?.accessToken]
);

const updateApplication = useCallback(
Expand Down Expand Up @@ -98,7 +99,7 @@ export function useTopologyApplications(
}
);
if (response.ok) {
revalidateMultiple([topologyBaseKey, topologyApplicationsKey]);
revalidateMultiple([TOPOLOGY_URL, TOPOLOGY_APPLICATIONS_URL]);
} else {
// Rollback optimistic update on error
mutate(applications, false);
Expand All @@ -110,12 +111,12 @@ export function useTopologyApplications(
return response;
},
[
apiUrl,
applications,
mutate,
mutateTopology,
revalidateMultiple,
session?.accessToken,
topologyApplicationsKey,
topologyData,
]
);
Expand Down Expand Up @@ -152,7 +153,7 @@ export function useTopologyApplications(
}
);
if (response.ok) {
revalidateMultiple([topologyBaseKey, topologyApplicationsKey]);
revalidateMultiple([TOPOLOGY_URL, TOPOLOGY_APPLICATIONS_URL]);
} else {
// Rollback optimistic update on error
mutate(applications, false);
Expand All @@ -164,12 +165,12 @@ export function useTopologyApplications(
return response;
},
[
apiUrl,
applications,
mutate,
mutateTopology,
revalidateMultiple,
session?.accessToken,
topologyApplicationsKey,
topologyData,
]
);
Expand Down
8 changes: 6 additions & 2 deletions keep-ui/utils/hooks/usePresets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useConfig } from "./useConfig";
import useSWRSubscription from "swr/subscription";
import { useWebsocket } from "./usePusher";
import { useSearchParams } from "next/navigation";
import { useRevalidateMultiple } from "../state";

export const usePresets = (type?: string, useFilters?: boolean) => {
const { data: session } = useSession();
Expand All @@ -31,6 +32,7 @@ export const usePresets = (type?: string, useFilters?: boolean) => {
const presetsOrderRef = useRef(presetsOrderFromLS);
const staticPresetsOrderRef = useRef(staticPresetsOrderFromLS);
const { bind, unbind } = useWebsocket();
const revalidateMultiple = useRevalidateMultiple();

useEffect(() => {
presetsOrderRef.current = presetsOrderFromLS;
Expand Down Expand Up @@ -88,6 +90,8 @@ export const usePresets = (type?: string, useFilters?: boolean) => {
(_, { next }) => {
const newPresets = (newPresets: Preset[]) => {
updateLocalPresets(newPresets);
// update the presets aggregated endpoint for the sidebar
revalidateMultiple(["/preset"]);
next(null, {
presets: newPresets,
isAsyncLoading: false,
Expand All @@ -110,11 +114,11 @@ export const usePresets = (type?: string, useFilters?: boolean) => {
return useSWR<Preset[]>(
() =>
session
? `${apiUrl}/preset${
? `/preset${
useFilters && filters && isDashBoard ? `?${filters}` : ""
}`
: null,
(url) => fetcher(url, session?.accessToken),
(url) => fetcher(apiUrl + url, session?.accessToken),
{
...options,
onSuccess: (data) => {
Expand Down
14 changes: 3 additions & 11 deletions keep-ui/utils/state.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import { useSWRConfig } from "swr";

type MutateArgs = [string, (data: any) => any];

export const mutateLocalMultiple = (args: MutateArgs[]) => {
const { cache } = useSWRConfig();
args.forEach(([key, mutateFunction]) => {
const currentData = cache.get(key as string);
cache.set(key as string, mutateFunction(currentData));
});
};

export const useRevalidateMultiple = () => {
const { mutate } = useSWRConfig();
return (keys: string[]) =>
mutate((key) => typeof key === "string" && keys.includes(key));
mutate(
(key) => typeof key === "string" && keys.some((k) => key.startsWith(k))
);
};
10 changes: 7 additions & 3 deletions keep/api/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from sqlalchemy.sql import exists, expression
from sqlmodel import Session, SQLModel, col, or_, select, text

from keep.api.consts import STATIC_PRESETS
from keep.api.core.db_utils import create_db_engine, get_json_extract_field

# This import is required to create the tables
Expand Down Expand Up @@ -2615,7 +2616,7 @@
return presets


def get_preset_by_name(tenant_id: str, preset_name: str) -> Preset:
def get_db_preset_by_name(tenant_id: str, preset_name: str) -> Preset | None:
with Session(engine) as session:
preset = session.exec(
select(Preset)
Expand All @@ -2624,8 +2625,7 @@
).first()
return preset


def get_all_presets(tenant_id: str) -> List[Preset]:
def get_db_presets(tenant_id: str) -> List[Preset]:
with Session(engine) as session:
presets = (
session.exec(select(Preset).where(Preset.tenant_id == tenant_id))
Expand All @@ -2634,6 +2634,10 @@
)
return presets

def get_all_presets_dtos(tenant_id: str) -> List[PresetDto]:
presets = get_db_presets(tenant_id)
static_presets_dtos = list(STATIC_PRESETS.values())
return [PresetDto(**preset.to_dict()) for preset in presets] + static_presets_dtos

Check warning on line 2640 in keep/api/core/db.py

View check run for this annotation

Codecov / codecov/patch

keep/api/core/db.py#L2638-L2640

Added lines #L2638 - L2640 were not covered by tests

def get_dashboards(tenant_id: str, email=None) -> List[Dict[str, Any]]:
with Session(engine) as session:
Expand Down
4 changes: 2 additions & 2 deletions keep/api/routes/preset.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from sqlmodel import Session, select

from keep.api.consts import PROVIDER_PULL_INTERVAL_DAYS, STATIC_PRESETS
from keep.api.core.db import get_preset_by_name as get_preset_by_name_db
from keep.api.core.db import get_db_preset_by_name
from keep.api.core.db import get_presets as get_presets_db
from keep.api.core.db import (
get_session,
Expand Down Expand Up @@ -448,7 +448,7 @@
if preset_name in STATIC_PRESETS:
preset = STATIC_PRESETS[preset_name]
else:
preset = get_preset_by_name_db(tenant_id, preset_name)
preset = get_db_preset_by_name(tenant_id, preset_name)

Check warning on line 451 in keep/api/routes/preset.py

View check run for this annotation

Codecov / codecov/patch

keep/api/routes/preset.py#L451

Added line #L451 was not covered by tests
# if preset does not exist
if not preset:
raise HTTPException(404, "Preset not found")
Expand Down
10 changes: 4 additions & 6 deletions keep/api/tasks/process_event_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,14 @@
from keep.api.core.db import (
bulk_upsert_alert_fields,
get_alerts_by_fingerprint,
get_all_presets,
get_all_presets_dtos,
get_enrichment_with_session,
get_session_sync,
)
from keep.api.core.dependencies import get_pusher_client
from keep.api.core.elastic import ElasticClient
from keep.api.models.alert import AlertDto, AlertStatus, IncidentDto
from keep.api.models.db.alert import Alert, AlertActionType, AlertAudit, AlertRaw
from keep.api.models.db.preset import PresetDto
from keep.api.utils.enrichment_helpers import (
calculated_start_firing_time,
convert_db_alerts_to_dto_alerts,
Expand Down Expand Up @@ -443,12 +442,11 @@
return

try:
presets = get_all_presets(tenant_id)
presets = get_all_presets_dtos(tenant_id)

Check warning on line 445 in keep/api/tasks/process_event_task.py

View check run for this annotation

Codecov / codecov/patch

keep/api/tasks/process_event_task.py#L445

Added line #L445 was not covered by tests
rules_engine = RulesEngine(tenant_id=tenant_id)
presets_do_update = []
for preset in presets:
for preset_dto in presets:

Check warning on line 448 in keep/api/tasks/process_event_task.py

View check run for this annotation

Codecov / codecov/patch

keep/api/tasks/process_event_task.py#L448

Added line #L448 was not covered by tests
# filter the alerts based on the search query
preset_dto = PresetDto(**preset.to_dict())
filtered_alerts = rules_engine.filter_alerts(
enriched_formatted_events, preset_dto.cel_query
)
Expand All @@ -458,7 +456,7 @@
presets_do_update.append(preset_dto)
preset_dto.alerts_count = len(filtered_alerts)
# update noisy
if preset.is_noisy:
if preset_dto.is_noisy:

Check warning on line 459 in keep/api/tasks/process_event_task.py

View check run for this annotation

Codecov / codecov/patch

keep/api/tasks/process_event_task.py#L459

Added line #L459 was not covered by tests
firing_filtered_alerts = list(
filter(
lambda alert: alert.status == AlertStatus.FIRING.value,
Expand Down
Loading