Merge pull request #5966 from homarr-labs/feat/beszel-fixes
fix(beszel): chart color mismatch, system selector UX, SSE infrastructure, and widget fixes
This commit is contained in:
39 files changed
+1051
-393
No files matched your search
@@ -0,0 +1,33 @@
|
|||||||
|
---
|
||||||
|
title: 'Gotify'
|
||||||
|
description: "Gotify is a simple, self-hosted server for sending and receiving messages in real time."
|
||||||
|
hide_title: true
|
||||||
|
---
|
||||||
|
|
||||||
|
import { notificationsWidget } from '@site/docs/widgets/notifications';
|
||||||
|
import { AddingIntegration } from '@site/src/components/integrations/adding';
|
||||||
|
import { IntegrationHeader } from '@site/src/components/integrations/header';
|
||||||
|
import { IntegrationSecrets } from '@site/src/components/integrations/secrets';
|
||||||
|
import { IntegrationCapabilites } from '@site/src/components/integrations/widgets';
|
||||||
|
import { gotifyIntegration } from '.';
|
||||||
|
|
||||||
|
<IntegrationHeader
|
||||||
|
integration={gotifyIntegration}
|
||||||
|
categories={['Notifications', 'Messaging']}
|
||||||
|
/>
|
||||||
|
|
||||||
|
### Widgets & Capabilities
|
||||||
|
<IntegrationCapabilites
|
||||||
|
items={[{
|
||||||
|
widget: notificationsWidget
|
||||||
|
}]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
### Adding the integration
|
||||||
|
<AddingIntegration />
|
||||||
|
|
||||||
|
### Secrets
|
||||||
|
<IntegrationSecrets secrets={[{
|
||||||
|
credentials: ['username', 'password'],
|
||||||
|
steps: []
|
||||||
|
}]} />
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { IntegrationDefinition } from "@site/src/types";
|
||||||
|
|
||||||
|
export const gotifyIntegration: IntegrationDefinition = {
|
||||||
|
name: "Gotify",
|
||||||
|
description: "Gotify is a simple, self-hosted server for sending and receiving messages in real time.",
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/gotify.svg",
|
||||||
|
path: "../../integrations/gotify",
|
||||||
|
};
|
||||||
@@ -130,6 +130,7 @@ Homarr exposes 50+ tools organized by namespace. Each tool is either a **query**
|
|||||||
| ------------------ | -------------------------------------------------------- | ---------- |
|
| ------------------ | -------------------------------------------------------- | ---------- |
|
||||||
| `app` | List all apps, get app by ID, create/update/delete app | GET + POST |
|
| `app` | List all apps, get app by ID, create/update/delete app | GET + POST |
|
||||||
| `apiKeys` | List API keys | GET |
|
| `apiKeys` | List API keys | GET |
|
||||||
|
| `beszel` | Systems status, alerts, historical system metrics | GET |
|
||||||
| `board` | List boards, get board by ID, create/update/delete board | GET + POST |
|
| `board` | List boards, get board by ID, create/update/delete board | GET + POST |
|
||||||
| `docker` | List containers, inspect container, start/stop/restart | GET + POST |
|
| `docker` | List containers, inspect container, start/stop/restart | GET + POST |
|
||||||
| `icon` | Search icons | GET |
|
| `icon` | Search icons | GET |
|
||||||
@@ -162,3 +163,4 @@ The tools table on the MCP tab is dynamically generated - it always reflects the
|
|||||||
- **"Create a new app pointing to my Grafana instance"** - AI creates an app with the correct icon and URL
|
- **"Create a new app pointing to my Grafana instance"** - AI creates an app with the correct icon and URL
|
||||||
- **"How many users are on my Homarr instance?"** - AI lists all users (admin only)
|
- **"How many users are on my Homarr instance?"** - AI lists all users (admin only)
|
||||||
- **"Toggle Pi-hole blocking for 5 minutes"** - AI interacts with DNS controls
|
- **"Toggle Pi-hole blocking for 5 minutes"** - AI interacts with DNS controls
|
||||||
|
- **"How are my servers doing?"** - AI fetches Beszel system stats including CPU, memory, disk, and alerts
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"label": "Tools",
|
|
||||||
"collapsed": true,
|
|
||||||
"position": 10
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
---
|
|
||||||
title: SQLite Backup & Restore
|
|
||||||
tags:
|
|
||||||
- Management
|
|
||||||
- Backup
|
|
||||||
- Restore
|
|
||||||
- SQLite
|
|
||||||
---
|
|
||||||
|
|
||||||
The SQLite Backup & Restore feature allows you to export and import your entire Homarr database as a portable ZIP file. This is useful for creating backups, migrating between instances, or recovering from failures.
|
|
||||||
|
|
||||||
:::info SQLite only
|
|
||||||
This feature is only available when using the SQLite database driver (`DB_DRIVER=better-sqlite3`). MySQL and PostgreSQL users should use their respective database backup tools.
|
|
||||||
:::
|
|
||||||
|
|
||||||
## Accessing Backup & Restore
|
|
||||||
|
|
||||||
Navigate to **Management → Tools → Backup** from the sidebar. This page is only visible when running with SQLite.
|
|
||||||
|
|
||||||
## Exporting a Backup
|
|
||||||
|
|
||||||
Click the **Export** button to download a ZIP archive containing:
|
|
||||||
|
|
||||||
- **`db.sqlite`** — A consistent snapshot of your database (created via `VACUUM INTO`)
|
|
||||||
- **`metadata.json`** — Contains:
|
|
||||||
- `homarrVersion` — The version of Homarr that created the backup
|
|
||||||
- `exportedAt` — Timestamp of the export
|
|
||||||
- `dbDialect` — The database dialect (`sqlite`)
|
|
||||||
- `encryptionKey` — Your `SECRET_ENCRYPTION_KEY` (needed to decrypt integration secrets)
|
|
||||||
|
|
||||||
:::caution
|
|
||||||
The exported ZIP contains your encryption key and database. Store it securely and do not share it publicly.
|
|
||||||
:::
|
|
||||||
|
|
||||||
A confirmation dialog will ask you to type **"I understand"** before the export proceeds.
|
|
||||||
|
|
||||||
## Importing a Backup
|
|
||||||
|
|
||||||
1. Click the **Import** button and upload a previously exported ZIP file
|
|
||||||
2. Homarr analyzes the backup **entirely in your browser** using WebAssembly (sql.js) — no data is sent to the server during preview
|
|
||||||
3. The preview shows:
|
|
||||||
- **Entity counts** — How many boards, apps, users, integrations, etc. are in the backup
|
|
||||||
- **Board names** — A list of all boards contained in the backup
|
|
||||||
- **Migration status** — If the backup is from an older version, Homarr shows each pending database migration as animated timeline steps
|
|
||||||
4. Review the preview and type **"I understand"** to confirm
|
|
||||||
5. Homarr applies any pending migrations, re-encrypts integration secrets if the `SECRET_ENCRYPTION_KEY` differs between instances, and replaces the live database
|
|
||||||
6. The server automatically restarts to pick up the new database
|
|
||||||
|
|
||||||
:::tip
|
|
||||||
The import process is **backward-compatible** with older backups that used a separate `encryption-key.txt` file instead of embedding the key in `metadata.json`.
|
|
||||||
:::
|
|
||||||
|
|
||||||
## Onboarding Integration
|
|
||||||
|
|
||||||
When setting up a fresh Homarr instance with SQLite, the onboarding wizard includes a **"Restore from SQLite backup"** option. This lets you upload a backup ZIP to bootstrap your new instance with data from a previous installation.
|
|
||||||
|
|
||||||
## Docker Restart Behavior
|
|
||||||
|
|
||||||
After a successful import, only the Next.js process restarts — nginx and Redis remain running. The `run.sh` script automatically restarts Next.js in a loop, so the application comes back online within seconds. Running `docker stop` still works gracefully.
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
|
|
||||||
- **Back up regularly** — Create exports before major updates or configuration changes
|
|
||||||
- **Test restores** — Periodically verify your backups by importing them on a test instance
|
|
||||||
- **Secure storage** — Keep backups in an encrypted or access-controlled location since they contain your encryption key
|
|
||||||
- **Check versions** — Backups from newer versions cannot be imported into older Homarr instances; always import into the same or newer version
|
|
||||||
@@ -8,12 +8,19 @@ export const beszelSystemStatsWidget: WidgetDefinition = {
|
|||||||
path: "../../widgets/beszel-system-stats",
|
path: "../../widgets/beszel-system-stats",
|
||||||
configuration: {
|
configuration: {
|
||||||
items: [
|
items: [
|
||||||
|
{
|
||||||
|
name: "System",
|
||||||
|
description: "The Beszel system to display stats for. Searchable select populated from the integration.",
|
||||||
|
values: { type: "string" },
|
||||||
|
defaultValue: "First available system",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "Time period",
|
name: "Time period",
|
||||||
description: "The time range for chart data",
|
description:
|
||||||
|
"The time range for chart data. '1 Minute' enables live streaming via PocketBase SSE (requires Beszel agent >= 0.13.0)",
|
||||||
values: {
|
values: {
|
||||||
type: "select",
|
type: "select",
|
||||||
options: ["1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
|
options: ["1 Minute", "1 Hour", "12 Hours", "24 Hours", "1 Week", "30 Days"],
|
||||||
},
|
},
|
||||||
defaultValue: "1 Hour",
|
defaultValue: "1 Hour",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import Tabs from '@theme/Tabs';
|
|||||||
import TabItem from '@theme/TabItem';
|
import TabItem from '@theme/TabItem';
|
||||||
import { notificationsWidget } from '.';
|
import { notificationsWidget } from '.';
|
||||||
import { ntfyIntegration } from '@site/docs/integrations/ntfy';
|
import { ntfyIntegration } from '@site/docs/integrations/ntfy';
|
||||||
import { nextcloudIntegration } from '@site/docs/integrations/nextcloud'
|
import { nextcloudIntegration } from '@site/docs/integrations/nextcloud';
|
||||||
|
import { gotifyIntegration } from '@site/docs/integrations/gotify';
|
||||||
|
|
||||||
<WidgetHeader
|
<WidgetHeader
|
||||||
widget={notificationsWidget}
|
widget={notificationsWidget}
|
||||||
@@ -33,7 +34,8 @@ import notificationsScreenshot from './img/notifications.png';
|
|||||||
<WidgetIntegrations
|
<WidgetIntegrations
|
||||||
items={[
|
items={[
|
||||||
{ integration: ntfyIntegration },
|
{ integration: ntfyIntegration },
|
||||||
{ integration: nextcloudIntegration }
|
{ integration: nextcloudIntegration },
|
||||||
|
{ integration: gotifyIntegration }
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -57,13 +57,13 @@ export const CustomWidgetList = ({ definitions }: CustomWidgetListProps) => {
|
|||||||
{definitions.map((def) => (
|
{definitions.map((def) => (
|
||||||
<Table.Tr key={def.id} style={{ opacity: def.enabled ? undefined : 0.5 }}>
|
<Table.Tr key={def.id} style={{ opacity: def.enabled ? undefined : 0.5 }}>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Group gap="xs">
|
<Group gap="xs" wrap="nowrap">
|
||||||
{def.iconUrl ? (
|
{def.iconUrl ? (
|
||||||
<Avatar size={20} radius="sm" src={def.iconUrl} styles={{ image: { objectFit: "contain" } }} />
|
<Avatar size={20} radius="sm" src={def.iconUrl} styles={{ image: { objectFit: "contain" } }} />
|
||||||
) : (
|
) : (
|
||||||
<IconApi size={16} />
|
<IconApi size={16} />
|
||||||
)}
|
)}
|
||||||
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"}>
|
<Text size="sm" fw={500} lineClamp={1} c={def.enabled ? undefined : "dimmed"} style={{ minWidth: 0 }}>
|
||||||
{def.name}
|
{def.name}
|
||||||
</Text>
|
</Text>
|
||||||
</Group>
|
</Group>
|
||||||
|
|||||||
@@ -1,17 +1,5 @@
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import {
|
import { Alert, Anchor, Center, Group, Stack, Table, TableTbody, TableTd, TableTr, Text, Title } from "@mantine/core";
|
||||||
Alert,
|
|
||||||
Anchor,
|
|
||||||
Center,
|
|
||||||
Group,
|
|
||||||
Stack,
|
|
||||||
Table,
|
|
||||||
TableTbody,
|
|
||||||
TableTd,
|
|
||||||
TableTr,
|
|
||||||
Text,
|
|
||||||
Title,
|
|
||||||
} from "@mantine/core";
|
|
||||||
import { IconExclamationCircle } from "@tabler/icons-react";
|
import { IconExclamationCircle } from "@tabler/icons-react";
|
||||||
|
|
||||||
import type { RouterOutputs } from "@homarr/api";
|
import type { RouterOutputs } from "@homarr/api";
|
||||||
@@ -53,14 +41,10 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
|
|||||||
const group = await api.group.getById({ id: params.id });
|
const group = await api.group.getById({ id: params.id });
|
||||||
const isReserved = group.name === everyoneGroup;
|
const isReserved = group.name === everyoneGroup;
|
||||||
|
|
||||||
const filteredMembers = searchParams.search
|
const searchTerm = searchParams.search?.trim().toLowerCase();
|
||||||
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
const filteredMembers = group.members.filter(
|
||||||
group.members.filter((member) =>
|
(member) => !searchTerm || member.name?.toLowerCase().includes(searchTerm),
|
||||||
member.name
|
);
|
||||||
?.toLowerCase()
|
|
||||||
.includes(searchParams.search!.trim().toLowerCase()),
|
|
||||||
)
|
|
||||||
: group.members;
|
|
||||||
|
|
||||||
// "local" = every enabled provider managed locally, "external" = none, "mixed" = some.
|
// "local" = every enabled provider managed locally, "external" = none, "mixed" = some.
|
||||||
const managementType = getGroupMemberManagementType();
|
const managementType = getGroupMemberManagementType();
|
||||||
@@ -75,21 +59,14 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
|
|||||||
<ReservedGroupAlert />
|
<ReservedGroupAlert />
|
||||||
) : (
|
) : (
|
||||||
managementType !== "local" && (
|
managementType !== "local" && (
|
||||||
<Alert
|
<Alert variant="light" color="yellow" icon={<IconExclamationCircle size="1rem" stroke={1.5} />}>
|
||||||
variant="light"
|
|
||||||
color="yellow"
|
|
||||||
icon={<IconExclamationCircle size="1rem" stroke={1.5} />}
|
|
||||||
>
|
|
||||||
{t(`group.memberNotice.${managementType}`)}
|
{t(`group.memberNotice.${managementType}`)}
|
||||||
</Alert>
|
</Alert>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<SearchInput
|
<SearchInput placeholder={`${tMembers("search")}...`} defaultValue={searchParams.search} />
|
||||||
placeholder={`${tMembers("search")}...`}
|
|
||||||
defaultValue={searchParams.search}
|
|
||||||
/>
|
|
||||||
{canManageMembers && !isReserved && (
|
{canManageMembers && !isReserved && (
|
||||||
<AddGroupMember
|
<AddGroupMember
|
||||||
groupId={group.id}
|
groupId={group.id}
|
||||||
@@ -108,12 +85,7 @@ export default async function GroupsDetailPage(props: GroupsDetailPageProps) {
|
|||||||
<Table striped highlightOnHover>
|
<Table striped highlightOnHover>
|
||||||
<TableTbody>
|
<TableTbody>
|
||||||
{filteredMembers.map((member) => (
|
{filteredMembers.map((member) => (
|
||||||
<Row
|
<Row key={group.id} member={member} groupId={group.id} disabled={isReserved} />
|
||||||
key={group.id}
|
|
||||||
member={member}
|
|
||||||
groupId={group.id}
|
|
||||||
disabled={isReserved}
|
|
||||||
/>
|
|
||||||
))}
|
))}
|
||||||
</TableTbody>
|
</TableTbody>
|
||||||
</Table>
|
</Table>
|
||||||
@@ -140,11 +112,7 @@ const Row = ({ member, groupId, disabled }: RowProps) => {
|
|||||||
</Anchor>
|
</Anchor>
|
||||||
</Group>
|
</Group>
|
||||||
</TableTd>
|
</TableTd>
|
||||||
<TableTd w={100}>
|
<TableTd w={100}>{canBeRemoved && !disabled && <RemoveGroupMember user={member} groupId={groupId} />}</TableTd>
|
||||||
{canBeRemoved && !disabled && (
|
|
||||||
<RemoveGroupMember user={member} groupId={groupId} />
|
|
||||||
)}
|
|
||||||
</TableTd>
|
|
||||||
</TableTr>
|
</TableTr>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -148,6 +148,8 @@ If \`hasUseAccess\` is false, the API key owner lacks permission for that integr
|
|||||||
|
|
||||||
**"Check server health"** → Use \`healthMonitoring_getSystemHealthStatus\` for NAS/server metrics or \`healthMonitoring_getClusterHealthStatus\` for Proxmox clusters.
|
**"Check server health"** → Use \`healthMonitoring_getSystemHealthStatus\` for NAS/server metrics or \`healthMonitoring_getClusterHealthStatus\` for Proxmox clusters.
|
||||||
|
|
||||||
|
**"Check Beszel systems"** → Call \`integration_all\` to get Beszel integrationIds, then use \`beszel_getSystems\` to list all monitored systems with CPU/memory/disk/network status. Use \`beszel_getAlerts\` for active alerts and history. Use \`beszel_getSystemStats\` for historical metrics of a specific system (requires systemId from \`beszel_getSystems\`).
|
||||||
|
|
||||||
**"Manage Docker containers"** → Use \`docker_getContainers\` to list containers with status/CPU/memory, then \`docker_startAll\`/\`docker_stopAll\`/\`docker_restartAll\` with container IDs.
|
**"Manage Docker containers"** → Use \`docker_getContainers\` to list containers with status/CPU/memory, then \`docker_startAll\`/\`docker_stopAll\`/\`docker_restartAll\` with container IDs.
|
||||||
|
|
||||||
**"Control smart home"** → Use \`smartHome_entityState\` to check a Home Assistant entity, \`smartHome_switchEntity\` to toggle it, or \`smartHome_executeAutomation\` to trigger an automation.
|
**"Control smart home"** → Use \`smartHome_entityState\` to check a Home Assistant entity, \`smartHome_switchEntity\` to toggle it, or \`smartHome_executeAutomation\` to trigger an automation.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { iconsRouter } from "./router/icons";
|
|||||||
import { infoRouter } from "./router/info";
|
import { infoRouter } from "./router/info";
|
||||||
import { integrationRouter } from "./router/integration/integration-router";
|
import { integrationRouter } from "./router/integration/integration-router";
|
||||||
import { inviteRouter } from "./router/invite";
|
import { inviteRouter } from "./router/invite";
|
||||||
|
import { beszelRouter } from "./router/widgets/beszel";
|
||||||
import { calendarRouter } from "./router/widgets/calendar";
|
import { calendarRouter } from "./router/widgets/calendar";
|
||||||
import { dnsHoleRouter } from "./router/widgets/dns-hole";
|
import { dnsHoleRouter } from "./router/widgets/dns-hole";
|
||||||
import { downloadsRouter } from "./router/widgets/downloads";
|
import { downloadsRouter } from "./router/widgets/downloads";
|
||||||
@@ -26,6 +27,7 @@ export const mcpRouter = createTRPCRouter({
|
|||||||
info: infoRouter,
|
info: infoRouter,
|
||||||
integration: integrationRouter,
|
integration: integrationRouter,
|
||||||
invite: inviteRouter,
|
invite: inviteRouter,
|
||||||
|
beszel: beszelRouter,
|
||||||
calendar: calendarRouter,
|
calendar: calendarRouter,
|
||||||
dnsHole: dnsHoleRouter,
|
dnsHole: dnsHoleRouter,
|
||||||
downloads: downloadsRouter,
|
downloads: downloadsRouter,
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
import { observable } from "@trpc/server/observable";
|
import { observable } from "@trpc/server/observable";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||||
import {
|
import {
|
||||||
beszelAlertsRequestHandler,
|
beszelAlertsRequestHandler,
|
||||||
beszelStatsRequestHandler,
|
beszelStatsRequestHandler,
|
||||||
@@ -13,12 +16,21 @@ import { createTRPCRouter, publicProcedure } from "../../trpc";
|
|||||||
|
|
||||||
export const beszelRouter = createTRPCRouter({
|
export const beszelRouter = createTRPCRouter({
|
||||||
getSystems: publicProcedure
|
getSystems: publicProcedure
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get all Beszel-monitored systems with CPU, memory, disk, GPU, network, temperature, and status. REQUIRED: integrationIds (array of Beszel integration IDs from integration_all)",
|
||||||
|
},
|
||||||
|
})
|
||||||
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
||||||
.query(async ({ ctx }) => {
|
.query(async ({ ctx }) => {
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
ctx.integrations.map(async (integration) => {
|
ctx.integrations.map(async (integration) => {
|
||||||
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
|
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
|
||||||
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({
|
||||||
|
forceUpdate: false,
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
integrationId: integration.id,
|
integrationId: integration.id,
|
||||||
integrationName: integration.name,
|
integrationName: integration.name,
|
||||||
@@ -34,7 +46,11 @@ export const beszelRouter = createTRPCRouter({
|
|||||||
subscribeSystems: publicProcedure
|
subscribeSystems: publicProcedure
|
||||||
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
||||||
.subscription(({ ctx }) => {
|
.subscription(({ ctx }) => {
|
||||||
return observable<{ integrationId: string; systems: BeszelSystemRow[]; timestamp: Date }>((emit) => {
|
return observable<{
|
||||||
|
integrationId: string;
|
||||||
|
systems: BeszelSystemRow[];
|
||||||
|
timestamp: Date;
|
||||||
|
}>((emit) => {
|
||||||
const unsubscribes = ctx.integrations.map((integration) => {
|
const unsubscribes = ctx.integrations.map((integration) => {
|
||||||
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
|
const innerHandler = beszelSystemsRequestHandler.handler(integration, {});
|
||||||
return innerHandler.subscribe((systems) => {
|
return innerHandler.subscribe((systems) => {
|
||||||
@@ -52,6 +68,13 @@ export const beszelRouter = createTRPCRouter({
|
|||||||
}),
|
}),
|
||||||
|
|
||||||
getAlerts: publicProcedure
|
getAlerts: publicProcedure
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get Beszel alerts and optional alert history for all monitored systems. REQUIRED: integrationIds (array of Beszel integration IDs from integration_all). OPTIONAL: includeHistory (default true), maxHistoryItems (default 10)",
|
||||||
|
},
|
||||||
|
})
|
||||||
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -96,14 +119,22 @@ export const beszelRouter = createTRPCRouter({
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.subscription(({ ctx, input }) => {
|
.subscription(({ ctx, input }) => {
|
||||||
return observable<{ integrationId: string; alerts: BeszelAlertsData; timestamp: Date }>((emit) => {
|
return observable<{
|
||||||
|
integrationId: string;
|
||||||
|
alerts: BeszelAlertsData;
|
||||||
|
timestamp: Date;
|
||||||
|
}>((emit) => {
|
||||||
const unsubscribes = ctx.integrations.map((integration) => {
|
const unsubscribes = ctx.integrations.map((integration) => {
|
||||||
const innerHandler = beszelAlertsRequestHandler.handler(integration, {
|
const innerHandler = beszelAlertsRequestHandler.handler(integration, {
|
||||||
includeHistory: input.includeHistory,
|
includeHistory: input.includeHistory,
|
||||||
maxHistoryItems: input.maxHistoryItems,
|
maxHistoryItems: input.maxHistoryItems,
|
||||||
});
|
});
|
||||||
return innerHandler.subscribe((data) => {
|
return innerHandler.subscribe((data) => {
|
||||||
emit.next({ integrationId: integration.id, alerts: data, timestamp: new Date() });
|
emit.next({
|
||||||
|
integrationId: integration.id,
|
||||||
|
alerts: data,
|
||||||
|
timestamp: new Date(),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
@@ -113,17 +144,26 @@ export const beszelRouter = createTRPCRouter({
|
|||||||
}),
|
}),
|
||||||
|
|
||||||
getSystemStats: publicProcedure
|
getSystemStats: publicProcedure
|
||||||
|
.meta({
|
||||||
|
mcp: {
|
||||||
|
enabled: true,
|
||||||
|
description:
|
||||||
|
"Get historical Beszel system metrics (CPU, memory, disk, network, temperature) and optional Docker container stats. REQUIRED: integrationIds (pass the single integrationId from the beszel_getSystems entry containing the target system — only the first ID is used), systemId (from beszel_getSystems). OPTIONAL: timePeriod (1m/1h/12h/24h/1w/30d, default 1h), includeDocker (default true)",
|
||||||
|
},
|
||||||
|
})
|
||||||
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
||||||
.input(
|
.input(
|
||||||
z.object({
|
z.object({
|
||||||
systemId: z.string(),
|
systemId: z.string(),
|
||||||
timePeriod: z.enum(["1h", "12h", "24h", "1w", "30d"]),
|
timePeriod: z.enum(["1m", "1h", "12h", "24h", "1w", "30d"]).default("1h"),
|
||||||
includeDocker: z.boolean().default(true),
|
includeDocker: z.boolean().default(true),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const integration = ctx.integrations[0];
|
const integration = ctx.integrations[0];
|
||||||
if (!integration) return null;
|
if (!integration) {
|
||||||
|
throw new TRPCError({ code: "BAD_REQUEST", message: "At least one Beszel integrationId is required" });
|
||||||
|
}
|
||||||
const innerHandler = beszelStatsRequestHandler.handler(integration, {
|
const innerHandler = beszelStatsRequestHandler.handler(integration, {
|
||||||
systemId: input.systemId,
|
systemId: input.systemId,
|
||||||
timePeriod: input.timePeriod,
|
timePeriod: input.timePeriod,
|
||||||
@@ -132,4 +172,45 @@ export const beszelRouter = createTRPCRouter({
|
|||||||
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
||||||
return { integrationId: integration.id, ...data, updatedAt: timestamp };
|
return { integrationId: integration.id, ...data, updatedAt: timestamp };
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
subscribeSystemStats: publicProcedure
|
||||||
|
.concat(createManyIntegrationMiddleware("query", "beszel", "mock"))
|
||||||
|
.input(
|
||||||
|
z.object({
|
||||||
|
systemId: z.string(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.subscription(({ ctx, input }) => {
|
||||||
|
return observable<{
|
||||||
|
stats: BeszelSystemStatsRecord;
|
||||||
|
containerStats: BeszelContainerStatsRecord | null;
|
||||||
|
}>((emit) => {
|
||||||
|
const integration = ctx.integrations[0];
|
||||||
|
if (!integration) {
|
||||||
|
emit.error(new Error("No Beszel integration configured"));
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const abortController = new AbortController();
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const instance = await createIntegrationAsync(integration);
|
||||||
|
await instance.subscribeRealtimeMetrics(input.systemId, (data) => emit.next(data), abortController.signal);
|
||||||
|
} catch (error) {
|
||||||
|
if (!abortController.signal.aborted) {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
emit.error(error);
|
||||||
|
} else {
|
||||||
|
emit.error(new Error(String(error)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
abortController.abort();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
@@ -323,6 +323,7 @@ export type HomarrDocumentationPath =
|
|||||||
| "/docs/integrations/github-containerregistry"
|
| "/docs/integrations/github-containerregistry"
|
||||||
| "/docs/integrations/quay"
|
| "/docs/integrations/quay"
|
||||||
| "/docs/integrations/ntfy"
|
| "/docs/integrations/ntfy"
|
||||||
|
| "/docs/integrations/gotify"
|
||||||
| "/docs/integrations/ical"
|
| "/docs/integrations/ical"
|
||||||
| "/docs/integrations/anchor"
|
| "/docs/integrations/anchor"
|
||||||
| "/docs/integrations/truenas"
|
| "/docs/integrations/truenas"
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
|
|||||||
gitHubContainerRegistry: "github-containerregistry",
|
gitHubContainerRegistry: "github-containerregistry",
|
||||||
quay: "quay",
|
quay: "quay",
|
||||||
ntfy: "ntfy",
|
ntfy: "ntfy",
|
||||||
|
gotify: "gotify",
|
||||||
ical: "ical",
|
ical: "ical",
|
||||||
anchor: "anchor",
|
anchor: "anchor",
|
||||||
truenas: "truenas",
|
truenas: "truenas",
|
||||||
@@ -56,5 +57,6 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
|
|||||||
umami: "umami",
|
umami: "umami",
|
||||||
peaNut: "peanut",
|
peaNut: "peanut",
|
||||||
beszel: "beszel",
|
beszel: "beszel",
|
||||||
|
archiveTeamWarrior: null,
|
||||||
mock: null,
|
mock: null,
|
||||||
};
|
};
|
||||||
@@ -44,6 +44,7 @@ export const widgetDocSlugs: Record<WidgetKind, string | null> = {
|
|||||||
audioStats: "audio-stats",
|
audioStats: "audio-stats",
|
||||||
umami: "umami",
|
umami: "umami",
|
||||||
ups: "ups",
|
ups: "ups",
|
||||||
|
archiveTeamWarrior: null,
|
||||||
beszelSystemTable: "beszel-system-table",
|
beszelSystemTable: "beszel-system-table",
|
||||||
beszelSystemGrid: "beszel-system-grid",
|
beszelSystemGrid: "beszel-system-grid",
|
||||||
beszelAlerts: "beszel-alerts",
|
beszelAlerts: "beszel-alerts",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ResponseError } from "@homarr/common/server";
|
import { ResponseError } from "@homarr/common/server";
|
||||||
|
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||||
|
|
||||||
import type { IntegrationInput, IntegrationTestingInput } from "../base/integration";
|
import type { IntegrationInput, IntegrationTestingInput } from "../base/integration";
|
||||||
@@ -12,17 +13,21 @@ import type {
|
|||||||
BeszelAlertHistory,
|
BeszelAlertHistory,
|
||||||
BeszelAuthResponse,
|
BeszelAuthResponse,
|
||||||
BeszelContainer,
|
BeszelContainer,
|
||||||
|
BeszelContainerStats,
|
||||||
BeszelContainerStatsRecord,
|
BeszelContainerStatsRecord,
|
||||||
BeszelSmartDevice,
|
BeszelSmartDevice,
|
||||||
BeszelSystem,
|
BeszelSystem,
|
||||||
BeszelSystemDetails,
|
BeszelSystemDetails,
|
||||||
BeszelSystemdService,
|
BeszelSystemdService,
|
||||||
|
BeszelSystemStats,
|
||||||
BeszelSystemStatsRecord,
|
BeszelSystemStatsRecord,
|
||||||
CreateAlertInput,
|
CreateAlertInput,
|
||||||
PocketBaseListResponse,
|
PocketBaseListResponse,
|
||||||
UpdateAlertInput,
|
UpdateAlertInput,
|
||||||
} from "./beszel-types";
|
} from "./beszel-types";
|
||||||
|
|
||||||
|
const logger = createLogger({ module: "beszel-integration" });
|
||||||
|
|
||||||
const escapeFilterValue = (value: string) => value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
const escapeFilterValue = (value: string) => value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
||||||
|
|
||||||
interface BeszelSession {
|
interface BeszelSession {
|
||||||
@@ -245,6 +250,100 @@ export class BeszelIntegration extends Integration {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async subscribeRealtimeMetrics(
|
||||||
|
systemId: string,
|
||||||
|
onMessage: (data: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null }) => void,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<void> {
|
||||||
|
const session = await this.authenticateAsync();
|
||||||
|
const sseUrl = this.url("/api/realtime");
|
||||||
|
|
||||||
|
const sseResponse = await fetchWithTrustedCertificatesAsync(sseUrl, {
|
||||||
|
headers: { Authorization: session.token },
|
||||||
|
signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sseResponse.ok || !sseResponse.body) {
|
||||||
|
throw new ResponseError(sseResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = sseResponse.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = "";
|
||||||
|
let clientId: string | null = null;
|
||||||
|
|
||||||
|
const processLine = (line: string) => {
|
||||||
|
if (!line.startsWith("data:")) return;
|
||||||
|
const jsonStr = line.slice(5).trim();
|
||||||
|
if (!jsonStr) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(jsonStr) as Record<string, unknown>;
|
||||||
|
|
||||||
|
if (!clientId && typeof parsed.clientId === "string") {
|
||||||
|
clientId = parsed.clientId;
|
||||||
|
this.subscribeTopic(clientId, systemId, session.token).catch((err) => {
|
||||||
|
logger.warn("Failed to subscribe to rt_metrics topic, aborting SSE", { error: err });
|
||||||
|
reader.cancel().catch(() => {});
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("stats" in parsed) {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const envelope = { id: "", system: systemId, type: "1m" as const, created: now, updated: now };
|
||||||
|
const stats: BeszelSystemStatsRecord = { ...envelope, stats: parsed.stats as BeszelSystemStats };
|
||||||
|
|
||||||
|
let containerStats: BeszelContainerStatsRecord | null = null;
|
||||||
|
const hasContainers =
|
||||||
|
parsed.container &&
|
||||||
|
Array.isArray(parsed.container) &&
|
||||||
|
(parsed.container as BeszelContainerStats[]).length > 0;
|
||||||
|
if (hasContainers) {
|
||||||
|
containerStats = { ...envelope, stats: parsed.container as BeszelContainerStats[] };
|
||||||
|
}
|
||||||
|
onMessage({ stats, containerStats });
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
logger.debug("Failed to parse SSE message", { line });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (!signal.aborted) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
const lines = buffer.split("\n");
|
||||||
|
buffer = lines.pop() ?? "";
|
||||||
|
for (const line of lines) {
|
||||||
|
processLine(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!signal.aborted) {
|
||||||
|
throw new Error("Beszel SSE stream ended unexpectedly");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.cancel().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async subscribeTopic(clientId: string, systemId: string, token: string): Promise<void> {
|
||||||
|
const topic = `rt_metrics?options=${JSON.stringify({ query: { system: systemId } })}`;
|
||||||
|
const response = await fetchWithTrustedCertificatesAsync(this.url("/api/realtime"), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: token,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ clientId, subscriptions: [topic] }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ResponseError(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
||||||
const response = await input.fetchAsync(this.url("/api/collections/users/auth-with-password"), {
|
const response = await input.fetchAsync(this.url("/api/collections/users/auth-with-password"), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -330,6 +330,40 @@ export class BeszelMockService {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async subscribeRealtimeMetrics(
|
||||||
|
systemId: string,
|
||||||
|
onMessage: (data: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null }) => void,
|
||||||
|
signal: AbortSignal,
|
||||||
|
): Promise<void> {
|
||||||
|
const sys = resolveSystem(systemId);
|
||||||
|
const emit = () => {
|
||||||
|
if (signal.aborted) return;
|
||||||
|
const [stats] = generateSystemStatsSeries(1, sys);
|
||||||
|
if (!stats) return;
|
||||||
|
const record: BeszelSystemStatsRecord = {
|
||||||
|
id: `mock-rt-${Date.now()}`,
|
||||||
|
system: systemId,
|
||||||
|
stats,
|
||||||
|
type: "1m",
|
||||||
|
created: new Date().toISOString(),
|
||||||
|
updated: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
onMessage({ stats: record, containerStats: null });
|
||||||
|
};
|
||||||
|
if (signal.aborted) return;
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const interval = setInterval(emit, 1000);
|
||||||
|
signal.addEventListener(
|
||||||
|
"abort",
|
||||||
|
() => {
|
||||||
|
clearInterval(interval);
|
||||||
|
resolve();
|
||||||
|
},
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public async getAlertHistoryAsync(_systemId?: string, perPage = 10): Promise<BeszelAlertHistory[]> {
|
public async getAlertHistoryAsync(_systemId?: string, perPage = 10): Promise<BeszelAlertHistory[]> {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const names = ["CPU", "Memory", "Disk", "Temperature", "Bandwidth"];
|
const names = ["CPU", "Memory", "Disk", "Temperature", "Bandwidth"];
|
||||||
@@ -341,7 +375,7 @@ export class BeszelMockService {
|
|||||||
name: names[i % names.length] ?? "CPU",
|
name: names[i % names.length] ?? "CPU",
|
||||||
val: rand(60, 95),
|
val: rand(60, 95),
|
||||||
created: new Date(now - (i + 1) * 3_600_000).toISOString(),
|
created: new Date(now - (i + 1) * 3_600_000).toISOString(),
|
||||||
resolved: i % 2 === 0 ? new Date(now - i * 1_800_000).toISOString() : null,
|
resolved: (i % 2 === 0 && new Date(now - i * 1_800_000).toISOString()) || null,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,4 +140,5 @@ export class MockIntegration
|
|||||||
getContainerStatsAsync = MockIntegration.beszel.getContainerStatsAsync.bind(MockIntegration.beszel);
|
getContainerStatsAsync = MockIntegration.beszel.getContainerStatsAsync.bind(MockIntegration.beszel);
|
||||||
getAlertsAsync = MockIntegration.beszel.getAlertsAsync.bind(MockIntegration.beszel);
|
getAlertsAsync = MockIntegration.beszel.getAlertsAsync.bind(MockIntegration.beszel);
|
||||||
getAlertHistoryAsync = MockIntegration.beszel.getAlertHistoryAsync.bind(MockIntegration.beszel);
|
getAlertHistoryAsync = MockIntegration.beszel.getAlertHistoryAsync.bind(MockIntegration.beszel);
|
||||||
|
subscribeRealtimeMetrics = MockIntegration.beszel.subscribeRealtimeMetrics.bind(MockIntegration.beszel);
|
||||||
}
|
}
|
||||||
@@ -90,12 +90,13 @@ export const beszelAlertsRequestHandler = createCachedIntegrationRequestHandler<
|
|||||||
queryKey: "beszelAlerts",
|
queryKey: "beszelAlerts",
|
||||||
});
|
});
|
||||||
|
|
||||||
const timePeriodConfig: Record<string, { type: string; perPage: number }> = {
|
const timePeriodConfig: Record<string, { type: string; perPage: number; cacheSeconds: number }> = {
|
||||||
"1h": { type: "1m", perPage: 60 },
|
"1m": { type: "1m", perPage: 60, cacheSeconds: 5 },
|
||||||
"12h": { type: "10m", perPage: 72 },
|
"1h": { type: "1m", perPage: 60, cacheSeconds: 60 },
|
||||||
"24h": { type: "20m", perPage: 72 },
|
"12h": { type: "10m", perPage: 72, cacheSeconds: 300 },
|
||||||
"1w": { type: "120m", perPage: 84 },
|
"24h": { type: "20m", perPage: 72, cacheSeconds: 600 },
|
||||||
"30d": { type: "480m", perPage: 90 },
|
"1w": { type: "120m", perPage: 84, cacheSeconds: 1800 },
|
||||||
|
"30d": { type: "480m", perPage: 90, cacheSeconds: 3600 },
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface BeszelStatsData {
|
export interface BeszelStatsData {
|
||||||
@@ -109,7 +110,7 @@ export const beszelStatsRequestHandler = createCachedIntegrationRequestHandler<
|
|||||||
{ systemId: string; timePeriod: string; includeDocker: boolean }
|
{ systemId: string; timePeriod: string; includeDocker: boolean }
|
||||||
>({
|
>({
|
||||||
async requestAsync(integration, input) {
|
async requestAsync(integration, input) {
|
||||||
const config = timePeriodConfig[input.timePeriod] ?? { type: "1m", perPage: 60 };
|
const config = timePeriodConfig[input.timePeriod] ?? { type: "1m", perPage: 60, cacheSeconds: 60 };
|
||||||
const instance = await createIntegrationAsync(integration);
|
const instance = await createIntegrationAsync(integration);
|
||||||
const systemStats = await instance.getSystemStatsAsync(input.systemId, config.type, config.perPage);
|
const systemStats = await instance.getSystemStatsAsync(input.systemId, config.type, config.perPage);
|
||||||
const containerStats = input.includeDocker
|
const containerStats = input.includeDocker
|
||||||
@@ -117,6 +118,11 @@ export const beszelStatsRequestHandler = createCachedIntegrationRequestHandler<
|
|||||||
: [];
|
: [];
|
||||||
return { systemStats, containerStats };
|
return { systemStats, containerStats };
|
||||||
},
|
},
|
||||||
cacheDuration: dayjs.duration(30, "seconds"),
|
cacheDuration: dayjs.duration(60, "seconds"),
|
||||||
queryKey: "beszelStats",
|
queryKey: "beszelStats",
|
||||||
|
cacheDurationForInput(input) {
|
||||||
|
const config = timePeriodConfig[input.timePeriod];
|
||||||
|
if (!config) return undefined;
|
||||||
|
return dayjs.duration(config.cacheSeconds, "seconds");
|
||||||
|
},
|
||||||
});
|
});
|
||||||
@@ -14,10 +14,10 @@ type IntegrationOfKind<TKind extends IntegrationKind> = Omit<Integration, "kind"
|
|||||||
};
|
};
|
||||||
|
|
||||||
interface Options<TData, TKind extends IntegrationKind, TInput extends Record<string, unknown>> {
|
interface Options<TData, TKind extends IntegrationKind, TInput extends Record<string, unknown>> {
|
||||||
// Unique key for this request handler
|
|
||||||
queryKey: string;
|
queryKey: string;
|
||||||
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
||||||
cacheDuration: Duration;
|
cacheDuration: Duration;
|
||||||
|
cacheDurationForInput?: (input: TInput) => Duration | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createCachedIntegrationRequestHandler = <
|
export const createCachedIntegrationRequestHandler = <
|
||||||
@@ -34,9 +34,9 @@ export const createCachedIntegrationRequestHandler = <
|
|||||||
requestAsync: async (input: { options: TInput; integration: IntegrationOfKind<TKind> }) => {
|
requestAsync: async (input: { options: TInput; integration: IntegrationOfKind<TKind> }) => {
|
||||||
return await options.requestAsync(input.integration, input.options);
|
return await options.requestAsync(input.integration, input.options);
|
||||||
},
|
},
|
||||||
cacheDuration: options.cacheDuration,
|
cacheDuration: options.cacheDurationForInput?.(itemOptions) ?? options.cacheDuration,
|
||||||
createRedisChannel(input, options) {
|
createRedisChannel(input, handlerOptions) {
|
||||||
return createIntegrationOptionsChannel<TData>(input.integration.id, options.queryKey, input.options);
|
return createIntegrationOptionsChannel<TData>(input.integration.id, handlerOptions.queryKey, input.options);
|
||||||
},
|
},
|
||||||
}).handler({ options: itemOptions, integration }),
|
}).handler({ options: itemOptions, integration }),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1652,6 +1652,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"widget": {
|
"widget": {
|
||||||
|
"integrationSelect": {
|
||||||
|
"configureIntegrationFirst": "Connect an integration first",
|
||||||
|
"loading": "Loading...",
|
||||||
|
"placeholder": "Select an option",
|
||||||
|
"noResults": "No results found",
|
||||||
|
"loadError": "Failed to load options"
|
||||||
|
},
|
||||||
"app": {
|
"app": {
|
||||||
"name": "App",
|
"name": "App",
|
||||||
"description": "Embeds an app into the board.",
|
"description": "Embeds an app into the board.",
|
||||||
@@ -3570,6 +3577,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"noRecords": "No systems found",
|
"noRecords": "No systems found",
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
|
||||||
|
},
|
||||||
"column": {
|
"column": {
|
||||||
"system": "System",
|
"system": "System",
|
||||||
"cpu": "CPU",
|
"cpu": "CPU",
|
||||||
@@ -3626,6 +3636,9 @@
|
|||||||
"label": "Show agent version"
|
"label": "Show agent version"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
|
||||||
|
},
|
||||||
"metric": {
|
"metric": {
|
||||||
"cpu": "CPU",
|
"cpu": "CPU",
|
||||||
"memory": "Memory",
|
"memory": "Memory",
|
||||||
@@ -3652,6 +3665,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"empty": "No alerts configured",
|
"empty": "No alerts configured",
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Unable to connect to Beszel. Check your integration settings."
|
||||||
|
},
|
||||||
"history": "History",
|
"history": "History",
|
||||||
"resolved": "Resolved",
|
"resolved": "Resolved",
|
||||||
"status": {
|
"status": {
|
||||||
@@ -3663,6 +3679,10 @@
|
|||||||
"name": "Beszel System Stats",
|
"name": "Beszel System Stats",
|
||||||
"description": "Time-series charts for CPU, memory, disk, network, and Docker container metrics",
|
"description": "Time-series charts for CPU, memory, disk, network, and Docker container metrics",
|
||||||
"option": {
|
"option": {
|
||||||
|
"systemId": {
|
||||||
|
"label": "System",
|
||||||
|
"description": "Select a Beszel system to display stats for"
|
||||||
|
},
|
||||||
"timePeriod": {
|
"timePeriod": {
|
||||||
"label": "Time period"
|
"label": "Time period"
|
||||||
},
|
},
|
||||||
@@ -3692,6 +3712,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"selectSystem": "Select system",
|
"selectSystem": "Select system",
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Unable to connect to Beszel. Check your integration settings.",
|
||||||
|
"liveConnectionFailed": "Live connection failed. Your Beszel instance may not support real-time streaming.",
|
||||||
|
"switchToHistorical": "Switch to historical view",
|
||||||
|
"systemNotFound": "Selected system was not found. Choose a different system."
|
||||||
|
},
|
||||||
"chart": {
|
"chart": {
|
||||||
"cpu": {
|
"cpu": {
|
||||||
"title": "CPU Usage",
|
"title": "CPU Usage",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { WidgetTextInput } from "./widget-text-input";
|
|||||||
import { WidgetUmamiEventInput } from "./widget-umami-event-input";
|
import { WidgetUmamiEventInput } from "./widget-umami-event-input";
|
||||||
import { WidgetUmamiEventNamesInput } from "./widget-umami-event-names-input";
|
import { WidgetUmamiEventNamesInput } from "./widget-umami-event-names-input";
|
||||||
import { WidgetUmamiWebsiteInput } from "./widget-umami-website-input";
|
import { WidgetUmamiWebsiteInput } from "./widget-umami-website-input";
|
||||||
|
import { WidgetIntegrationSelectInput } from "./widget-integration-select-input";
|
||||||
|
|
||||||
const mapping = {
|
const mapping = {
|
||||||
anchorNote: WidgetAnchorNoteInput,
|
anchorNote: WidgetAnchorNoteInput,
|
||||||
@@ -35,6 +36,7 @@ const mapping = {
|
|||||||
umamiEventNames: WidgetUmamiEventNamesInput,
|
umamiEventNames: WidgetUmamiEventNamesInput,
|
||||||
umamiWebsite: WidgetUmamiWebsiteInput,
|
umamiWebsite: WidgetUmamiWebsiteInput,
|
||||||
customWidgetSelect: WidgetCustomWidgetSelectInput,
|
customWidgetSelect: WidgetCustomWidgetSelectInput,
|
||||||
|
integrationSelect: WidgetIntegrationSelectInput,
|
||||||
} satisfies Record<WidgetOptionType, unknown>;
|
} satisfies Record<WidgetOptionType, unknown>;
|
||||||
|
|
||||||
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
|
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Select, Text } from "@mantine/core";
|
||||||
|
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import type { CommonWidgetInputProps } from "./common";
|
||||||
|
import { useWidgetInputTranslation } from "./common";
|
||||||
|
import { useFormContext } from "./form";
|
||||||
|
|
||||||
|
const useIntegrationSelectTranslation = () => useScopedI18n("widget.integrationSelect");
|
||||||
|
|
||||||
|
export const WidgetIntegrationSelectInput = ({
|
||||||
|
property,
|
||||||
|
kind,
|
||||||
|
options,
|
||||||
|
}: CommonWidgetInputProps<"integrationSelect">) => {
|
||||||
|
const t = useIntegrationSelectTranslation();
|
||||||
|
const tInput = useWidgetInputTranslation(kind, property);
|
||||||
|
const form = useFormContext();
|
||||||
|
|
||||||
|
const integrationIds = form.values.integrationIds as string[];
|
||||||
|
|
||||||
|
const { data: selectData = [], isPending, isError } = options.useOptions(integrationIds);
|
||||||
|
const currentValue = form.getInputProps(`options.${property}`).value as string;
|
||||||
|
const hasCurrentInData = !currentValue || selectData.some((opt) => opt.value === currentValue);
|
||||||
|
const data = hasCurrentInData ? selectData : [...selectData, { value: currentValue, label: currentValue }];
|
||||||
|
|
||||||
|
if (integrationIds.length === 0) {
|
||||||
|
return (
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t("configureIntegrationFirst")}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const description = options.withDescription ? tInput("description") : undefined;
|
||||||
|
const placeholder = isPending ? t("loading") : t("placeholder");
|
||||||
|
const error = isError ? t("loadError") : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Select
|
||||||
|
label={tInput("label")}
|
||||||
|
description={description}
|
||||||
|
placeholder={placeholder}
|
||||||
|
clearable={options.clearable}
|
||||||
|
searchable={options.searchable}
|
||||||
|
nothingFoundMessage={t("noResults")}
|
||||||
|
data={data}
|
||||||
|
disabled={isError}
|
||||||
|
error={error}
|
||||||
|
{...form.getInputProps(`options.${property}`)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -36,35 +36,35 @@ export default function BeszelAlertsWidget({
|
|||||||
isEditMode,
|
isEditMode,
|
||||||
}: WidgetComponentProps<"beszelAlerts">) {
|
}: WidgetComponentProps<"beszelAlerts">) {
|
||||||
const t = useScopedI18n("widget.beszelAlerts");
|
const t = useScopedI18n("widget.beszelAlerts");
|
||||||
const { data: results = [] } = clientApi.widget.beszel.getAlerts.useQuery(
|
const alertsInput = useMemo(
|
||||||
{
|
() => ({ integrationIds, includeHistory: options.showHistory, maxHistoryItems: options.maxHistoryItems }),
|
||||||
integrationIds,
|
[integrationIds, options.showHistory, options.maxHistoryItems],
|
||||||
includeHistory: options.showHistory,
|
|
||||||
maxHistoryItems: options.maxHistoryItems,
|
|
||||||
},
|
|
||||||
{ staleTime: 30 * 1000 },
|
|
||||||
);
|
);
|
||||||
|
const { data: results = [] } = clientApi.widget.beszel.getAlerts.useQuery(alertsInput, {
|
||||||
|
staleTime: 15_000,
|
||||||
|
refetchInterval: 15_000,
|
||||||
|
retry: false,
|
||||||
|
});
|
||||||
const utils = clientApi.useUtils();
|
const utils = clientApi.useUtils();
|
||||||
|
|
||||||
clientApi.widget.beszel.subscribeAlerts.useSubscription(
|
clientApi.widget.beszel.subscribeAlerts.useSubscription(alertsInput, {
|
||||||
{ integrationIds, includeHistory: options.showHistory, maxHistoryItems: options.maxHistoryItems },
|
enabled: !isEditMode,
|
||||||
{
|
onData(data) {
|
||||||
enabled: !isEditMode,
|
utils.widget.beszel.getAlerts.setData(alertsInput, (prev) => {
|
||||||
onData(data) {
|
if (!prev) return prev;
|
||||||
utils.widget.beszel.getAlerts.setData(
|
return prev.map((r) =>
|
||||||
{ integrationIds, includeHistory: options.showHistory, maxHistoryItems: options.maxHistoryItems },
|
r.integrationId === data.integrationId
|
||||||
(prev) => {
|
? {
|
||||||
if (!prev) return prev;
|
...r,
|
||||||
return prev.map((r) =>
|
alerts: data.alerts.alerts,
|
||||||
r.integrationId === data.integrationId
|
history: data.alerts.history,
|
||||||
? { ...r, alerts: data.alerts.alerts, history: data.alerts.history, updatedAt: data.timestamp }
|
updatedAt: data.timestamp,
|
||||||
: r,
|
}
|
||||||
);
|
: r,
|
||||||
},
|
|
||||||
);
|
);
|
||||||
},
|
});
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
|
|
||||||
const systemNameMap = useMemo(() => {
|
const systemNameMap = useMemo(() => {
|
||||||
const map: Record<string, string> = {};
|
const map: Record<string, string> = {};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { IconBell } from "@tabler/icons-react";
|
import { IconBell, IconServerOff } from "@tabler/icons-react";
|
||||||
import { z } from "zod/v4";
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
import { createWidgetDefinition } from "../definition";
|
import { createWidgetDefinition } from "../definition";
|
||||||
@@ -11,7 +11,16 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelAle
|
|||||||
createOptions() {
|
createOptions() {
|
||||||
return optionsBuilder.from((factory) => ({
|
return optionsBuilder.from((factory) => ({
|
||||||
showHistory: factory.switch({ defaultValue: true }),
|
showHistory: factory.switch({ defaultValue: true }),
|
||||||
maxHistoryItems: factory.number({ defaultValue: 10, validate: z.number().min(1).max(100) }),
|
maxHistoryItems: factory.number({
|
||||||
|
defaultValue: 10,
|
||||||
|
validate: z.number().min(1).max(100),
|
||||||
|
}),
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.beszelAlerts.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
}).withDynamicImport(() => import("./component"));
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Badge, Box, Card, Group, Progress, Text, Stack } from "@mantine/core";
|
import type { MantineSize } from "@mantine/core";
|
||||||
|
import { Badge, Box, Card, Group, Progress, Text, Stack, useComputedColorScheme } from "@mantine/core";
|
||||||
import {
|
import {
|
||||||
Activity,
|
Activity,
|
||||||
Battery,
|
Battery,
|
||||||
@@ -16,6 +17,7 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
import { clientApi } from "@homarr/api/client";
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import { useRequiredBoard } from "@homarr/boards/context";
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
import type { WidgetComponentProps } from "../definition";
|
import type { WidgetComponentProps } from "../definition";
|
||||||
@@ -151,6 +153,8 @@ interface SystemCardProps {
|
|||||||
t: ReturnType<typeof useScopedI18n<"widget.beszelSystemGrid">>;
|
t: ReturnType<typeof useScopedI18n<"widget.beszelSystemGrid">>;
|
||||||
size: SizeConfig;
|
size: SizeConfig;
|
||||||
maxMetrics: number;
|
maxMetrics: number;
|
||||||
|
backgroundColor: string;
|
||||||
|
itemRadius: MantineSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
const metricRenderers = [
|
const metricRenderers = [
|
||||||
@@ -307,16 +311,21 @@ const metricRenderers = [
|
|||||||
},
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const SystemCard = ({ system, options, t, size, maxMetrics }: SystemCardProps) => {
|
const SystemCard = ({ system, options, t, size, maxMetrics, backgroundColor, itemRadius }: SystemCardProps) => {
|
||||||
const visibleMetrics = metricRenderers.filter((m) => m.visible(system, options)).slice(0, maxMetrics);
|
const visibleMetrics = metricRenderers.filter((m) => m.visible(system, options)).slice(0, maxMetrics);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
padding={size.cardPadding}
|
padding={size.cardPadding}
|
||||||
radius="sm"
|
radius={itemRadius}
|
||||||
withBorder
|
bg={backgroundColor}
|
||||||
h="100%"
|
h="100%"
|
||||||
style={{ overflow: "hidden", display: "flex", flexDirection: "column" as const }}
|
style={{
|
||||||
|
overflow: "hidden",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column" as const,
|
||||||
|
border: "0.0625rem solid var(--border-color)",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Group gap="xs" mb={2}>
|
<Group gap="xs" mb={2}>
|
||||||
<Badge
|
<Badge
|
||||||
@@ -344,9 +353,15 @@ export default function BeszelSystemGridWidget({
|
|||||||
height,
|
height,
|
||||||
}: WidgetComponentProps<"beszelSystemGrid">) {
|
}: WidgetComponentProps<"beszelSystemGrid">) {
|
||||||
const t = useScopedI18n("widget.beszelSystemGrid");
|
const t = useScopedI18n("widget.beszelSystemGrid");
|
||||||
|
const board = useRequiredBoard();
|
||||||
|
const colorScheme = useComputedColorScheme("light");
|
||||||
|
const opacity = board.opacity / 100;
|
||||||
|
const bgBase: Record<"light" | "dark", string> = { dark: "57, 57, 57", light: "246, 247, 248" };
|
||||||
|
const backgroundColor = `rgba(${bgBase[colorScheme]}, ${opacity})`;
|
||||||
|
|
||||||
const { data: results = [] } = clientApi.widget.beszel.getSystems.useQuery(
|
const { data: results = [] } = clientApi.widget.beszel.getSystems.useQuery(
|
||||||
{ integrationIds },
|
{ integrationIds },
|
||||||
{ staleTime: 30 * 1000 },
|
{ staleTime: 5_000, refetchInterval: 5_000, retry: false },
|
||||||
);
|
);
|
||||||
|
|
||||||
useBeszelSystemsSubscription(integrationIds, !isEditMode);
|
useBeszelSystemsSubscription(integrationIds, !isEditMode);
|
||||||
@@ -374,7 +389,16 @@ export default function BeszelSystemGridWidget({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{filteredSystems.map((system) => (
|
{filteredSystems.map((system) => (
|
||||||
<SystemCard key={system._key} system={system} options={options} t={t} size={size} maxMetrics={maxMetrics} />
|
<SystemCard
|
||||||
|
key={system._key}
|
||||||
|
system={system}
|
||||||
|
options={options}
|
||||||
|
t={t}
|
||||||
|
size={size}
|
||||||
|
maxMetrics={maxMetrics}
|
||||||
|
backgroundColor={backgroundColor}
|
||||||
|
itemRadius={board.itemRadius}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { IconLayoutGrid } from "@tabler/icons-react";
|
import { IconLayoutGrid, IconServerOff } from "@tabler/icons-react";
|
||||||
|
|
||||||
import { createWidgetDefinition } from "../definition";
|
import { createWidgetDefinition } from "../definition";
|
||||||
import { statusOptions } from "../beszel/_shared/options";
|
import { statusOptions } from "../beszel/_shared/options";
|
||||||
@@ -10,7 +10,10 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
integrationsRequired: true,
|
integrationsRequired: true,
|
||||||
createOptions() {
|
createOptions() {
|
||||||
return optionsBuilder.from((factory) => ({
|
return optionsBuilder.from((factory) => ({
|
||||||
statusFilter: factory.select({ defaultValue: "all", options: statusOptions }),
|
statusFilter: factory.select({
|
||||||
|
defaultValue: "all",
|
||||||
|
options: statusOptions,
|
||||||
|
}),
|
||||||
showCpu: factory.switch({ defaultValue: true }),
|
showCpu: factory.switch({ defaultValue: true }),
|
||||||
showMemory: factory.switch({ defaultValue: true }),
|
showMemory: factory.switch({ defaultValue: true }),
|
||||||
showDisk: factory.switch({ defaultValue: true }),
|
showDisk: factory.switch({ defaultValue: true }),
|
||||||
@@ -24,4 +27,10 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
showAgent: factory.switch({ defaultValue: true }),
|
showAgent: factory.switch({ defaultValue: true }),
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.beszelSystemGrid.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
}).withDynamicImport(() => import("./component"));
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.beszelStatsSystemToggle {
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 150ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.beszelStatsWrapper:hover .beszelStatsSystemToggle {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useMemo } from "react";
|
||||||
import { ScrollArea, Select, SimpleGrid, Stack } from "@mantine/core";
|
import { ActionIcon, Button, Center, Menu, ScrollArea, Select, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||||
|
import { IconPlugConnectedX, IconServer, IconQuestionMark } from "@tabler/icons-react";
|
||||||
|
|
||||||
import { clientApi } from "@homarr/api/client";
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||||
import { useScopedI18n } from "@homarr/translation/client";
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import classes from "./component.module.css";
|
||||||
|
|
||||||
import type { WidgetComponentProps } from "../definition";
|
import type { WidgetComponentProps } from "../definition";
|
||||||
import { containerColors } from "../beszel/_shared/colors";
|
import { containerColors } from "../beszel/_shared/colors";
|
||||||
import {
|
import {
|
||||||
BeszelAreaChart,
|
BeszelChartPanel,
|
||||||
ChartPanel,
|
CPU_Y_AXIS_DOMAIN,
|
||||||
useContainerNames,
|
useContainerNames,
|
||||||
useDockerChartData,
|
useDockerChartData,
|
||||||
useSystemChartData,
|
useSystemChartData,
|
||||||
@@ -23,6 +27,7 @@ import {
|
|||||||
formatStorageBytes,
|
formatStorageBytes,
|
||||||
} from "../beszel/_shared/format";
|
} from "../beszel/_shared/format";
|
||||||
import { makeTooltipProps } from "../beszel/_shared/tooltip";
|
import { makeTooltipProps } from "../beszel/_shared/tooltip";
|
||||||
|
import { useLiveStats } from "../beszel/_shared/use-live-stats";
|
||||||
|
|
||||||
const tooltipPercent = makeTooltipProps(formatPercent);
|
const tooltipPercent = makeTooltipProps(formatPercent);
|
||||||
const tooltipGB = makeTooltipProps(formatGB, true);
|
const tooltipGB = makeTooltipProps(formatGB, true);
|
||||||
@@ -31,15 +36,23 @@ const tooltipPercentTotal = makeTooltipProps(formatPercent, true);
|
|||||||
const tooltipBytesTotal = makeTooltipProps(formatStorageBytes, true);
|
const tooltipBytesTotal = makeTooltipProps(formatStorageBytes, true);
|
||||||
|
|
||||||
const CHART_HEIGHT = 180;
|
const CHART_HEIGHT = 180;
|
||||||
|
const MB = 1024 * 1024;
|
||||||
|
const gridColumns = [1, 2] as const;
|
||||||
|
|
||||||
|
function statsWhenShown<T>(show: boolean | undefined, data: T | undefined): T | undefined {
|
||||||
|
if (!show || !data) return undefined;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
export default function BeszelSystemStatsWidget({
|
export default function BeszelSystemStatsWidget({
|
||||||
options,
|
options,
|
||||||
integrationIds,
|
integrationIds,
|
||||||
isEditMode,
|
isEditMode,
|
||||||
width,
|
width,
|
||||||
|
setOptions,
|
||||||
}: WidgetComponentProps<"beszelSystemStats">) {
|
}: WidgetComponentProps<"beszelSystemStats">) {
|
||||||
const t = useScopedI18n("widget.beszelSystemStats");
|
const t = useScopedI18n("widget.beszelSystemStats");
|
||||||
const { data: systemsResult = [] } = clientApi.widget.beszel.getSystems.useQuery(
|
const { data: systemsResult = [], isPending: systemsPending } = clientApi.widget.beszel.getSystems.useQuery(
|
||||||
{ integrationIds },
|
{ integrationIds },
|
||||||
{ staleTime: 30 * 1000 },
|
{ staleTime: 30 * 1000 },
|
||||||
);
|
);
|
||||||
@@ -49,200 +62,313 @@ export default function BeszelSystemStatsWidget({
|
|||||||
[systemsResult],
|
[systemsResult],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [selectedSystem, setSelectedSystem] = useState<string | null>(systems[0]?.value ?? null);
|
const selectedSystem = options.systemId || systems[0]?.value || "";
|
||||||
|
const selectedLabel = systems.find((s) => s.value === selectedSystem)?.label;
|
||||||
|
const systemExists = systems.some((s) => s.value === selectedSystem);
|
||||||
|
const systemReady = !systemsPending && (selectedSystem === "" || systemExists);
|
||||||
|
|
||||||
|
const handleSelectSystem = useCallback(
|
||||||
|
(value: string) => setOptions({ newOptions: { systemId: value } }),
|
||||||
|
[setOptions],
|
||||||
|
);
|
||||||
|
|
||||||
const showDocker = options.showDockerCpu || options.showDockerMemory || options.showDockerNetwork;
|
const showDocker = options.showDockerCpu || options.showDockerMemory || options.showDockerNetwork;
|
||||||
|
const isLive = options.timePeriod === "1m";
|
||||||
|
|
||||||
const { data: statsResult } = clientApi.widget.beszel.getSystemStats.useQuery(
|
const { data: statsResult } = clientApi.widget.beszel.getSystemStats.useQuery(
|
||||||
{
|
{
|
||||||
integrationIds,
|
integrationIds,
|
||||||
systemId: selectedSystem ?? systems[0]?.value ?? "",
|
systemId: selectedSystem,
|
||||||
timePeriod: options.timePeriod as "1h" | "12h" | "24h" | "1w" | "30d",
|
timePeriod: options.timePeriod as "1m" | "1h" | "12h" | "24h" | "1w" | "30d",
|
||||||
includeDocker: showDocker,
|
includeDocker: showDocker,
|
||||||
},
|
},
|
||||||
{ staleTime: 30 * 1000 },
|
{ staleTime: 30 * 1000, enabled: !isLive && systemReady && selectedSystem !== "" },
|
||||||
);
|
);
|
||||||
|
|
||||||
// BeszelSystemStats fields: storage values (m, mu, mb, d, du, s, su) are already in GB.
|
const { data: liveData, error: liveError } = useLiveStats(integrationIds, selectedSystem, isLive && systemReady);
|
||||||
// Disk I/O (dr, dw) is in MB/s — scale to bytes/s for display formatters.
|
|
||||||
// Network (ns, nr, b) is in bytes/s. Container memory (m) is in MB.
|
|
||||||
|
|
||||||
const cpuMap = useCallback((s: { cpu: number }) => ({ [t("chart.cpu.series")]: s.cpu }), [t]);
|
let activeStats:
|
||||||
const memoryMap = useCallback(
|
| { systemStats: BeszelSystemStatsRecord[]; containerStats: BeszelContainerStatsRecord[] }
|
||||||
(s: { mu: number; mb: number }) => ({
|
| null
|
||||||
[t("chart.memory.series")]: s.mu,
|
| undefined = statsResult;
|
||||||
[t("chart.memory.cache")]: s.mb ?? 0,
|
if (isLive) {
|
||||||
}),
|
activeStats = liveData;
|
||||||
[t],
|
}
|
||||||
);
|
|
||||||
const diskMap = useCallback((s: { du: number }) => ({ [t("chart.disk.series")]: s.du }), [t]);
|
const mappers = useMemo(
|
||||||
const diskIOMap = useCallback(
|
() => ({
|
||||||
(s: { dr?: number; dw?: number }) => ({
|
cpu: (s: { cpu: number }) => ({ [t("chart.cpu.series")]: s.cpu }),
|
||||||
[t("chart.diskIO.read")]: (s.dr ?? 0) * (1024 * 1024),
|
memory: (s: { mu: number; mb: number }) => ({
|
||||||
[t("chart.diskIO.write")]: (s.dw ?? 0) * (1024 * 1024),
|
[t("chart.memory.series")]: s.mu,
|
||||||
}),
|
[t("chart.memory.cache")]: s.mb ?? 0,
|
||||||
[t],
|
}),
|
||||||
);
|
disk: (s: { du: number }) => ({ [t("chart.disk.series")]: s.du }),
|
||||||
// b = public interface bandwidth (preferred), ns/nr = all-interface traffic (fallback)
|
diskIO: (s: { dr?: number; dw?: number }) => ({
|
||||||
const networkMap = useCallback(
|
[t("chart.diskIO.read")]: (s.dr ?? 0) * MB,
|
||||||
(s: { ns: number; nr: number; b?: [number, number] }) => ({
|
[t("chart.diskIO.write")]: (s.dw ?? 0) * MB,
|
||||||
[t("chart.network.sent")]: s.b?.[0] ?? s.ns,
|
}),
|
||||||
[t("chart.network.recv")]: s.b?.[1] ?? s.nr,
|
network: (s: { ns: number; nr: number; b?: [number, number] }) => ({
|
||||||
|
[t("chart.network.sent")]: s.b?.[0] ?? s.ns,
|
||||||
|
[t("chart.network.recv")]: s.b?.[1] ?? s.nr,
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
[t],
|
[t],
|
||||||
);
|
);
|
||||||
|
|
||||||
const cpuData = useSystemChartData(statsResult?.systemStats, cpuMap);
|
const series = useMemo(
|
||||||
const memoryData = useSystemChartData(statsResult?.systemStats, memoryMap);
|
() => ({
|
||||||
const diskData = useSystemChartData(statsResult?.systemStats, diskMap);
|
cpu: [{ name: t("chart.cpu.series"), color: "teal.6" }],
|
||||||
const diskIOData = useSystemChartData(statsResult?.systemStats, diskIOMap);
|
memory: [
|
||||||
const networkData = useSystemChartData(statsResult?.systemStats, networkMap);
|
{ name: t("chart.memory.series"), color: "teal.5" },
|
||||||
|
{ name: t("chart.memory.cache"), color: "teal.8" },
|
||||||
|
],
|
||||||
|
disk: [{ name: t("chart.disk.series"), color: "grape.6" }],
|
||||||
|
diskIO: [
|
||||||
|
{ name: t("chart.diskIO.write"), color: "orange.6" },
|
||||||
|
{ name: t("chart.diskIO.read"), color: "blue.6" },
|
||||||
|
],
|
||||||
|
network: [
|
||||||
|
{ name: t("chart.network.sent"), color: "blue.6" },
|
||||||
|
{ name: t("chart.network.recv"), color: "teal.6" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
[t],
|
||||||
|
);
|
||||||
|
|
||||||
const containerNames = useContainerNames(statsResult?.containerStats);
|
const systemStats = activeStats?.systemStats;
|
||||||
const dockerCpuData = useDockerChartData(statsResult?.containerStats, containerNames, "cpu");
|
const containerStatsRaw = activeStats?.containerStats;
|
||||||
const dockerMemData = useDockerChartData(statsResult?.containerStats, containerNames, "memory");
|
|
||||||
const dockerNetData = useDockerChartData(statsResult?.containerStats, containerNames, "network");
|
|
||||||
|
|
||||||
const containerSeries = containerNames.map((name, i) => ({
|
const cpuData = useSystemChartData(statsWhenShown(options.showCpu, systemStats), mappers.cpu, isLive);
|
||||||
name,
|
const memoryData = useSystemChartData(statsWhenShown(options.showMemory, systemStats), mappers.memory, isLive);
|
||||||
color: containerColors[i % containerColors.length] as string,
|
const diskData = useSystemChartData(statsWhenShown(options.showDisk, systemStats), mappers.disk, isLive);
|
||||||
}));
|
const diskIOData = useSystemChartData(statsWhenShown(options.showDiskIO, systemStats), mappers.diskIO, isLive);
|
||||||
|
const networkData = useSystemChartData(statsWhenShown(options.showNetwork, systemStats), mappers.network, isLive);
|
||||||
|
|
||||||
const cols = width > 600 ? 2 : 1;
|
const containerNames = useContainerNames(statsWhenShown(showDocker, containerStatsRaw));
|
||||||
|
const dockerCpuData = useDockerChartData(
|
||||||
|
statsWhenShown(options.showDockerCpu, containerStatsRaw),
|
||||||
|
containerNames,
|
||||||
|
"cpu",
|
||||||
|
isLive,
|
||||||
|
);
|
||||||
|
const dockerMemData = useDockerChartData(
|
||||||
|
statsWhenShown(options.showDockerMemory, containerStatsRaw),
|
||||||
|
containerNames,
|
||||||
|
"memory",
|
||||||
|
isLive,
|
||||||
|
);
|
||||||
|
const dockerNetData = useDockerChartData(
|
||||||
|
statsWhenShown(options.showDockerNetwork, containerStatsRaw),
|
||||||
|
containerNames,
|
||||||
|
"network",
|
||||||
|
isLive,
|
||||||
|
);
|
||||||
|
|
||||||
|
const containerSeries = useMemo(
|
||||||
|
() => containerNames.map((name, i) => ({ name, color: containerColors[i % containerColors.length] as string })),
|
||||||
|
[containerNames],
|
||||||
|
);
|
||||||
|
|
||||||
|
const cols = gridColumns[Number(width > 600)];
|
||||||
|
|
||||||
|
if (!systemsPending && !systemExists && systems.length > 0) {
|
||||||
|
return (
|
||||||
|
<Center h="100%">
|
||||||
|
<Stack align="center" gap="sm" p="md">
|
||||||
|
<IconQuestionMark size={40} />
|
||||||
|
<Text size="sm" c="dimmed" ta="center">
|
||||||
|
{t("error.systemNotFound")}
|
||||||
|
</Text>
|
||||||
|
<Select
|
||||||
|
size="xs"
|
||||||
|
data={systems}
|
||||||
|
value={selectedSystem}
|
||||||
|
placeholder={t("selectSystem")}
|
||||||
|
onChange={(value) => value && handleSelectSystem(value)}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Center>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLive && liveError && !liveData) {
|
||||||
|
return (
|
||||||
|
<Center h="100%">
|
||||||
|
<Stack align="center" gap="sm" p="md">
|
||||||
|
<IconPlugConnectedX size={40} />
|
||||||
|
<Text size="sm" c="dimmed" ta="center">
|
||||||
|
{t("error.liveConnectionFailed")}
|
||||||
|
</Text>
|
||||||
|
<Button size="xs" variant="light" onClick={() => setOptions({ newOptions: { timePeriod: "1h" } })}>
|
||||||
|
{t("error.switchToHistorical")}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
</Center>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollArea h="100%" style={{ pointerEvents: isEditMode ? "none" : undefined }}>
|
<ScrollArea
|
||||||
|
h="100%"
|
||||||
|
className={classes.beszelStatsWrapper}
|
||||||
|
style={{ pointerEvents: (isEditMode && "none") || undefined }}
|
||||||
|
>
|
||||||
<Stack gap="md" p="sm">
|
<Stack gap="md" p="sm">
|
||||||
<Select
|
{!isEditMode && systems.length > 1 && (
|
||||||
size="xs"
|
<Menu
|
||||||
data={systems}
|
trigger="click-hover"
|
||||||
value={selectedSystem}
|
openDelay={100}
|
||||||
onChange={setSelectedSystem}
|
closeDelay={300}
|
||||||
placeholder={t("selectSystem")}
|
position="bottom-start"
|
||||||
/>
|
withArrow
|
||||||
|
shadow="md"
|
||||||
|
withinPortal
|
||||||
|
>
|
||||||
|
<Menu.Target>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
size="sm"
|
||||||
|
className={classes.beszelStatsSystemToggle}
|
||||||
|
style={{ position: "absolute", top: 6, left: 6, zIndex: 1 }}
|
||||||
|
title={selectedLabel}
|
||||||
|
>
|
||||||
|
<IconServer size={14} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Menu.Target>
|
||||||
|
<Menu.Dropdown>
|
||||||
|
{systems.map((s) => (
|
||||||
|
<Menu.Item
|
||||||
|
key={s.value}
|
||||||
|
fz="xs"
|
||||||
|
fw={(s.value === selectedSystem && 600) || 400}
|
||||||
|
c={(s.value !== selectedSystem && "dimmed") || undefined}
|
||||||
|
onClick={() => handleSelectSystem(s.value)}
|
||||||
|
>
|
||||||
|
{s.label}
|
||||||
|
</Menu.Item>
|
||||||
|
))}
|
||||||
|
</Menu.Dropdown>
|
||||||
|
</Menu>
|
||||||
|
)}
|
||||||
|
|
||||||
{statsResult && (
|
{activeStats && (
|
||||||
<SimpleGrid cols={cols} spacing="md">
|
<SimpleGrid cols={cols} spacing="md">
|
||||||
{options.showCpu && cpuData.length > 0 && (
|
{options.showCpu && cpuData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.cpu.title")} subtitle={t("chart.cpu.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.cpu.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.cpu.subtitle")}
|
||||||
data={cpuData}
|
chartProps={{
|
||||||
series={[{ name: t("chart.cpu.series"), color: "teal.6" }]}
|
h: CHART_HEIGHT,
|
||||||
fillOpacity={0.4}
|
data: cpuData,
|
||||||
yAxisFormatter={chartAxisFormatters.percent}
|
series: series.cpu,
|
||||||
yAxisDomain={[0, "auto"]}
|
yAxisFormatter: chartAxisFormatters.percent,
|
||||||
tooltipProps={tooltipPercent}
|
yAxisDomain: CPU_Y_AXIS_DOMAIN,
|
||||||
/>
|
tooltipProps: tooltipPercent,
|
||||||
</ChartPanel>
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showMemory && memoryData.length > 0 && (
|
{options.showMemory && memoryData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.memory.title")} subtitle={t("chart.memory.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.memory.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.memory.subtitle")}
|
||||||
data={memoryData}
|
chartProps={{
|
||||||
series={[
|
h: CHART_HEIGHT,
|
||||||
{ name: t("chart.memory.series"), color: "teal.5" },
|
data: memoryData,
|
||||||
{ name: t("chart.memory.cache"), color: "teal.8" },
|
type: "stacked",
|
||||||
]}
|
series: series.memory,
|
||||||
fillOpacity={0.4}
|
yAxisFormatter: chartAxisFormatters.gb,
|
||||||
yAxisFormatter={chartAxisFormatters.gb}
|
tooltipProps: tooltipGB,
|
||||||
tooltipProps={tooltipGB}
|
}}
|
||||||
withLegend
|
/>
|
||||||
/>
|
|
||||||
</ChartPanel>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showDisk && diskData.length > 0 && (
|
{options.showDisk && diskData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.disk.title")} subtitle={t("chart.disk.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.disk.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.disk.subtitle")}
|
||||||
data={diskData}
|
chartProps={{
|
||||||
series={[{ name: t("chart.disk.series"), color: "grape.6" }]}
|
h: CHART_HEIGHT,
|
||||||
fillOpacity={0.4}
|
data: diskData,
|
||||||
yAxisFormatter={chartAxisFormatters.gb}
|
series: series.disk,
|
||||||
tooltipProps={tooltipGB}
|
yAxisFormatter: chartAxisFormatters.gb,
|
||||||
/>
|
tooltipProps: tooltipGB,
|
||||||
</ChartPanel>
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showDiskIO && diskIOData.length > 0 && (
|
{options.showDiskIO && diskIOData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.diskIO.title")} subtitle={t("chart.diskIO.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.diskIO.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.diskIO.subtitle")}
|
||||||
data={diskIOData}
|
chartProps={{
|
||||||
series={[
|
h: CHART_HEIGHT,
|
||||||
{ name: t("chart.diskIO.write"), color: "orange.6" },
|
data: diskIOData,
|
||||||
{ name: t("chart.diskIO.read"), color: "blue.6" },
|
series: series.diskIO,
|
||||||
]}
|
yAxisFormatter: chartAxisFormatters.rate,
|
||||||
fillOpacity={0.3}
|
tooltipProps: tooltipRate,
|
||||||
yAxisFormatter={chartAxisFormatters.rate}
|
}}
|
||||||
tooltipProps={tooltipRate}
|
/>
|
||||||
withLegend
|
|
||||||
/>
|
|
||||||
</ChartPanel>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showNetwork && networkData.length > 0 && (
|
{options.showNetwork && networkData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.network.title")} subtitle={t("chart.network.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.network.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.network.subtitle")}
|
||||||
data={networkData}
|
chartProps={{
|
||||||
series={[
|
h: CHART_HEIGHT,
|
||||||
{ name: t("chart.network.sent"), color: "blue.6" },
|
data: networkData,
|
||||||
{ name: t("chart.network.recv"), color: "teal.6" },
|
series: series.network,
|
||||||
]}
|
yAxisFormatter: chartAxisFormatters.rate,
|
||||||
fillOpacity={0.3}
|
tooltipProps: tooltipRate,
|
||||||
yAxisFormatter={chartAxisFormatters.rate}
|
}}
|
||||||
tooltipProps={tooltipRate}
|
/>
|
||||||
withLegend
|
|
||||||
/>
|
|
||||||
</ChartPanel>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{showDocker && containerSeries.length > 0 && (
|
{showDocker && containerSeries.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{options.showDockerCpu && dockerCpuData.length > 0 && (
|
{options.showDockerCpu && dockerCpuData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.dockerCpu.title")} subtitle={t("chart.dockerCpu.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.dockerCpu.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.dockerCpu.subtitle")}
|
||||||
data={dockerCpuData}
|
chartProps={{
|
||||||
type="stacked"
|
h: CHART_HEIGHT,
|
||||||
series={containerSeries}
|
data: dockerCpuData,
|
||||||
fillOpacity={0.6}
|
type: "stacked",
|
||||||
yAxisFormatter={chartAxisFormatters.percent}
|
series: containerSeries,
|
||||||
tooltipProps={tooltipPercentTotal}
|
yAxisFormatter: chartAxisFormatters.percent,
|
||||||
/>
|
tooltipProps: tooltipPercentTotal,
|
||||||
</ChartPanel>
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showDockerMemory && dockerMemData.length > 0 && (
|
{options.showDockerMemory && dockerMemData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.dockerMemory.title")} subtitle={t("chart.dockerMemory.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.dockerMemory.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.dockerMemory.subtitle")}
|
||||||
data={dockerMemData}
|
chartProps={{
|
||||||
type="stacked"
|
h: CHART_HEIGHT,
|
||||||
series={containerSeries}
|
data: dockerMemData,
|
||||||
fillOpacity={0.6}
|
type: "stacked",
|
||||||
yAxisFormatter={chartAxisFormatters.bytes}
|
series: containerSeries,
|
||||||
tooltipProps={tooltipBytesTotal}
|
yAxisFormatter: chartAxisFormatters.bytes,
|
||||||
/>
|
tooltipProps: tooltipBytesTotal,
|
||||||
</ChartPanel>
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{options.showDockerNetwork && dockerNetData.length > 0 && (
|
{options.showDockerNetwork && dockerNetData.length > 0 && (
|
||||||
<ChartPanel title={t("chart.dockerNetwork.title")} subtitle={t("chart.dockerNetwork.subtitle")}>
|
<BeszelChartPanel
|
||||||
<BeszelAreaChart
|
title={t("chart.dockerNetwork.title")}
|
||||||
h={CHART_HEIGHT}
|
subtitle={t("chart.dockerNetwork.subtitle")}
|
||||||
data={dockerNetData}
|
chartProps={{
|
||||||
type="stacked"
|
h: CHART_HEIGHT,
|
||||||
series={containerSeries}
|
data: dockerNetData,
|
||||||
fillOpacity={0.6}
|
series: containerSeries,
|
||||||
yAxisFormatter={chartAxisFormatters.rate}
|
yAxisFormatter: chartAxisFormatters.rate,
|
||||||
tooltipProps={tooltipRate}
|
tooltipProps: tooltipRate,
|
||||||
/>
|
}}
|
||||||
</ChartPanel>
|
/>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { IconChartAreaLine } from "@tabler/icons-react";
|
import { IconChartAreaLine, IconServerOff } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
|
||||||
import { createWidgetDefinition } from "../definition";
|
import { createWidgetDefinition } from "../definition";
|
||||||
import { optionsBuilder } from "../options";
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
const timePeriodOptions = [
|
const timePeriodOptions = [
|
||||||
|
{ value: "1m", label: "Live" },
|
||||||
{ value: "1h", label: "1 Hour" },
|
{ value: "1h", label: "1 Hour" },
|
||||||
{ value: "12h", label: "12 Hours" },
|
{ value: "12h", label: "12 Hours" },
|
||||||
{ value: "24h", label: "24 Hours" },
|
{ value: "24h", label: "24 Hours" },
|
||||||
@@ -17,7 +20,26 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
integrationsRequired: true,
|
integrationsRequired: true,
|
||||||
createOptions() {
|
createOptions() {
|
||||||
return optionsBuilder.from((factory) => ({
|
return optionsBuilder.from((factory) => ({
|
||||||
timePeriod: factory.select({ defaultValue: "1h", options: timePeriodOptions }),
|
systemId: factory.integrationSelect({
|
||||||
|
withDescription: true,
|
||||||
|
clearable: true,
|
||||||
|
useOptions: (integrationIds: string[]) => {
|
||||||
|
const {
|
||||||
|
data = [],
|
||||||
|
isPending,
|
||||||
|
isError,
|
||||||
|
} = clientApi.widget.beszel.getSystems.useQuery(
|
||||||
|
{ integrationIds },
|
||||||
|
{ enabled: integrationIds.length > 0, staleTime: 30_000 },
|
||||||
|
);
|
||||||
|
const selectData = data.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name })));
|
||||||
|
return { data: selectData, isPending, isError };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
timePeriod: factory.select({
|
||||||
|
defaultValue: "1h",
|
||||||
|
options: timePeriodOptions,
|
||||||
|
}),
|
||||||
showCpu: factory.switch({ defaultValue: true }),
|
showCpu: factory.switch({ defaultValue: true }),
|
||||||
showMemory: factory.switch({ defaultValue: true }),
|
showMemory: factory.switch({ defaultValue: true }),
|
||||||
showDisk: factory.switch({ defaultValue: true }),
|
showDisk: factory.switch({ defaultValue: true }),
|
||||||
@@ -28,4 +50,10 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
showDockerNetwork: factory.switch({ defaultValue: true }),
|
showDockerNetwork: factory.switch({ defaultValue: true }),
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.beszelSystemStats.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
}).withDynamicImport(() => import("./component"));
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -34,7 +34,7 @@ type SystemRowWithKey = BeszelSystemRow & { _key: string };
|
|||||||
|
|
||||||
interface SizeConfig {
|
interface SizeConfig {
|
||||||
iconSize: number;
|
iconSize: number;
|
||||||
fontSize: "xs" | "10px";
|
fontSize: "xs" | "sm";
|
||||||
progressSize: "xs" | "sm";
|
progressSize: "xs" | "sm";
|
||||||
cellPadding: number;
|
cellPadding: number;
|
||||||
valueMiw: number;
|
valueMiw: number;
|
||||||
@@ -42,9 +42,21 @@ interface SizeConfig {
|
|||||||
|
|
||||||
const getSizeConfig = (width: number): SizeConfig => {
|
const getSizeConfig = (width: number): SizeConfig => {
|
||||||
if (width < 400) {
|
if (width < 400) {
|
||||||
return { iconSize: 10, fontSize: "10px", progressSize: "xs", cellPadding: 2, valueMiw: 30 };
|
return {
|
||||||
|
iconSize: 10,
|
||||||
|
fontSize: "xs",
|
||||||
|
progressSize: "xs",
|
||||||
|
cellPadding: 2,
|
||||||
|
valueMiw: 30,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
return { iconSize: 14, fontSize: "xs", progressSize: "sm", cellPadding: 4, valueMiw: 38 };
|
return {
|
||||||
|
iconSize: 14,
|
||||||
|
fontSize: "sm",
|
||||||
|
progressSize: "sm",
|
||||||
|
cellPadding: 4,
|
||||||
|
valueMiw: 38,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function BeszelSystemTableWidget({
|
export default function BeszelSystemTableWidget({
|
||||||
@@ -56,7 +68,7 @@ export default function BeszelSystemTableWidget({
|
|||||||
const t = useScopedI18n("widget.beszelSystemTable");
|
const t = useScopedI18n("widget.beszelSystemTable");
|
||||||
const { data: results = [] } = clientApi.widget.beszel.getSystems.useQuery(
|
const { data: results = [] } = clientApi.widget.beszel.getSystems.useQuery(
|
||||||
{ integrationIds },
|
{ integrationIds },
|
||||||
{ staleTime: 30 * 1000 },
|
{ staleTime: 5_000, refetchInterval: 5_000, retry: false },
|
||||||
);
|
);
|
||||||
const size = getSizeConfig(width);
|
const size = getSizeConfig(width);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { IconTable } from "@tabler/icons-react";
|
import { IconServerOff, IconTable } from "@tabler/icons-react";
|
||||||
|
|
||||||
import { createWidgetDefinition } from "../definition";
|
import { createWidgetDefinition } from "../definition";
|
||||||
import { statusOptions } from "../beszel/_shared/options";
|
import { statusOptions } from "../beszel/_shared/options";
|
||||||
@@ -29,9 +29,15 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
integrationsRequired: true,
|
integrationsRequired: true,
|
||||||
createOptions() {
|
createOptions() {
|
||||||
return optionsBuilder.from((factory) => ({
|
return optionsBuilder.from((factory) => ({
|
||||||
statusFilter: factory.select({ defaultValue: "all", options: statusOptions }),
|
statusFilter: factory.select({
|
||||||
|
defaultValue: "all",
|
||||||
|
options: statusOptions,
|
||||||
|
}),
|
||||||
sortBy: factory.select({ defaultValue: "name", options: sortOptions }),
|
sortBy: factory.select({ defaultValue: "name", options: sortOptions }),
|
||||||
sortDirection: factory.select({ defaultValue: "asc", options: sortDirectionOptions }),
|
sortDirection: factory.select({
|
||||||
|
defaultValue: "asc",
|
||||||
|
options: sortDirectionOptions,
|
||||||
|
}),
|
||||||
showCpu: factory.switch({ defaultValue: true }),
|
showCpu: factory.switch({ defaultValue: true }),
|
||||||
showMemory: factory.switch({ defaultValue: true }),
|
showMemory: factory.switch({ defaultValue: true }),
|
||||||
showDisk: factory.switch({ defaultValue: true }),
|
showDisk: factory.switch({ defaultValue: true }),
|
||||||
@@ -45,4 +51,10 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
showAgent: factory.switch({ defaultValue: true }),
|
showAgent: factory.switch({ defaultValue: true }),
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.beszelSystemTable.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
}).withDynamicImport(() => import("./component"));
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useMemo } from "react";
|
import { memo, useMemo, useRef } from "react";
|
||||||
import { Group, Stack, Text } from "@mantine/core";
|
import { Group, Stack, Text } from "@mantine/core";
|
||||||
import type { AreaChartProps } from "@mantine/charts";
|
import type { AreaChartProps } from "@mantine/charts";
|
||||||
import { AreaChart } from "@mantine/charts";
|
import { AreaChart } from "@mantine/charts";
|
||||||
@@ -9,17 +9,28 @@ import dayjs from "dayjs";
|
|||||||
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||||
|
|
||||||
const formatTime = (timestamp: string) => dayjs(timestamp).format("HH:mm");
|
const formatTime = (timestamp: string) => dayjs(timestamp).format("HH:mm");
|
||||||
|
const formatTimeLive = (timestamp: string) => dayjs(timestamp).format("HH:mm:ss");
|
||||||
|
|
||||||
const yAxisBase = { tickMargin: 0, tick: { fontSize: 10 } } as const;
|
function prepareRecords<T>(records: T[], live: boolean) {
|
||||||
|
if (live) {
|
||||||
interface ChartPanelProps {
|
return { fmt: formatTimeLive, ordered: records };
|
||||||
title: string;
|
}
|
||||||
subtitle?: string;
|
return { fmt: formatTime, ordered: [...records].toReversed() };
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ChartPanel = ({ title, subtitle, children }: ChartPanelProps) => (
|
const yAxisBase = { tickMargin: 0, tick: { fontSize: 10 } } as const;
|
||||||
<Stack gap={4} style={{ minWidth: 0, overflow: "hidden" }}>
|
const chartStyle = { minWidth: 0, minHeight: 0 } as const;
|
||||||
|
const panelStyle = { minWidth: 0, overflow: "hidden" } as const;
|
||||||
|
export const CPU_Y_AXIS_DOMAIN: [number, string] = [0, "auto"];
|
||||||
|
|
||||||
|
interface BeszelChartPanelProps {
|
||||||
|
title: string;
|
||||||
|
subtitle?: string;
|
||||||
|
chartProps: BeszelAreaChartProps;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BeszelChartPanel = memo(({ title, subtitle, chartProps }: BeszelChartPanelProps) => (
|
||||||
|
<Stack gap={4} style={panelStyle}>
|
||||||
<Group gap="xs">
|
<Group gap="xs">
|
||||||
<Text size="sm" fw={600}>
|
<Text size="sm" fw={600}>
|
||||||
{title}
|
{title}
|
||||||
@@ -30,57 +41,93 @@ export const ChartPanel = ({ title, subtitle, children }: ChartPanelProps) => (
|
|||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
{children}
|
<BeszelAreaChart {...chartProps} />
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
));
|
||||||
|
|
||||||
type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "withDots" | "withXAxis" | "withYAxis"> & {
|
type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "withDots" | "withXAxis" | "withYAxis"> & {
|
||||||
yAxisFormatter: (value: number) => string;
|
yAxisFormatter: (value: number) => string;
|
||||||
yAxisDomain?: [number, string];
|
yAxisDomain?: [number, string];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const BeszelAreaChart = ({ yAxisFormatter, yAxisDomain, yAxisProps, style, ...props }: BeszelAreaChartProps) => (
|
const BeszelAreaChart = memo(
|
||||||
<AreaChart
|
({
|
||||||
dataKey="time"
|
yAxisFormatter,
|
||||||
curveType="monotone"
|
yAxisDomain,
|
||||||
withDots={false}
|
yAxisProps: yAxisPropsOverride,
|
||||||
withXAxis
|
type = "default",
|
||||||
withYAxis
|
...props
|
||||||
w="100%"
|
}: BeszelAreaChartProps) => {
|
||||||
style={{ minWidth: 0, minHeight: 0, ...style }}
|
const mergedYAxis = useMemo(() => {
|
||||||
yAxisProps={{
|
const base = {
|
||||||
...yAxisBase,
|
...yAxisBase,
|
||||||
...(yAxisDomain ? { domain: yAxisDomain } : {}),
|
width: 48,
|
||||||
tickFormatter: yAxisFormatter,
|
tickMargin: 2,
|
||||||
...yAxisProps,
|
tickFormatter: yAxisFormatter,
|
||||||
}}
|
...yAxisPropsOverride,
|
||||||
{...props}
|
};
|
||||||
/>
|
if (yAxisDomain) {
|
||||||
|
return { ...base, domain: yAxisDomain };
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}, [yAxisFormatter, yAxisDomain, yAxisPropsOverride]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AreaChart
|
||||||
|
dataKey="time"
|
||||||
|
curveType="monotone"
|
||||||
|
withGradient={false}
|
||||||
|
connectNulls
|
||||||
|
withDots={false}
|
||||||
|
type={type}
|
||||||
|
strokeWidth={1}
|
||||||
|
fillOpacity={0.2}
|
||||||
|
withXAxis
|
||||||
|
withYAxis
|
||||||
|
w="100%"
|
||||||
|
style={chartStyle}
|
||||||
|
yAxisProps={mergedYAxis}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const useSystemChartData = (
|
export const useSystemChartData = (
|
||||||
systemStats: BeszelSystemStatsRecord[] | undefined,
|
systemStats: BeszelSystemStatsRecord[] | undefined,
|
||||||
mapFn: (stats: BeszelSystemStatsRecord["stats"]) => Record<string, unknown>,
|
mapFn: (stats: BeszelSystemStatsRecord["stats"]) => Record<string, unknown>,
|
||||||
|
live = false,
|
||||||
) =>
|
) =>
|
||||||
useMemo(() => {
|
useMemo(() => {
|
||||||
if (!systemStats) return [];
|
if (!systemStats) return [];
|
||||||
return [...systemStats].toReversed().map((r) => ({
|
const { fmt, ordered } = prepareRecords(systemStats, live);
|
||||||
time: formatTime(r.created),
|
return ordered.map((r) => ({
|
||||||
|
time: fmt(r.created),
|
||||||
...mapFn(r.stats),
|
...mapFn(r.stats),
|
||||||
}));
|
}));
|
||||||
}, [systemStats, mapFn]);
|
}, [systemStats, mapFn, live]);
|
||||||
|
|
||||||
export const useContainerNames = (containerStats: BeszelContainerStatsRecord[] | undefined, max = 15) =>
|
export const useContainerNames = (containerStats: BeszelContainerStatsRecord[] | undefined, max = 15) => {
|
||||||
useMemo(() => {
|
const prevRef = useRef<string[]>([]);
|
||||||
if (!containerStats?.length) return [];
|
return useMemo(() => {
|
||||||
|
if (!containerStats?.length) {
|
||||||
|
if (prevRef.current.length === 0) return prevRef.current;
|
||||||
|
prevRef.current = [];
|
||||||
|
return prevRef.current;
|
||||||
|
}
|
||||||
const names = new Set<string>();
|
const names = new Set<string>();
|
||||||
for (const record of containerStats) {
|
for (const record of containerStats) {
|
||||||
for (const c of record.stats) {
|
for (const c of record.stats) {
|
||||||
names.add(c.n);
|
names.add(c.n);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return [...names].slice(0, max);
|
const next = [...names].slice(0, max);
|
||||||
|
const prev = prevRef.current;
|
||||||
|
if (prev.length === next.length && prev.every((n, i) => n === next[i])) return prev;
|
||||||
|
prevRef.current = next;
|
||||||
|
return next;
|
||||||
}, [containerStats, max]);
|
}, [containerStats, max]);
|
||||||
|
};
|
||||||
|
|
||||||
type ContainerExtractor = (container: BeszelContainerStatsRecord["stats"][number] | undefined) => number;
|
type ContainerExtractor = (container: BeszelContainerStatsRecord["stats"][number] | undefined) => number;
|
||||||
|
|
||||||
@@ -97,16 +144,19 @@ export const useDockerChartData = (
|
|||||||
containerStats: BeszelContainerStatsRecord[] | undefined,
|
containerStats: BeszelContainerStatsRecord[] | undefined,
|
||||||
containerNames: string[],
|
containerNames: string[],
|
||||||
metric: "cpu" | "memory" | "network",
|
metric: "cpu" | "memory" | "network",
|
||||||
|
live = false,
|
||||||
) =>
|
) =>
|
||||||
useMemo(() => {
|
useMemo(() => {
|
||||||
if (!containerStats?.length) return [];
|
if (!containerStats?.length) return [];
|
||||||
const extract = defaultContainerExtractors[metric];
|
const extract = defaultContainerExtractors[metric];
|
||||||
if (!extract) return [];
|
if (!extract) return [];
|
||||||
return [...containerStats].toReversed().map((record) => {
|
const { fmt, ordered } = prepareRecords(containerStats, live);
|
||||||
const point: Record<string, unknown> = { time: formatTime(record.created) };
|
return ordered.map((record) => {
|
||||||
|
const point: Record<string, unknown> = { time: fmt(record.created) };
|
||||||
|
const byName = new Map(record.stats.map((c) => [c.n, c]));
|
||||||
for (const name of containerNames) {
|
for (const name of containerNames) {
|
||||||
point[name] = extract(record.stats.find((c) => c.n === name));
|
point[name] = extract(byName.get(name));
|
||||||
}
|
}
|
||||||
return point;
|
return point;
|
||||||
});
|
});
|
||||||
}, [containerStats, containerNames, metric]);
|
}, [containerStats, containerNames, metric, live]);
|
||||||
@@ -21,19 +21,16 @@ export const statusColorMap: Record<BeszelSystemStatus, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const containerColors = [
|
export const containerColors = [
|
||||||
"blue.6",
|
|
||||||
"teal.6",
|
|
||||||
"orange.6",
|
|
||||||
"grape.6",
|
|
||||||
"cyan.6",
|
|
||||||
"pink.6",
|
|
||||||
"lime.6",
|
|
||||||
"violet.6",
|
|
||||||
"indigo.6",
|
|
||||||
"yellow.6",
|
|
||||||
"red.6",
|
"red.6",
|
||||||
|
"orange.6",
|
||||||
|
"yellow.6",
|
||||||
|
"lime.6",
|
||||||
"green.6",
|
"green.6",
|
||||||
"blue.4",
|
"teal.6",
|
||||||
"teal.4",
|
"cyan.6",
|
||||||
"orange.4",
|
"blue.6",
|
||||||
|
"indigo.6",
|
||||||
|
"violet.6",
|
||||||
|
"grape.6",
|
||||||
|
"pink.6",
|
||||||
];
|
];
|
||||||
@@ -13,13 +13,11 @@ const styles: Record<string, CSSProperties> = {
|
|||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
lineHeight: 1.5,
|
lineHeight: 1.5,
|
||||||
pointerEvents: "none",
|
pointerEvents: "none",
|
||||||
maxHeight: 320,
|
|
||||||
overflowY: "auto",
|
|
||||||
overflowX: "hidden",
|
overflowX: "hidden",
|
||||||
},
|
},
|
||||||
header: { marginBottom: 4, fontWeight: 500, color: "var(--mantine-color-gray-2)" },
|
header: { marginBottom: 4, fontWeight: 550, color: "var(--mantine-color-gray-2)" },
|
||||||
row: { display: "flex", alignItems: "center", gap: 6, padding: "1px 0" },
|
row: { display: "flex", alignItems: "center", gap: 6, padding: "1px 0" },
|
||||||
indicator: { width: 3, height: 14, borderRadius: 1, flexShrink: 0 },
|
indicator: { width: 5, height: 14, borderRadius: 5, flexShrink: 0 },
|
||||||
name: {
|
name: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
color: "var(--mantine-color-gray-3)",
|
color: "var(--mantine-color-gray-3)",
|
||||||
@@ -78,7 +76,11 @@ const PortalTooltipContent = ({ active, label, payload, formatter, showTotal }:
|
|||||||
|
|
||||||
if (!isActive) return null;
|
if (!isActive) return null;
|
||||||
|
|
||||||
const sorted = [...(payload ?? [])].filter((p) => p.value > 0).toSorted((a, b) => b.value - a.value);
|
const deduped = new Map<string, TooltipPayloadItem>();
|
||||||
|
for (const item of (payload ?? []).filter((entry) => entry.value > 0)) {
|
||||||
|
if (!deduped.has(item.dataKey)) deduped.set(item.dataKey, item);
|
||||||
|
}
|
||||||
|
const sorted = [...deduped.values()].toSorted((a, b) => b.value - a.value);
|
||||||
|
|
||||||
if (!sorted.length) return null;
|
if (!sorted.length) return null;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
const MAX_BUFFER = 30;
|
||||||
|
const FLUSH_INTERVAL_MS = 3000;
|
||||||
|
|
||||||
|
interface LiveStatsData {
|
||||||
|
systemStats: BeszelSystemStatsRecord[];
|
||||||
|
containerStats: BeszelContainerStatsRecord[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendToBuffer(
|
||||||
|
prev: LiveStatsData | null,
|
||||||
|
incoming: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null },
|
||||||
|
): LiveStatsData {
|
||||||
|
const systemStats = [...(prev?.systemStats ?? []), incoming.stats].slice(-MAX_BUFFER);
|
||||||
|
const prevContainer = prev?.containerStats ?? [];
|
||||||
|
if (!incoming.containerStats) {
|
||||||
|
return { systemStats, containerStats: prevContainer };
|
||||||
|
}
|
||||||
|
return { systemStats, containerStats: [...prevContainer, incoming.containerStats].slice(-MAX_BUFFER) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useLiveStats = (integrationIds: string[], systemId: string, enabled: boolean) => {
|
||||||
|
const [data, setData] = useState<LiveStatsData | null>(null);
|
||||||
|
const [error, setError] = useState<Error | null>(null);
|
||||||
|
const bufferRef = useRef<LiveStatsData | null>(null);
|
||||||
|
const dirtyRef = useRef(false);
|
||||||
|
const generationRef = useRef(0);
|
||||||
|
|
||||||
|
const integrationKey = [...integrationIds].sort().join(",");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
generationRef.current += 1;
|
||||||
|
setData(null);
|
||||||
|
setError(null);
|
||||||
|
bufferRef.current = null;
|
||||||
|
dirtyRef.current = false;
|
||||||
|
}, [systemId, enabled, integrationKey]);
|
||||||
|
|
||||||
|
const onData = useCallback(
|
||||||
|
(incoming: { stats: BeszelSystemStatsRecord; containerStats: BeszelContainerStatsRecord | null }) => {
|
||||||
|
const gen = generationRef.current;
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (generationRef.current !== gen) return;
|
||||||
|
setError(null);
|
||||||
|
const isFirst = !bufferRef.current;
|
||||||
|
bufferRef.current = appendToBuffer(bufferRef.current, incoming);
|
||||||
|
dirtyRef.current = true;
|
||||||
|
if (isFirst) {
|
||||||
|
setData(bufferRef.current);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const onError = useCallback((err: unknown) => {
|
||||||
|
if (err instanceof Error) {
|
||||||
|
setError(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(new Error(String(err)));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const subscriptionInput = useMemo(() => ({ integrationIds, systemId }), [integrationKey, systemId]);
|
||||||
|
const subscriptionEnabled = enabled && systemId !== "";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!subscriptionEnabled) return;
|
||||||
|
const gen = generationRef.current;
|
||||||
|
const id = setInterval(() => {
|
||||||
|
if (generationRef.current !== gen) return;
|
||||||
|
if (!dirtyRef.current || !bufferRef.current) return;
|
||||||
|
dirtyRef.current = false;
|
||||||
|
setData(bufferRef.current);
|
||||||
|
}, FLUSH_INTERVAL_MS);
|
||||||
|
return () => clearInterval(id);
|
||||||
|
}, [subscriptionEnabled, integrationKey, systemId]);
|
||||||
|
|
||||||
|
clientApi.widget.beszel.subscribeSystemStats.useSubscription(subscriptionInput, {
|
||||||
|
enabled: subscriptionEnabled,
|
||||||
|
onData,
|
||||||
|
onError,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { data, error };
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import JsxParser from "react-jsx-parser";
|
import JsxParser from "react-jsx-parser";
|
||||||
import { Alert, Stack, Text } from "@mantine/core";
|
import { Alert, Stack, Text } from "@mantine/core";
|
||||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||||
@@ -19,6 +19,11 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
|||||||
const template = String(data.template ?? "");
|
const template = String(data.template ?? "");
|
||||||
const apiData = data.data;
|
const apiData = data.data;
|
||||||
const [parseErrors, setParseErrors] = useState<string[]>([]);
|
const [parseErrors, setParseErrors] = useState<string[]>([]);
|
||||||
|
const bindings = useMemo(() => SAFE_BINDINGS(apiData), [apiData]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setParseErrors([]);
|
||||||
|
}, [template, bindings]);
|
||||||
|
|
||||||
const handleError = useCallback((error: Error) => {
|
const handleError = useCallback((error: Error) => {
|
||||||
setParseErrors((prev) => appendParseError(prev, error.message));
|
setParseErrors((prev) => appendParseError(prev, error.message));
|
||||||
@@ -39,7 +44,8 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
|
|||||||
<JsxParser
|
<JsxParser
|
||||||
jsx={template}
|
jsx={template}
|
||||||
components={WHITELISTED_COMPONENTS as never}
|
components={WHITELISTED_COMPONENTS as never}
|
||||||
bindings={SAFE_BINDINGS(apiData)}
|
bindings={bindings}
|
||||||
|
disableKeyGeneration
|
||||||
componentsOnly
|
componentsOnly
|
||||||
allowUnknownElements={false}
|
allowUnknownElements={false}
|
||||||
blacklistedAttrs={[/^on.+/i, /^dangerously/i]}
|
blacklistedAttrs={[/^on.+/i, /^dangerously/i]}
|
||||||
|
|||||||
@@ -69,9 +69,13 @@ function isTabPanel(child: ReactNode): child is React.ReactElement<TabPanelProps
|
|||||||
export function TabsContainer({ children, defaultTab }: TabsContainerProps) {
|
export function TabsContainer({ children, defaultTab }: TabsContainerProps) {
|
||||||
const panels = Children.toArray(children).filter(isTabPanel);
|
const panels = Children.toArray(children).filter(isTabPanel);
|
||||||
const firstPanel = panels[0];
|
const firstPanel = panels[0];
|
||||||
|
const panelValues = new Set(panels.map((p) => p.props.value));
|
||||||
|
const resolvedDefault = defaultTab && panelValues.has(defaultTab) && defaultTab;
|
||||||
|
const initialTab = resolvedDefault || firstPanel?.props.value || null;
|
||||||
|
const [activeTab, setActiveTab] = useState<string | null>(initialTab);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tabs defaultValue={defaultTab ?? firstPanel?.props.value}>
|
<Tabs value={activeTab} onChange={setActiveTab}>
|
||||||
<Tabs.List>
|
<Tabs.List>
|
||||||
{panels.map((panel) => (
|
{panels.map((panel) => (
|
||||||
<Tabs.Tab key={panel.props.value} value={panel.props.value}>
|
<Tabs.Tab key={panel.props.value} value={panel.props.value}>
|
||||||
|
|||||||
@@ -60,6 +60,16 @@ interface DynamicSelectInput extends CommonInput<DynamicSelectOption | null> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface IntegrationSelectInput extends CommonInput<string> {
|
||||||
|
clearable?: boolean;
|
||||||
|
searchable?: boolean;
|
||||||
|
useOptions: (integrationIds: string[]) => {
|
||||||
|
data: { value: string; label: string }[];
|
||||||
|
isPending: boolean;
|
||||||
|
isError: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface NumberInput extends CommonInput<number> {
|
interface NumberInput extends CommonInput<number> {
|
||||||
validate: z.ZodNumber;
|
validate: z.ZodNumber;
|
||||||
step?: number;
|
step?: number;
|
||||||
@@ -175,6 +185,14 @@ const optionsFactory = {
|
|||||||
defaultValue: "",
|
defaultValue: "",
|
||||||
withDescription: true,
|
withDescription: true,
|
||||||
}),
|
}),
|
||||||
|
integrationSelect: (input: IntegrationSelectInput) => ({
|
||||||
|
type: "integrationSelect" as const,
|
||||||
|
defaultValue: input.defaultValue ?? "",
|
||||||
|
withDescription: input.withDescription ?? false,
|
||||||
|
clearable: input.clearable ?? false,
|
||||||
|
searchable: input.searchable ?? true,
|
||||||
|
useOptions: input.useOptions,
|
||||||
|
}),
|
||||||
customWidgetSelect: (input?: CommonInput<string>) => ({
|
customWidgetSelect: (input?: CommonInput<string>) => ({
|
||||||
type: "customWidgetSelect" as const,
|
type: "customWidgetSelect" as const,
|
||||||
defaultValue: input?.defaultValue ?? "",
|
defaultValue: input?.defaultValue ?? "",
|
||||||
|
|||||||
Reference in new issue
Block a user