Merge pull request #230 from Portabase/revert-229-feat/add-healthcheck

Revert "feat: add-healthcheck"
This commit is contained in:
Charles GTE
2026-03-28 16:28:25 +01:00
committed by GitHub
53 changed files with 1333 additions and 19938 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aquasecurity/trivy-action@0.35.0
- uses: aquasecurity/trivy-action@0.20.0
with:
scan-type: 'fs'
format: 'table'
+1
View File
@@ -8,6 +8,7 @@ import Link from "next/link";
import { Separator } from "@/components/ui/separator";
import { CardAuth } from "@/features/layout/card-auth";
import { env } from "@/env.mjs";
import { en } from "zod/v4/locales";
export const metadata: Metadata = {
title: "Login",
@@ -6,7 +6,6 @@ import {SettingsTabs} from "@/components/wrappers/dashboard/admin/settings/setti
import {desc, isNull} from "drizzle-orm";
import * as drizzleDb from "@/db";
import {StorageChannelWith} from "@/db/schema/12_storage-channel";
import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
export default async function RoutePage(props: PageParams<{}>) {
@@ -14,8 +13,6 @@ export default async function RoutePage(props: PageParams<{}>) {
where: (fields, {eq}) => eq(fields.name, "system"),
});
console.log(settings)
const storageChannels = await db.query.storageChannel.findMany({
with: {
organizations: true
@@ -24,16 +21,7 @@ export default async function RoutePage(props: PageParams<{}>) {
orderBy: desc(drizzleDb.schemas.storageChannel.createdAt)
}) as StorageChannelWith[]
const notificationChannels = await db.query.notificationChannel.findMany({
with: {
organizations: true
},
where: isNull(drizzleDb.schemas.notificationChannel.organizationId),
orderBy: desc(drizzleDb.schemas.notificationChannel.createdAt)
}) as NotificationChannelWith[]
if (!settings || !storageChannels || !notificationChannels ) {
if (!settings || !storageChannels ) {
notFound()
}
@@ -45,7 +33,7 @@ export default async function RoutePage(props: PageParams<{}>) {
</div>
</PageHeader>
<PageContent className="flex flex-col gap-5">
<SettingsTabs storageChannels={storageChannels} notificationChannels={notificationChannels} settings={settings} />
<SettingsTabs storageChannels={storageChannels} settings={settings} />
</PageContent>
</Page>
);
@@ -8,7 +8,6 @@ import {getOrganizationProjectDatabases} from "@/lib/services";
import {getActiveMember, getOrganization} from "@/lib/auth/auth";
import {BackupModalProvider} from "@/components/wrappers/dashboard/database/backup/backup-modal-context";
import {DatabaseContent} from "@/components/wrappers/dashboard/projects/database/database-content";
import {getHealthLast12hLogs} from "@/db/services/healthcheck";
export default async function RoutePage(props: PageParams<{
projectId: string;
@@ -84,8 +83,6 @@ export default async function RoutePage(props: PageParams<{
notFound();
}
const databaseHealthLogs = dbItem ? await getHealthLast12hLogs({ id: dbItem.id }) : []
const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null;
@@ -98,7 +95,6 @@ export default async function RoutePage(props: PageParams<{
activeMember={activeMember}
settings={settings}
database={dbItem}
databaseHealthLogs={databaseHealthLogs}
isAlreadyRestore={isAlreadyRestore}
restorations={restorations}
backups={backups}
+3 -27
View File
@@ -67,25 +67,12 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
name: db.name,
dbms: db.dbms as EDbmsSchema,
agentDatabaseId: db.generatedId,
lastContact: db.pingStatus ? lastContact : null,
healthErrorCount: null
lastContact: lastContact,
})
.returning();
if (databaseCreated) {
await dbClient
.insert(drizzleDb.schemas.healthcheckLog)
.values({
kind: "database",
status: db.pingStatus ? "success" : "failed",
objectId: databaseCreated.id,
date: lastContact
})
const storages = await getDatabaseStorageChannels(databaseCreated.id)
databasesResponse.push(formatDatabase(databaseCreated, backupAction, restoreAction, urlBackup, storages, null));
@@ -97,23 +84,11 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
.set(withUpdatedAt({
name: db.name,
agentId: agent.id,
lastContact: db.pingStatus ? lastContact : existingDatabase.lastContact,
healthErrorCount: db.pingStatus ? null : existingDatabase.healthErrorCount,
lastContact: lastContact
}))
.where(eq(drizzleDb.schemas.database.id, existingDatabase.id))
.returning();
await dbClient
.insert(drizzleDb.schemas.healthcheckLog)
.values({
kind: "database",
status: db.pingStatus ? "success" : "failed",
objectId: databaseUpdated.id,
date: lastContact
})
const activeBackup = await dbClient.query.backup.findFirst({
where: and(
eq(drizzleDb.schemas.backup.databaseId, databaseUpdated.id),
@@ -205,6 +180,7 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat
databasesResponse.push(formatDatabase(databaseUpdated, backupAction, restoreAction, urlBackup, storages, urlMeta));
}
}
return databasesResponse;
}
+1 -11
View File
@@ -13,7 +13,6 @@ export type databaseAgent = {
name: string,
dbms: EDbmsSchema,
generatedId: string
pingStatus: boolean
}
export type Body = {
@@ -63,19 +62,10 @@ export async function POST(
.update(drizzleDb.schemas.agent)
.set(withUpdatedAt({
version: body.version,
lastContact: lastContact,
healthErrorCount: null
lastContact: lastContact
}))
.where(eq(drizzleDb.schemas.agent.id, agentId));
await db
.insert(drizzleDb.schemas.healthcheckLog)
.values({
kind: "agent",
status: "success",
objectId: agentId,
date: lastContact
})
const response = {
agent: {
-3
View File
@@ -43,9 +43,6 @@ const nextConfig: NextConfig = {
typescript: {
ignoreBuildErrors: true,
},
logging: {
browserToTerminal: false,
},
experimental: {
serverActions: {
bodySizeLimit: "10gb",
+29 -28
View File
@@ -15,8 +15,8 @@
"release": "release-it"
},
"dependencies": {
"@better-auth/passkey": "^1.5.6",
"@better-auth/sso": "^1.5.6",
"@better-auth/passkey": "^1.4.19",
"@better-auth/sso": "^1.4.19",
"@hookform/resolvers": "^5.2.2",
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-alert-dialog": "^1.1.15",
@@ -47,20 +47,20 @@
"@radix-ui/react-toggle-group": "^1.1.11",
"@radix-ui/react-tooltip": "^1.2.8",
"@react-email/components": "^0.0.41",
"@t3-oss/env-nextjs": "^0.13.11",
"@tanstack/react-query": "^5.95.2",
"@t3-oss/env-nextjs": "^0.13.10",
"@tanstack/react-query": "^5.90.21",
"@tanstack/react-table": "^8.21.3",
"@types/nodemailer": "^6.4.23",
"@types/ws": "^8.18.1",
"@zenstackhq/runtime": "2.14.2",
"argon2": "^0.43.1",
"bcrypt": "^6.0.0",
"better-auth": "1.5.6",
"better-auth": "1.4.18",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"dockerode": "^4.0.10",
"dockerode": "^4.0.9",
"dotenv": "^16.6.1",
"drizzle-orm": "^0.43.1",
"drizzle-zod": "^0.7.1",
@@ -68,23 +68,23 @@
"googleapis": "^170.1.0",
"input-otp": "^1.4.2",
"lucide-react": "^0.553.0",
"minio": "^8.0.7",
"motion": "^12.38.0",
"next": "16.2.1",
"minio": "^8.0.6",
"motion": "^12.34.3",
"next": "16.1.5",
"next-safe-action": "^7.10.8",
"next-themes": "^0.4.6",
"node-cron": "^4.2.1",
"node-forge": "^1.4.0",
"node-forge": "^1.3.3",
"nodemailer": "^7.0.13",
"npm-check-updates": "^18.3.1",
"pg": "^8.20.0",
"pg": "^8.18.0",
"prettier": "^3.8.1",
"react": "^19.2.4",
"react-day-picker": "9.7.0",
"react-dom": "^19.2.4",
"react-dropzone": "^14.4.1",
"react-email": "^4.3.2",
"react-hook-form": "^7.72.0",
"react-hook-form": "^7.71.2",
"react-qr-code": "^2.0.18",
"react-resizable-panels": "^3.0.6",
"react-twc": "^1.5.1",
@@ -94,11 +94,11 @@
"socket.io": "^4.8.3",
"socket.io-client": "^4.8.3",
"sonner": "^2.0.7",
"swiper": "^12.1.3",
"swiper": "^12.1.2",
"tailwind-merge": "^3.5.0",
"uuid": "^11.1.0",
"vaul": "^1.1.2",
"ws": "^8.20.0",
"ws": "^8.19.0",
"zod": "^3.25.76"
},
"devDependencies": {
@@ -107,29 +107,30 @@
"@react-email/preview-server": "4.3.2",
"@react-email/render": "^2.0.4",
"@release-it/bumper": "^7.0.5",
"@release-it/conventional-changelog": "^10.0.6",
"@tailwindcss/postcss": "^4.2.2",
"@release-it/conventional-changelog": "^10.0.5",
"@tailwindcss/postcss": "^4.2.1",
"@types/eslint-plugin-tailwindcss": "^3.17.0",
"@types/node": "^22.19.15",
"@types/node": "^22.19.11",
"@types/node-forge": "^1.3.14",
"@types/pg": "^8.20.0",
"@types/pg": "^8.16.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@zenstackhq/openapi": "^2.22.1",
"@zenstackhq/tanstack-query": "^2.22.2",
"baseline-browser-mapping": "^2.10.11",
"drizzle-kit": "^0.31.10",
"esbuild": "^0.27.4",
"eslint": "^9.39.4",
"eslint-config-next": "^16.2.1",
"baseline-browser-mapping": "^2.10.0",
"drizzle-kit": "^0.31.9",
"esbuild": "^0.27.3",
"eslint": "^9.39.3",
"eslint-config-next": "^16.1.6",
"eslint-plugin-tailwindcss": "^3.18.2",
"framer-motion": "^12.38.0",
"postcss": "^8.5.8",
"framer-motion": "^12.34.3",
"postcss": "^8.5.6",
"release-it": "^19.2.4",
"tailwindcss": "^4.2.2",
"tailwindcss": "^4.2.1",
"tsx": "^4.21.0",
"tw-animate-css": "^1.4.0",
"typescript": "^5.9.3",
"zenstack": "2.14.2"
}
}
},
"packageManager": "pnpm@10.30.1+sha512.3590e550d5384caa39bd5c7c739f72270234b2f6059e13018f975c313b1eb9fefcc09714048765d4d9efe961382c312e624572c0420762bdc5d5940cdf9be73a"
}
+1235 -1198
View File
File diff suppressed because it is too large Load Diff
+6 -17
View File
@@ -209,25 +209,14 @@ type UseZodFormProps<Z extends ZodSchema> = Exclude<
};
// const useZodForm = <Z extends ZodSchema>({
// schema,
// ...formProps
// }: UseZodFormProps<Z>) =>
// useForm({
// ...formProps,
// // @ts-ignore
// resolver: zodResolver(schema),
// });
const useZodForm = <Z extends ZodSchema>({
schema,
...formProps
}: UseZodFormProps<Z>): UseFormReturn<TypeOf<Z>> =>
useForm<TypeOf<Z>>({
...formProps,
schema,
...formProps
}: UseZodFormProps<Z>) =>
useForm({
...formProps,
// @ts-ignore
resolver: zodResolver(schema),
resolver: zodResolver(schema),
});
export {
@@ -1,5 +1,6 @@
"use client";
import {Card, CardContent} from "@/components/ui/card";
import {
FormControl,
FormDescription,
@@ -1,149 +0,0 @@
"use client"
import {Alert, AlertDescription, AlertTitle} from "@/components/ui/alert";
import {Info, Send} from "lucide-react";
import {ButtonWithLoading} from "@/components/wrappers/common/button/button-with-loading";
import {useRouter} from "next/navigation";
import {Setting} from "@/db/schema/01_setting";
import {
Form,
FormField,
FormItem,
FormLabel,
useZodForm
} from "@/components/ui/form";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {useMutation} from "@tanstack/react-query";
import {getChannelIcon} from "@/components/wrappers/dashboard/admin/channels/helpers/common";
import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
import {
DefaultNotificationSchema, DefaultNotificationType
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.schema";
import {
updateNotificationSettingsAction
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.action";
import {toast} from "sonner";
import {Badge} from "@/components/ui/badge";
export type SettingsNotificationSectionProps = {
settings: Setting;
notificationChannels: NotificationChannelWith[];
};
export const SettingsNotificationSection = ({settings, notificationChannels}: SettingsNotificationSectionProps) => {
const router = useRouter();
const form = useZodForm({
schema: DefaultNotificationSchema,
defaultValues: {
notificationChannelId: settings.defaultNotificationChannelId ?? "",
}
});
const mutation = useMutation({
mutationFn: async (values: DefaultNotificationType) => {
const result = await updateNotificationSettingsAction({name: "system", data: values})
const inner = result?.data;
if (inner?.success) {
toast.success(inner.actionSuccess?.message);
router.refresh();
} else {
toast.error(inner?.actionError?.message);
}
}
});
return (
<div className="flex flex-col h-full">
<Alert className="mt-3 flex items-start gap-2">
<Info className="h-4 w-4 mt-1"/>
<div>
<AlertTitle>Informations</AlertTitle>
<AlertDescription className="flex flex-wrap items-center gap-1">
The default notification channel will be used to send
<Badge>error_health_agent</Badge>
<Badge>error_health_database</Badge>
<Badge>error_backup</Badge>
<Badge>error_restore</Badge>
events. For more options like notify when success, please set policy at database level
</AlertDescription>
</div>
</Alert>
<div className="flex flex-col h-full py-4 gap-3">
<Form
className="space-y-4"
form={form}
onSubmit={async (values) => {
await mutation.mutateAsync(values);
}}
>
<div className="flex flex-wrap items-center gap-3">
<FormField
control={form.control}
name="notificationChannelId"
render={({ field }) => (
<FormItem className="flex-grow ">
<FormLabel>Default Notification Provider</FormLabel>
{notificationChannels.length === 0 ? (
<div className="text-sm text-muted-foreground">No channel available</div>
) : (
<Select
value={field.value ?? ""}
onValueChange={(value) => field.onChange(value)}
>
<SelectTrigger className="w-full h-full mb-0">
<SelectValue placeholder="Select a default channel" />
</SelectTrigger>
<SelectContent>
{notificationChannels.map((channel) => (
<SelectItem key={channel.id} value={channel.id}>
<div className="flex items-center gap-2">
{getChannelIcon(channel.provider)}
<span className="font-medium">{channel.name}</span>
<span className="text-[9px] uppercase bg-secondary px-1.5 py-0.5 rounded">
{channel.provider}
</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
</FormItem>
)}
/>
</div>
<div className="flex justify-between gap-4">
{notificationChannels.length > 0 && (
<ButtonWithLoading
type="submit"
>
Confirm
</ButtonWithLoading>
)}
<div className="flex justify-end">
{notificationChannels.length > 0 && form.getValues("notificationChannelId") ? (
<ButtonWithLoading
type="button"
variant="outline"
onClick={async () => {
form.setValue("notificationChannelId", "");
await mutation.mutateAsync({
notificationChannelId: null,
});
}}
className="flex-shrink-0 w-full sm:w-auto"
>
Reset
</ButtonWithLoading>
) : null}
</div>
</div>
</Form>
</div>
</div>
);
};
@@ -1,51 +0,0 @@
"use server"
import {userAction} from "@/lib/safe-actions/actions";
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {eq} from "drizzle-orm";
import {ServerActionResult} from "@/types/action-type";
import {Setting} from "@/db/schema/01_setting";
import {z} from "zod";
import {
DefaultNotificationSchema
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification.schema";
export const updateNotificationSettingsAction = userAction
.schema(
z.object({
name: z.string(),
data: DefaultNotificationSchema,
})
)
.action(async ({parsedInput}): Promise<ServerActionResult<Setting>> => {
const {name, data} = parsedInput;
try {
const [updatedSettings] = await db
.update(drizzleDb.schemas.setting)
.set({
defaultNotificationChannelId: data.notificationChannelId ?? null,
})
.where(eq(drizzleDb.schemas.setting.name, name))
.returning();
return {
success: true,
value: updatedSettings,
actionSuccess: {
message: "Settings successfully updated",
},
};
} catch (error) {
return {
success: false,
actionError: {
message: "Failed update settings.",
status: 500,
cause: error instanceof Error ? error.message : "Unknown error",
},
};
}
});
@@ -1,7 +0,0 @@
import {z} from "zod";
export const DefaultNotificationSchema = z.object({
notificationChannelId: z.string().optional().nullable()
});
export type DefaultNotificationType = z.infer<typeof DefaultNotificationSchema>;
@@ -7,20 +7,14 @@ import {Setting} from "@/db/schema/01_setting";
import {SettingsEmailSection} from "@/components/wrappers/dashboard/admin/settings/email/settings-email-section";
import {SettingsStorageSection} from "@/components/wrappers/dashboard/admin/settings/storage/settings-storage-section";
import {StorageChannelWith} from "@/db/schema/12_storage-channel";
import {AlarmClock, MailboxIcon, Save} from "lucide-react";
import {
SettingsNotificationSection
} from "@/components/wrappers/dashboard/admin/settings/notification/settings-notification-section";
import {NotificationChannelWith} from "@/db/schema/09_notification-channel";
import {MailboxIcon, Save} from "lucide-react";
export type SettingsTabsProps = {
settings: Setting
storageChannels: StorageChannelWith[],
notificationChannels: NotificationChannelWith[];
storageChannels: StorageChannelWith[]
};
export const SettingsTabs = ({settings, storageChannels, notificationChannels}: SettingsTabsProps) => {
export const SettingsTabs = ({settings, storageChannels}: SettingsTabsProps) => {
const router = useRouter();
const searchParams = useSearchParams();
@@ -53,15 +47,6 @@ export const SettingsTabs = ({settings, storageChannels, notificationChannels}:
content: (
<SettingsStorageSection storageChannels={storageChannels} settings={settings}/>
)
},
{
name: 'Notification',
value: 'notification',
icon: AlarmClock,
content: (
<SettingsNotificationSection notificationChannels={notificationChannels} settings={settings}/>
)
}
]
@@ -109,7 +109,7 @@ export const SettingsStorageSection = ({settings, storageChannels}: SettingsStor
control={form.control}
name="storageChannelId"
render={({field}) => (
<FormItem className="flex-grow">
<FormItem className="flex-grow min-w-[200px] sm:flex-grow-0 sm:w-64">
<FormLabel>Default Storage Provider</FormLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-full mb-0">
@@ -52,11 +52,6 @@ export const AgentCard = (props: agentCardProps) => {
<Badge variant="secondary" className="h-5 px-1.5 text-[10px] font-bold tracking-wider">
v{agent.version}
</Badge>
{agent.healthErrorCount && (
<Badge variant="destructive" className="h-5 px-1.5 text-[10px] font-bold tracking-wider">
down
</Badge>
)}
{isUpdateAvailable && (
<Tooltip>
<TooltipTrigger asChild>
@@ -17,8 +17,6 @@ import {Separator} from "@/components/ui/separator";
import {Badge} from "@/components/ui/badge";
import {CardsWithPagination} from "@/components/wrappers/common/cards-with-pagination";
import {AgentDatabaseCard} from "@/components/wrappers/dashboard/agent/agent-database-card";
import {HealthCheckGraph} from "@/components/wrappers/dashboard/health/heath-grid";
import {HealthcheckLog} from "@/db/schema/15_healthcheck-log";
type AgentContentPageProps = {
edgeKey: string;
@@ -34,8 +32,7 @@ export const AgentContentPage = ({edgeKey, agent: initialAgent}: AgentContentPag
return result?.data;
},
initialData: {
data: initialAgent,
health: []
data: initialAgent
},
staleTime: 0,
gcTime: 0,
@@ -43,15 +40,13 @@ export const AgentContentPage = ({edgeKey, agent: initialAgent}: AgentContentPag
});
const agent = data?.data ?? initialAgent;
const agentHealthLogs: HealthcheckLog[] = data?.health ?? [];
return (
<div className="space-y-10">
<div className="flex flex-col sm:flex-row sm:justify-between gap-6 ">
<Card className="w-full sm:w-auto flex-1 transition-all border-border/50 bg-card ">
<Card className="w-full sm:w-auto flex-1 border-none shadow-none bg-muted/30">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle
className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Databases</CardTitle>
<CardTitle className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Databases</CardTitle>
<Server className="h-4 w-4 text-muted-foreground opacity-50"/>
</CardHeader>
<CardContent>
@@ -60,34 +55,26 @@ export const AgentContentPage = ({edgeKey, agent: initialAgent}: AgentContentPag
</CardContent>
</Card>
<Card className="w-full sm:w-auto flex-1 transition-all border-border/50 bg-card ">
<Card className="w-full sm:w-auto flex-1 border-none shadow-none bg-muted/30">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Last
contact</CardTitle>
<CardTitle className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Last contact</CardTitle>
<Server className="h-4 w-4 text-muted-foreground opacity-50"/>
</CardHeader>
<CardContent>
<div
className="text-3xl font-bold tracking-tight">{formatDateLastContact(agent.lastContact)}</div>
<div className="text-3xl font-bold tracking-tight">{formatDateLastContact(agent.lastContact)}</div>
<p className="text-xs text-muted-foreground mt-1">Status heartbeat</p>
</CardContent>
</Card>
</div>
{agent.lastContact && (
<HealthCheckGraph logs={agentHealthLogs}/>
)}
<div className="space-y-6">
<Accordion type="single" collapsible defaultValue={!agent.lastContact ? "registration" : undefined}>
<AccordionItem value="registration"
className="border rounded-xl px-6 bg-card shadow-sm overflow-hidden transition-all duration-300">
<AccordionItem value="registration" className="border rounded-xl px-6 bg-card shadow-sm overflow-hidden transition-all duration-300">
<AccordionTrigger className="hover:no-underline py-4 group">
<div className="flex items-center gap-3">
<span className="text-xl font-bold tracking-tight">Registration & Setup</span>
{!agent.lastContact && (
<Badge variant="outline"
className="bg-orange-500/10 text-orange-600 border-orange-500/20 animate-pulse">
<Badge variant="outline" className="bg-orange-500/10 text-orange-600 border-orange-500/20 animate-pulse">
Action Required
</Badge>
)}
@@ -104,23 +91,23 @@ export const AgentContentPage = ({edgeKey, agent: initialAgent}: AgentContentPag
</div>
{agent.databases.length > 0 && (
<div className="space-y-6">
<div className="flex items-center justify-between px-1">
<div className="space-y-1">
<h2 className="text-2xl font-bold tracking-tight">Managed Databases</h2>
<p className="text-sm text-muted-foreground">
Resources currently connected to this agent.
</p>
</div>
<div className="space-y-6">
<div className="flex items-center justify-between px-1">
<div className="space-y-1">
<h2 className="text-2xl font-bold tracking-tight">Managed Databases</h2>
<p className="text-sm text-muted-foreground">
Resources currently connected to this agent.
</p>
</div>
<Separator className="opacity-50"/>
<CardsWithPagination
cardsPerPage={4}
numberOfColumns={2}
data={agent.databases}
cardItem={AgentDatabaseCard}
/>
</div>
<Separator className="opacity-50" />
<CardsWithPagination
cardsPerPage={4}
numberOfColumns={2}
data={agent.databases}
cardItem={AgentDatabaseCard}
/>
</div>
)}
</div>
)
@@ -7,7 +7,6 @@ import * as drizzleDb from "@/db";
import {BackupWith, Restoration} from "@/db/schema/07_database";
import {getOrganizationChannels} from "@/db/services/notification-channel";
import {getOrganizationStorageChannels} from "@/db/services/storage-channel";
import {getHealthLast12hLogs} from "@/db/services/healthcheck";
export const getDatabaseDataAction = userAction
.schema(
@@ -51,9 +50,7 @@ export const getDatabaseDataAction = userAction
const successfulBackups = backups.filter(b => b.status === "success").length;
const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null;
// @ts-ignore
let activeOrganizationChannels = [];
// @ts-ignore
let activeOrganizationStorageChannels = [];
if (database?.project?.organizationId) {
@@ -64,20 +61,16 @@ export const getDatabaseDataAction = userAction
activeOrganizationStorageChannels = organizationStorageChannels.filter(channel => channel.enabled);
}
return {
database,
backups,
restorations,
// @ts-ignore
activeOrganizationChannels,
// @ts-ignore
activeOrganizationStorageChannels,
stats: {
totalBackups,
availableBackups,
successRate
},
health: database ? await getHealthLast12hLogs({ id: database.id }) : []
}
};
});
@@ -37,6 +37,7 @@ import {backupOnly} from "@/components/wrappers/dashboard/projects/database/data
type ChannelPoliciesFormProps = {
onSuccess?: () => void;
channels: NotificationChannel[] | StorageChannel[];
organizationId: string;
database: DatabaseWith;
kind: ChannelKind
};
@@ -45,6 +46,7 @@ type ChannelPoliciesFormProps = {
export const ChannelPoliciesForm = ({
database,
channels,
organizationId,
onSuccess,
kind
}: ChannelPoliciesFormProps) => {
@@ -65,6 +65,7 @@ export const ChannelPoliciesModal = ({icon, kind, database, channels, organizati
</DialogDescription>
<Separator className="mt-3 mb-3"/>
<ChannelPoliciesForm
organizationId={organizationId}
channels={channels}
database={database}
onSuccess={() => setOpen(false)}
@@ -3,7 +3,7 @@ import {z} from "zod";
export const PolicySchema = z.object({
channelId: z.string().min(1, "Please select channel"),
eventKinds: z.array(z.enum([
'error_backup', 'error_restore', 'success_restore', 'success_backup', 'weekly_report', 'error_health_database'
'error_backup', 'error_restore', 'success_restore', 'success_backup', 'weekly_report'
]))
.optional(),
enabled: z.boolean().default(true),
@@ -17,16 +17,16 @@ export const PoliciesSchema = z.object({
export type PoliciesType = z.infer<typeof PoliciesSchema>;
export type PolicyType = z.infer<typeof PolicySchema>;
export const EVENT_KIND_BACKUP_ONLY_OPTIONS = [
{label: "Error Backup", value: "error_backup"},
{label: "Success Backup", value: "success_backup"},
{label: "Health Ping Fail", value: "error_health_database"},
];
export const EVENT_KIND_OPTIONS = [
...EVENT_KIND_BACKUP_ONLY_OPTIONS,
{label: "Error Backup", value: "error_backup"},
{label: "Error Restore", value: "error_restore"},
{label: "Success Restore", value: "success_restore"},
{label: "Success Backup", value: "success_backup"},
// {label: "Weekly Report", value: "weekly_report"},
];
export const EVENT_KIND_BACKUP_ONLY_OPTIONS = [
{label: "Error Backup", value: "error_backup"},
{label: "Success Backup", value: "success_backup"},
];
@@ -1,43 +0,0 @@
"use client"
import {useState} from "react";
import {Button} from "@/components/ui/button";
import {DatabaseWith} from "@/db/schema/07_database";
import {HeartPulse} from "lucide-react";
import {
Sheet,
SheetContent,
SheetTitle,
SheetTrigger
} from "@/components/ui/sheet";
import {HealthcheckLog} from "@/db/schema/15_healthcheck-log";
import {HealthCheckGraph} from "@/components/wrappers/dashboard/health/heath-grid";
type HealthModalProps = {
database: DatabaseWith,
healthLogs: HealthcheckLog[]
}
export const HealthModal = ({database, healthLogs}: HealthModalProps) => {
const [open, setOpen] = useState(false);
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant="outline" onClick={() => setOpen(true)}>
<HeartPulse/>
</Button>
</SheetTrigger>
<SheetContent side="bottom">
<div className="flex pl-5 pt-4">
<SheetTitle>
Database Health Status
</SheetTitle>
</div>
<div className="px-4 pb-5">
<HealthCheckGraph logs={healthLogs} />
</div>
</SheetContent>
</Sheet>
)
}
@@ -1,204 +0,0 @@
"use client"
import {useMemo} from "react"
import {Card} from "@/components/ui/card"
import {HealthcheckLog} from "@/db/schema/15_healthcheck-log"
import {useIsMobile} from "@/hooks/use-mobile";
type HealthStatus = "healthy" | "degraded" | "down" | "unknown"
interface HealthCheckData {
timestamp: Date
status: HealthStatus
}
interface Props {
logs: HealthcheckLog[]
}
const INTERVAL_MINUTES = 10
const WINDOW_HOURS = 12
function roundDateToInterval(date: Date, intervalMinutes: number): Date {
const ms = intervalMinutes * 60 * 1000
return new Date(Math.floor(date.getTime() / ms) * ms)
}
function buildTimeSeries(logs: HealthcheckLog[]): HealthCheckData[] {
const intervalMs = INTERVAL_MINUTES * 60 * 1000
const now = new Date()
const roundedNow = roundDateToInterval(now, INTERVAL_MINUTES)
const buckets = (WINDOW_HOURS * 60) / INTERVAL_MINUTES
const data: HealthCheckData[] = []
const oldestLog = logs.length > 0 ? getOldestLog(logs) : null
for (let i = buckets - 1; i >= 0; i--) {
const start = new Date(roundedNow.getTime() - i * intervalMs)
const end = new Date(start.getTime() + intervalMs)
const bucketLogs = logs.filter(
(l) =>
l.date &&
new Date(l.date) >= start &&
new Date(l.date) < end
)
let status: HealthStatus = "unknown"
if (!oldestLog || new Date(oldestLog.date!) > start) {
status = "unknown"
} else if (new Date(oldestLog.date!) < start) {
status = "down"
}
if (bucketLogs.length > 0) {
const hasFailure = bucketLogs.some((l) => l.status === "failed")
const hasSuccess = bucketLogs.some((l) => l.status === "success")
if (hasFailure && hasSuccess) {
status = "degraded"
} else if (hasFailure) {
status = "down"
} else if (hasSuccess) {
status = "healthy"
}
}
data.push({timestamp: start, status})
}
return data
}
function getStatusColor(status: HealthStatus): string {
switch (status) {
case "healthy":
return "bg-emerald-500"
case "degraded":
return "bg-emerald-700"
case "down":
return "bg-red-500"
case "unknown":
return "bg-zinc-700"
}
}
function getOldestLog(logs: HealthcheckLog[]): HealthcheckLog {
console.log(logs)
const validLogs = logs.filter(l => l.date)
return validLogs.reduce((oldest, current) =>
new Date(current.date!) < new Date(oldest.date!) ? current : oldest
)
}
function formatTime(date: Date): string {
return date.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
})
}
export const HealthCheckGraph = ({logs}: Props) => {
const data = useMemo(() => {
return buildTimeSeries(logs)
}, [logs])
const isMobile = useIsMobile()
const hourLabels = useMemo(() => {
if (data.length === 0) return []
return data
.map((item, index) => ({ item, index }))
.filter(({ item }) => {
const hours = item.timestamp.getHours()
const minutes = item.timestamp.getMinutes()
if (isMobile) {
return minutes === 0 && hours % 3 === 0
} else {
return minutes === 0
}
})
.map(({ item, index }) => ({
hour: formatTime(item.timestamp),
index,
}))
}, [data])
const healthyCount = data.filter((d) => d.status === "healthy").length
const uptimePercent =
data.length > 0
? ((healthyCount / data.length) * 100).toFixed(1)
: "0.0"
return (
<div className="flex items-center justify-center">
<div className="w-full">
<Card className="h-full flex flex-col p-4 border-border/50 bg-card gap-0">
<div className="flex items-center justify-between mb-4">
<div>
<h2 className="text-lg font-semibold">Health</h2>
<p className="text-zinc-500 text-sm">
Last 12 hours {INTERVAL_MINUTES} minute intervals
</p>
</div>
<div className="text-right">
<p className="text-emerald-400 text-2xl font-bold">
{uptimePercent}%
</p>
<p className="text-zinc-500 text-sm">Uptime</p>
</div>
</div>
<div className="relative mb-1 h-4 text-xs text-zinc-500">
{hourLabels.map((label, i) => {
const left = (label.index / (data.length - 1)) * 100
return (
<div
key={i}
className="absolute -translate-x-1/2 whitespace-nowrap"
style={{ left: `${left}%` }}
>
{label.hour}
</div>
)
})}
</div>
<div className="flex gap-0.5">
{data.map((item, index) => (
<div
key={index}
className={`flex-1 h-8 rounded-sm ${getStatusColor(item.status)} hover:ring-2 hover:ring-zinc-400 transition-all cursor-pointer`}
title={`${formatTime(item.timestamp)} - ${item.status}`}
/>
))}
</div>
<div className="flex items-center justify-end gap-4 mt-4 text-xs text-zinc-500">
<Legend color="bg-zinc-700" label="Unknown"/>
<Legend color="bg-red-500" label="Down"/>
<Legend color="bg-emerald-700" label="Degraded"/>
<Legend color="bg-emerald-500" label="Healthy"/>
</div>
</Card>
</div>
</div>
)
}
const Legend = ({color, label}: { color: string; label: string }) => (
<div className="flex items-center gap-1.5">
<div className={`w-3 h-3 rounded-sm ${color}`}/>
<span>{label}</span>
</div>
)
@@ -20,8 +20,6 @@ import { ChannelPoliciesModal } from "@/components/wrappers/dashboard/database/c
import { HardDrive, Megaphone } from "lucide-react";
import { ImportModal } from "@/components/wrappers/dashboard/database/import/import-modal";
import { BackupButton } from "@/components/wrappers/dashboard/backup/backup-button/backup-button";
import {HealthModal} from "@/components/wrappers/dashboard/database/health/health-modal";
import {HealthcheckLog} from "@/db/schema/15_healthcheck-log";
export type DatabaseContentProps = {
settings: Setting;
@@ -36,7 +34,6 @@ export type DatabaseContentProps = {
organizationId: string;
activeOrganizationChannels: any[];
activeOrganizationStorageChannels: any[];
databaseHealthLogs: HealthcheckLog[]
};
export const DatabaseContent = (props: DatabaseContentProps) => {
@@ -67,7 +64,6 @@ export const DatabaseContent = (props: DatabaseContentProps) => {
availableBackups: props.availableBackups,
successRate: props.successRate,
},
health: props.databaseHealthLogs
},
staleTime: 0,
gcTime: 0,
@@ -122,13 +118,10 @@ export const DatabaseContent = (props: DatabaseContentProps) => {
organizationId={props.organizationId}
/>
<ImportModal database={database} />
<HealthModal database={database} healthLogs={data?.health ?? []}/>
</div>
<div className="flex items-center gap-2">
<BackupButton
disable={isAlreadyBackup || !database.lastContact}
disable={isAlreadyBackup}
databaseId={database.id}
/>
</div>
+1 -3
View File
@@ -15,7 +15,6 @@ import * as notificationLog from "./schema/11_notification-log";
import * as storageChannel from "./schema/12_storage-channel";
import * as storagePolicy from "@/db/schema/13_storage-policy";
import * as backupStorage from "@/db/schema/14_storage-backup";
import * as healthcheckLog from "@/db/schema/15_healthcheck-log";
import {Pool} from "pg";
@@ -47,8 +46,7 @@ export const schemas = {
...notificationLog,
...storageChannel,
...storagePolicy,
...backupStorage,
...healthcheckLog
...backupStorage
};
export const db = drizzle({
-12
View File
@@ -1,12 +0,0 @@
CREATE TYPE "public"."healthcheck_status" AS ENUM('success', 'failed');--> statement-breakpoint
CREATE TYPE "public"."healthcheck_kind" AS ENUM('database', 'agent');--> statement-breakpoint
CREATE TABLE "healthcheck_log" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"kind" "healthcheck_kind" NOT NULL,
"date" timestamp,
"status" "healthcheck_status",
"object_id" uuid,
"updated_at" timestamp,
"created_at" timestamp DEFAULT now() NOT NULL,
"deleted_at" timestamp
);
@@ -1,3 +0,0 @@
ALTER TABLE "healthcheck_log" ALTER COLUMN "date" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "healthcheck_log" ALTER COLUMN "status" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "healthcheck_log" ALTER COLUMN "object_id" SET NOT NULL;
-2
View File
@@ -1,2 +0,0 @@
ALTER TABLE "settings" ADD COLUMN "default_notification_channel_id" uuid;--> statement-breakpoint
ALTER TABLE "settings" ADD CONSTRAINT "settings_default_notification_channel_id_notification_channel_id_fk" FOREIGN KEY ("default_notification_channel_id") REFERENCES "public"."notification_channel"("id") ON DELETE set null ON UPDATE no action;
-1
View File
@@ -1 +0,0 @@
ALTER TABLE "agents" ADD COLUMN "health_error_count" integer;
-1
View File
@@ -1 +0,0 @@
ALTER TYPE "public"."event_kind" ADD VALUE 'error_health_agent';
@@ -1 +0,0 @@
ALTER TYPE "public"."event_kind" ADD VALUE 'error_health_database';
@@ -1 +0,0 @@
ALTER TABLE "databases" ADD COLUMN "health_error_count" integer;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-49
View File
@@ -281,55 +281,6 @@
"when": 1773659096498,
"tag": "0039_conscious_solo",
"breakpoints": true
},
{
"idx": 40,
"version": "7",
"when": 1774375027038,
"tag": "0040_quick_lester",
"breakpoints": true
},
{
"idx": 41,
"version": "7",
"when": 1774378412843,
"tag": "0041_spooky_radioactive_man",
"breakpoints": true
},
{
"idx": 42,
"version": "7",
"when": 1774472168308,
"tag": "0042_breezy_namora",
"breakpoints": true
},
{
"idx": 43,
"version": "7",
"when": 1774643615673,
"tag": "0043_peaceful_chat",
"breakpoints": true
},
{
"idx": 44,
"version": "7",
"when": 1774648872657,
"tag": "0044_steep_wiccan",
"breakpoints": true
},
{
"idx": 45,
"version": "7",
"when": 1774696680244,
"tag": "0045_needy_martin_li",
"breakpoints": true
},
{
"idx": 46,
"version": "7",
"when": 1774706071024,
"tag": "0046_mysterious_menace",
"breakpoints": true
}
]
}
+2 -5
View File
@@ -1,10 +1,10 @@
import {boolean, pgTable, uuid, varchar} from "drizzle-orm/pg-core";
import {boolean, pgTable, timestamp, uuid, varchar} from "drizzle-orm/pg-core";
import {createSelectSchema} from "drizzle-zod";
import {z} from "zod";
import {timestamps} from "@/db/schema/00_common";
import {storageChannel} from "@/db/schema/12_storage-channel";
import {relations} from "drizzle-orm";
import {notificationChannel} from "@/db/schema/09_notification-channel";
export const setting = pgTable("settings", {
id: uuid("id").primaryKey().defaultRandom(),
@@ -15,8 +15,6 @@ export const setting = pgTable("settings", {
smtpPort: varchar("smtp_port", {length: 255}),
smtpUser: varchar("smtp_user", {length: 255}),
smtpSecure: boolean("smtp_secure"),
defaultNotificationChannelId: uuid('default_notification_channel_id')
.references(() => notificationChannel.id, {onDelete: "set null"}),
defaultStorageChannelId: uuid('default_storage_channel_id')
.references(() => storageChannel.id, {onDelete: "set null"}),
encryption: boolean("encryption").default(false),
@@ -25,7 +23,6 @@ export const setting = pgTable("settings", {
export const settingRelations = relations(setting, ({one, many}) => ({
storageChannel: one(storageChannel, {fields: [setting.defaultStorageChannelId], references: [storageChannel.id]}),
notificationChannel: one(notificationChannel, {fields: [setting.defaultNotificationChannelId], references: [notificationChannel.id]}),
}));
-1
View File
@@ -19,7 +19,6 @@ export const database = pgTable("databases", {
backupPolicy: text("backup_policy"),
isWaitingForBackup: boolean("is_waiting_for_backup").default(false).notNull(),
backupToRestore: text("backup_to_restore"),
healthErrorCount: integer("health_error_count"),
agentId: uuid("agent_id")
.notNull()
.references(() => agent.id, {onDelete: "cascade"}),
+1 -2
View File
@@ -1,4 +1,4 @@
import {boolean, pgTable, text, timestamp, uuid, integer} from "drizzle-orm/pg-core";
import {boolean, pgTable, text, timestamp, uuid} from "drizzle-orm/pg-core";
import {createSelectSchema} from "drizzle-zod";
import {z} from "zod";
import {Database, database} from "@/db/schema/07_database";
@@ -10,7 +10,6 @@ export const agent = pgTable("agents", {
slug: text("slug").notNull().unique(),
version: text("version"),
name: text("name").notNull().notNull(),
healthErrorCount: integer("health_error_count"),
description: text("description").notNull(),
isArchived: boolean("is_archived").default(false),
lastContact: timestamp("last_contact"),
+1 -1
View File
@@ -6,7 +6,7 @@ import {database} from "@/db/schema/07_database";
import {createSelectSchema} from "drizzle-zod";
import {z} from "zod";
export const eventKindEnum = pgEnum('event_kind', ['error_backup', 'error_restore', 'success_restore', 'success_backup', 'weekly_report', 'error_health_agent', 'error_health_database']);
export const eventKindEnum = pgEnum('event_kind', ['error_backup', 'error_restore', 'success_restore', 'success_backup', 'weekly_report']);
export const alertPolicy = pgTable('alert_policy', {
id: uuid('id').defaultRandom().primaryKey(),
-23
View File
@@ -1,23 +0,0 @@
import {pgTable, uuid, timestamp, pgEnum} from 'drizzle-orm/pg-core';
import {timestamps} from "@/db/schema/00_common";
import {createSelectSchema} from "drizzle-zod";
import {z} from "zod";
export const healthcheckKindEnum = pgEnum('healthcheck_kind', ['database', 'agent']);
export const healthCheckStatusEnum = pgEnum('healthcheck_status', ['success', 'failed']);
export const healthcheckLog = pgTable('healthcheck_log', {
id: uuid('id').defaultRandom().primaryKey(),
kind: healthcheckKindEnum('kind').notNull(),
date: timestamp("date").notNull(),
status: healthCheckStatusEnum("status").notNull(),
objectId: uuid('object_id').notNull(),
...timestamps
});
export const healthcheckLogSchema = createSelectSchema(healthcheckLog);
export type HealthcheckLog = z.infer<typeof healthcheckLogSchema>;
export type HealthcheckKind = (typeof healthcheckKindEnum.enumValues)[number];
export type HealthcheckStatus = (typeof healthCheckStatusEnum.enumValues)[number];
-187
View File
@@ -1,187 +0,0 @@
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {and, eq, gte, isNotNull, lt} from "drizzle-orm";
import {dispatchNotification} from "@/features/notifications/dispatch";
import {EventPayload} from "@/features/notifications/types";
export async function getHealthLast12hLogs({id}: { id: string }) {
const now = new Date()
const since = new Date(now.getTime() - 12 * 60 * 60 * 1000)
return db
.select()
.from(drizzleDb.schemas.healthcheckLog)
.where(
and(
eq(drizzleDb.schemas.healthcheckLog.objectId, id),
gte(drizzleDb.schemas.healthcheckLog.date, since)
)
)
}
export async function deleteHealthLogsOlderThan12h() {
const now = new Date()
const threshold = new Date(now.getTime() - 12 * 60 * 60 * 1000)
const logsToDelete = await db
.select()
.from(drizzleDb.schemas.healthcheckLog)
.where(
lt(drizzleDb.schemas.healthcheckLog.date, threshold)
)
console.log(`Number of logs found to delete: ${logsToDelete.length}`)
await db
.delete(drizzleDb.schemas.healthcheckLog)
.where(
lt(drizzleDb.schemas.healthcheckLog.date, threshold)
)
return logsToDelete.length
}
export async function checkAgentsHealthError() {
const agents = await db.query.agent.findMany({
where: isNotNull(drizzleDb.schemas.agent.lastContact),
});
const settings = await db.query.setting.findFirst({
where: (fields, {eq}) => eq(fields.name, "system"),
});
if (!settings) {
throw new Error("System settings not found");
}
if (!settings.defaultNotificationChannelId) {
console.error("No default notification channel id found.");
return
}
const now = new Date();
for (const agent of agents) {
if (!agent.lastContact) continue;
const lastContactDate = new Date(agent.lastContact);
const diffMinutes = (now.getTime() - lastContactDate.getTime()) / 1000 / 60;
if (diffMinutes > 10) {
if ((agent.healthErrorCount ?? 0) < 3) {
const newHealthErrorCount = (agent.healthErrorCount ?? 0) + 1
await db.update(drizzleDb.schemas.agent)
.set({
healthErrorCount: newHealthErrorCount,
})
.where(eq(drizzleDb.schemas.agent.id, agent.id));
const payload: EventPayload = {
title: "Agent down",
message: `Agent ${agent.name} is down, (notification number: ${newHealthErrorCount}/3)`,
level: "critical",
event: "error_health_agent",
data: {
agent: agent.name,
id: agent.id,
error: "Agent is down",
},
};
console.log("[Agent Healthcheck] :", payload);
await dispatchNotification(
payload,
undefined,
settings.defaultNotificationChannelId,
undefined
);
}
}
}
}
export async function checkDatabasesHealthError() {
const databases = await db.query.database.findMany({
where: isNotNull(drizzleDb.schemas.database.lastContact),
with: {
agent: true,
alertPolicies: true
}
})
const now = new Date();
for (const database of databases) {
if (!database.lastContact) continue;
const lastContactDate = new Date(database.lastContact);
const diffMinutes = (now.getTime() - lastContactDate.getTime()) / 1000 / 60;
if (diffMinutes > 10) {
if ((database.healthErrorCount ?? 0) < 3) {
const newHealthErrorCount = (database.healthErrorCount ?? 0) + 1
await db.update(drizzleDb.schemas.database)
.set({
healthErrorCount: newHealthErrorCount,
})
.where(eq(drizzleDb.schemas.database.id, database.id));
const settings = await db.query.setting.findFirst({
where: eq(drizzleDb.schemas.setting.name, "system"),
with: { notificationChannel: true },
});
const defaultPolicy = settings?.notificationChannel
? [{
id: null,
notificationChannelId: settings.notificationChannel.id,
enabled: settings.notificationChannel.enabled,
eventKinds: ["error_health_database"]
}]
: [];
const policiesToUse = (database.alertPolicies && database.alertPolicies.length > 0)
? database.alertPolicies.filter(policy => policy.enabled && policy.eventKinds.includes("error_health_database"))
: defaultPolicy;
if (!policiesToUse || policiesToUse.length === 0) {
continue
}
const promises = policiesToUse.map(alertPolicy => {
const payload: EventPayload = {
title: "Database down",
message: `Database ${database.name} is down, (notification number: ${newHealthErrorCount}/3)`,
level: "critical",
event: "error_health_database",
data: {
agent: database.name,
id: database.id,
error: "Database is down",
},
};
console.log("[Database Healthcheck] :", payload);
return dispatchNotification(payload, alertPolicy.id == null ? undefined : alertPolicy.id, alertPolicy.id ? undefined : alertPolicy.notificationChannelId, undefined);
});
await Promise.all(promises);
}
}
}
}
-15
View File
@@ -39,20 +39,6 @@ export const env = createEnv({
process.env.NODE_ENV === "production" ? "0 7 * * *" : "* * * * *",
),
CLEANING_HEALTHCHECK_LOGS_CRON: z
.string()
.default(
process.env.NODE_ENV === "production" ? "0 * * * *" : "* * * * *",
),
HEALTHCHECK_CRON: z
.string()
.default(
process.env.NODE_ENV === "production" ? "0 * * * *" : "* * * * *",
),
AUTH_OIDC_ID: z.string().optional().default("oidc"),
AUTH_OIDC_TITLE: z.string().optional(),
AUTH_OIDC_DESC: z.string().optional(),
@@ -109,7 +95,6 @@ export const env = createEnv({
SMTP_SECURE: process.env.SMTP_SECURE,
RETENTION_CRON: process.env.RETENTION_CRON,
CLEANING_HEALTHCHECK_LOGS_CRON: process.env.CLEANING_HEALTHCHECK_LOGS_CRON,
AUTH_OIDC_ID: process.env.AUTH_OIDC_ID,
AUTH_OIDC_TITLE: process.env.AUTH_OIDC_TITLE,
-4
View File
@@ -6,7 +6,6 @@ import {eq, and, ne, count} from "drizzle-orm";
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {slugify} from "@/utils/slugify";
import {getHealthLast12hLogs} from "@/db/services/healthcheck";
const verifySlugUniqueness = async (slug: string, agentId?: string) => {
const conditions = agentId ? and(eq(drizzleDb.schemas.agent.slug, slug), ne(drizzleDb.schemas.agent.id, agentId)) : eq(drizzleDb.schemas.agent.slug, slug);
@@ -55,10 +54,7 @@ export const getAgentAction = userAction.schema(z.string()).action(async ({parse
databases: true
}
});
return {
data: agent,
health: agent ? await getHealthLast12hLogs({ id: agent.id }) : []
};
});
+7 -26
View File
@@ -1,35 +1,17 @@
import { DatabaseWith } from "@/db/schema/07_database";
import { EventKind, EventPayload } from "@/features/notifications/types";
import { dispatchNotification } from "@/features/notifications/dispatch";
import {db} from "@/db";
import {eq} from "drizzle-orm";
import * as drizzleDb from "@/db";
export async function sendNotificationsBackupRestore(database: DatabaseWith, event: EventKind) {
const settings = await db.query.setting.findFirst({
where: eq(drizzleDb.schemas.setting.name, "system"),
with: { notificationChannel: true },
});
const defaultPolicy = settings?.notificationChannel
? [{
id: null,
notificationChannelId: settings.notificationChannel.id,
enabled: settings.notificationChannel.enabled,
eventKinds: ["error_backup" , "error_restore"]
}]
: [];
const policiesToUse = (database.alertPolicies && database.alertPolicies.length > 0)
? database.alertPolicies.filter(policy => policy.enabled && policy.eventKinds.includes(event))
: defaultPolicy;
if (!policiesToUse || policiesToUse.length === 0) {
if (!database.alertPolicies || database.alertPolicies.length === 0) {
return [];
}
const promises = policiesToUse.map(alertPolicy => {
const activePolicies = database.alertPolicies.filter(policy =>
policy.enabled && policy.eventKinds.includes(event)
);
const promises = activePolicies.map(alertPolicy => {
const date = new Date();
let level: "info" | "critical" = "info";
let message = "";
@@ -59,7 +41,6 @@ export async function sendNotificationsBackupRestore(database: DatabaseWith, eve
success_backup: `Backup Notification`,
success_restore: `Restore Notification`,
weekly_report: `Weekly Report Notification`,
error_health_agent: "Health Agent Notification",
};
const payload: EventPayload = {
@@ -75,7 +56,7 @@ export async function sendNotificationsBackupRestore(database: DatabaseWith, eve
},
};
return dispatchNotification(payload, alertPolicy.id == null ? undefined : alertPolicy.id, alertPolicy.id ? undefined : alertPolicy.notificationChannelId, undefined);
return dispatchNotification(payload, alertPolicy.id, undefined, undefined);
});
+1 -1
View File
@@ -18,4 +18,4 @@ export interface EventPayload {
data?: Record<string, any>;
}
export type EventKind = ("error_backup" | "error_restore" | "success_restore" | "success_backup" | "weekly_report" | "error_health_agent" | "error_health_database")
export type EventKind = ("error_backup" | "error_restore" | "success_restore" | "success_backup" | "weekly_report")
+1 -25
View File
@@ -2,11 +2,7 @@ import cron from "node-cron";
import {retentionCleanTask} from "@/lib/tasks/database";
import {env} from "@/env.mjs";
import {backupCleanTask} from "@/lib/tasks/cleaning";
import {
checkAgentsHealthError,
checkDatabasesHealthError,
deleteHealthLogsOlderThan12h
} from "@/db/services/healthcheck";
export const retentionJob = cron.schedule(env.RETENTION_CRON, async () => {
try {
@@ -24,24 +20,4 @@ export const cleaningJob = cron.schedule("* * * * *", async () => {
} catch (err) {
console.error(`[CRON] Error:`, err);
}
});
export const cleaningHealthcheckLogsJob = cron.schedule(env.CLEANING_HEALTHCHECK_LOGS_CRON, async () => {
try {
console.log("Cleaning Healthcheck Logs Job : Starting task");
await deleteHealthLogsOlderThan12h();
} catch (err) {
console.error(`[CRON] Error:`, err);
}
});
export const healthcheckAgentAndDatabaseJob = cron.schedule(env.HEALTHCHECK_CRON, async () => {
try {
console.log("Healthcheck Job : Starting task");
await checkAgentsHealthError();
await checkDatabasesHealthError()
} catch (err) {
console.error(`[CRON] Error:`, err);
}
});
+1 -14
View File
@@ -2,7 +2,7 @@ import { env } from "@/env.mjs";
import { db, makeMigration } from "@/db";
import { eq } from "drizzle-orm";
import * as drizzleDb from "@/db";
import {cleaningHealthcheckLogsJob, cleaningJob, healthcheckAgentAndDatabaseJob, retentionJob} from "@/lib/tasks";
import { cleaningJob, retentionJob } from "@/lib/tasks";
import { generateRSAKeys, getOrCreateMasterKey } from "@/utils/rsa-keys";
import { StorageProviderKind } from "@/features/storages/types";
@@ -17,8 +17,6 @@ export async function init() {
console.log("====Initialization completed====");
await setupCronJobs();
await setupCleaningJobs();
await setupCleaningHealthLogsJobs();
await setupHealthCheckJobs();
if (
(env.AUTH_GOOGLE_ID && env.AUTH_GOOGLE_SECRET) ||
@@ -42,17 +40,6 @@ async function setupCleaningJobs() {
console.log("==== Cleaning job started ====");
}
async function setupCleaningHealthLogsJobs() {
console.log("==== Setting up Cleaning Healthcheck Logs Jobs ====");
cleaningHealthcheckLogsJob.start();
console.log("==== Cleaning Healthcheck Logs job started ====");
}
async function setupHealthCheckJobs() {
console.log("==== Setting up Healthcheck Jobs ====");
healthcheckAgentAndDatabaseJob.start();
console.log("==== Cleaning Healthcheck job started ====");
}
async function createSettingsIfNotExist() {
await db.transaction(async (tx) => {
const systemSettingsValues = {