Compare commits

..
Author SHA1 Message Date
Manuel cb77f588e9 Merge remote-tracking branch 'origin/experiment/tasks' into experiment/tasks
# Conflicts:
#	packages/job-scheduler/package.json
2026-03-25 21:12:12 +01:00
Manuel 4192cdaa6e experiment: tasks 2026-03-25 19:46:10 +00:00
Manuel 718b03cdb3 experiment: tasks 2026-03-25 20:35:53 +01:00
85 changed files with 774 additions and 1008 deletions

No files matched your search

-41
View File
@@ -1,44 +1,3 @@
## [1.57.0](https://github.com/homarr-labs/homarr/compare/v1.56.1...v1.57.0) (2026-03-27)
### Features
* add "allowModals" option for iframe widget ([#5339](https://github.com/homarr-labs/homarr/issues/5339)) ([2fefd9d](https://github.com/homarr-labs/homarr/commit/2fefd9da01c827160fa5fd9b63a38615ea9969e2))
* add GPU monitoring support via Glances integration ([#5255](https://github.com/homarr-labs/homarr/issues/5255)) ([003dac4](https://github.com/homarr-labs/homarr/commit/003dac4744f2e23535f1cbb7494187201af4b164)), closes [#5102](https://github.com/homarr-labs/homarr/issues/5102)
* add nextcloud notification provider ([#5343](https://github.com/homarr-labs/homarr/issues/5343)) ([f88bf95](https://github.com/homarr-labs/homarr/commit/f88bf9582e1cf45a6b7fd898e12d227869a3849f))
### Bug Fixes
* **deps:** update dependency @immich/sdk to ^2.6.0 ([#5318](https://github.com/homarr-labs/homarr/issues/5318)) ([20a9b3d](https://github.com/homarr-labs/homarr/commit/20a9b3d556a15e6fdf7d1dbd78b677b5ce219c75))
* **deps:** update dependency @immich/sdk to ^2.6.1 ([#5319](https://github.com/homarr-labs/homarr/issues/5319)) ([feaf022](https://github.com/homarr-labs/homarr/commit/feaf022965cf4a27112c7e3bcb9ef3ad0dd5c281))
* **deps:** update dependency @next/eslint-plugin-next to v16.1.7 ([#5289](https://github.com/homarr-labs/homarr/issues/5289)) ([237d11d](https://github.com/homarr-labs/homarr/commit/237d11d2c021e28d58b0d627d2802d509d4c1b2b))
* **deps:** update dependency @tanstack/react-query to ^5.91.0 ([#5305](https://github.com/homarr-labs/homarr/issues/5305)) ([13b99d0](https://github.com/homarr-labs/homarr/commit/13b99d021b46fe0541ce9b42ba66756fafd26c30))
* **deps:** update dependency @tanstack/react-query to ^5.91.2 ([#5314](https://github.com/homarr-labs/homarr/issues/5314)) ([6fa6ba3](https://github.com/homarr-labs/homarr/commit/6fa6ba385e6691fefbb9f045a0ff976bcd85de16))
* **deps:** update dependency drizzle-kit to ^0.31.10 ([#5291](https://github.com/homarr-labs/homarr/issues/5291)) ([09227a3](https://github.com/homarr-labs/homarr/commit/09227a3884d291032f1012b59ce06babc3c87103))
* **deps:** update dependency fast-xml-parser to ^5.5.6 ([#5297](https://github.com/homarr-labs/homarr/issues/5297)) ([991044e](https://github.com/homarr-labs/homarr/commit/991044ebd78288bea7b441d3c14b159b5e66915b))
* **deps:** update dependency fast-xml-parser to ^5.5.7 ([#5315](https://github.com/homarr-labs/homarr/issues/5315)) ([2336f9e](https://github.com/homarr-labs/homarr/commit/2336f9ee5e35f7b610743dee55b91caf8434c1e4))
* **deps:** update dependency ioredis to v5.10.1 ([#5316](https://github.com/homarr-labs/homarr/issues/5316)) ([47b2d36](https://github.com/homarr-labs/homarr/commit/47b2d36f7a0933b6a6bbb61a449888be9304e1c5))
* **deps:** update dependency isomorphic-dompurify to ^3.4.0 ([#5292](https://github.com/homarr-labs/homarr/issues/5292)) ([6276449](https://github.com/homarr-labs/homarr/commit/62764499e7bbc9995ecf3de7351c9224d6aee4b6))
* **deps:** update dependency isomorphic-dompurify to ^3.5.0 ([#5299](https://github.com/homarr-labs/homarr/issues/5299)) ([b6b11c3](https://github.com/homarr-labs/homarr/commit/b6b11c39d2b4a33c5732ae239d7c1aaba6003cc6))
* **deps:** update dependency isomorphic-dompurify to ^3.5.1 ([#5300](https://github.com/homarr-labs/homarr/issues/5300)) ([94dfddf](https://github.com/homarr-labs/homarr/commit/94dfddf8bde2966b46bcd2d30e5e4f886ebe4605))
* **deps:** update dependency isomorphic-dompurify to ^3.6.0 ([#5334](https://github.com/homarr-labs/homarr/issues/5334)) ([8d64cb8](https://github.com/homarr-labs/homarr/commit/8d64cb8a5e276677b033774152c921aedc1e6c8a))
* **deps:** update dependency mysql2 to v3.20.0 ([#5283](https://github.com/homarr-labs/homarr/issues/5283)) ([4fb48c2](https://github.com/homarr-labs/homarr/commit/4fb48c23a2ccb1c047bab0d354933561e81cc3ed))
* **deps:** update dependency swagger-ui-react to ^5.32.1 ([#5296](https://github.com/homarr-labs/homarr/issues/5296)) ([63c55ce](https://github.com/homarr-labs/homarr/commit/63c55cec5711c41544c65ab83f24d09e63b10354))
* **deps:** update dependency trpc-to-openapi to ^3.2.0 ([#5320](https://github.com/homarr-labs/homarr/issues/5320)) ([22f5d3b](https://github.com/homarr-labs/homarr/commit/22f5d3b95959cf0a835c9750b41106eaafc4432e))
* **deps:** update dependency typescript-eslint to ^8.57.1 ([#5286](https://github.com/homarr-labs/homarr/issues/5286)) ([d4e4c96](https://github.com/homarr-labs/homarr/commit/d4e4c9669d648632a055b5ec0515821b50821142))
* **deps:** update dependency undici to v7.24.5 ([#5338](https://github.com/homarr-labs/homarr/issues/5338)) ([22bbef9](https://github.com/homarr-labs/homarr/commit/22bbef9d8e03215abddf6c6e26a5df45f252626d))
* **deps:** update dependency ws to ^8.20.0 ([#5337](https://github.com/homarr-labs/homarr/issues/5337)) ([d53c922](https://github.com/homarr-labs/homarr/commit/d53c922688606bd7d9494089e1ec43b930ad9923))
* **deps:** update mantine monorepo to ^8.3.18 ([#5298](https://github.com/homarr-labs/homarr/issues/5298)) ([6f8e629](https://github.com/homarr-labs/homarr/commit/6f8e62963a4eb47cb3095dff46ee0e759e1cbd3c))
* **deps:** update nextjs monorepo to v16.2.0 ([#5309](https://github.com/homarr-labs/homarr/issues/5309)) ([8831613](https://github.com/homarr-labs/homarr/commit/883161357dab4d94ff794f9444040d88074c464c))
* **deps:** update nextjs monorepo to v16.2.1 ([#5330](https://github.com/homarr-labs/homarr/issues/5330)) ([e23a397](https://github.com/homarr-labs/homarr/commit/e23a397a80e4409f5da50c737aeb26b295ce79fc))
* **deps:** update testcontainers-node monorepo to ^11.13.0 ([#5293](https://github.com/homarr-labs/homarr/issues/5293)) ([c009dd7](https://github.com/homarr-labs/homarr/commit/c009dd7de649bf24ab9bcf5ea25c65ebd18540bb))
* **deps:** update tiptap monorepo to v3.20.4 ([#5287](https://github.com/homarr-labs/homarr/issues/5287)) ([369b4d4](https://github.com/homarr-labs/homarr/commit/369b4d486327d0eaa04b70dd692c426f9a39afd7))
* **deps:** update trpc monorepo to ^11.14.1 ([#5328](https://github.com/homarr-labs/homarr/issues/5328)) ([d7f0596](https://github.com/homarr-labs/homarr/commit/d7f0596db8e44e2e79bb26095abd142b50675cc3))
* **deps:** update turbo monorepo to ^2.8.18 ([#5308](https://github.com/homarr-labs/homarr/issues/5308)) ([24694b9](https://github.com/homarr-labs/homarr/commit/24694b92411aae818b97a3a5c9add97d707a2f38))
* **deps:** update turbo monorepo to ^2.8.19 ([#5310](https://github.com/homarr-labs/homarr/issues/5310)) ([7537184](https://github.com/homarr-labs/homarr/commit/7537184a8168a4837d0a83a925a70c938555f199))
* **deps:** update turbo monorepo to ^2.8.20 ([#5317](https://github.com/homarr-labs/homarr/issues/5317)) ([5b4e6fc](https://github.com/homarr-labs/homarr/commit/5b4e6fcc11c877815c4730607de84ab70d630fb8))
* handle null ports in Docker container table ([#5313](https://github.com/homarr-labs/homarr/issues/5313)) ([1639da5](https://github.com/homarr-labs/homarr/commit/1639da57794d2555426e56030b4b34e2cc201aa9)), closes [#5311](https://github.com/homarr-labs/homarr/issues/5311)
* warnings in code ([4f2b821](https://github.com/homarr-labs/homarr/commit/4f2b8217f819b91ec4b05e32aebd6bc5473db155))
## [1.56.1](https://github.com/homarr-labs/homarr/compare/v1.56.0...v1.56.1) (2026-03-20) ## [1.56.1](https://github.com/homarr-labs/homarr/compare/v1.56.0...v1.56.1) (2026-03-20)
### Bug Fixes ### Bug Fixes
+2 -1
View File
@@ -43,10 +43,11 @@ RUN mkdir -p /var/cache/nginx && \
COPY --from=builder /app/apps/nextjs/next.config.ts . COPY --from=builder /app/apps/nextjs/next.config.ts .
COPY --from=builder /app/apps/nextjs/package.json . COPY --from=builder /app/apps/nextjs/package.json .
COPY --from=builder /app/apps/tasks/tasks.cjs ./apps/tasks/tasks.cjs
COPY --from=builder /app/apps/websocket/wssServer.cjs ./apps/websocket/wssServer.cjs COPY --from=builder /app/apps/websocket/wssServer.cjs ./apps/websocket/wssServer.cjs
COPY --from=builder /app/node_modules/better-sqlite3/build/Release/better_sqlite3.node /app/build/better_sqlite3.node COPY --from=builder /app/node_modules/better-sqlite3/build/Release/better_sqlite3.node /app/build/better_sqlite3.node
COPY scripts/job-scheduler.js ./scripts/job-scheduler.js
COPY --from=builder /app/packages/db/migrations ./db/migrations COPY --from=builder /app/packages/db/migrations ./db/migrations
# Automatically leverage output traces to reduce image size # Automatically leverage output traces to reduce image size
+6 -6
View File
@@ -59,10 +59,10 @@
"@tanstack/react-query": "^5.91.2", "@tanstack/react-query": "^5.91.2",
"@tanstack/react-query-devtools": "^5.91.3", "@tanstack/react-query-devtools": "^5.91.3",
"@tanstack/react-query-next-experimental": "^5.91.0", "@tanstack/react-query-next-experimental": "^5.91.0",
"@trpc/client": "^11.14.1", "@trpc/client": "^11.13.4",
"@trpc/next": "^11.14.1", "@trpc/next": "^11.13.4",
"@trpc/react-query": "^11.14.1", "@trpc/react-query": "^11.13.4",
"@trpc/server": "^11.14.1", "@trpc/server": "^11.13.4",
"@xterm/addon-canvas": "^0.7.0", "@xterm/addon-canvas": "^0.7.0",
"@xterm/addon-fit": "0.11.0", "@xterm/addon-fit": "0.11.0",
"@xterm/xterm": "^6.0.0", "@xterm/xterm": "^6.0.0",
@@ -73,10 +73,10 @@
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"flag-icons": "^7.5.0", "flag-icons": "^7.5.0",
"glob": "^13.0.6", "glob": "^13.0.6",
"isomorphic-dompurify": "^3.6.0", "isomorphic-dompurify": "^3.5.1",
"jotai": "^2.18.1", "jotai": "^2.18.1",
"mantine-react-table": "2.0.0-beta.9", "mantine-react-table": "2.0.0-beta.9",
"next": "16.2.1", "next": "16.2.0",
"postcss-preset-mantine": "^1.18.0", "postcss-preset-mantine": "^1.18.0",
"prismjs": "^1.30.0", "prismjs": "^1.30.0",
"react": "19.2.4", "react": "19.2.4",
@@ -13,7 +13,6 @@ import type { useForm } from "@homarr/form";
import { useZodForm } from "@homarr/form"; import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications"; import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client"; import { useScopedI18n } from "@homarr/translation/client";
import { sanitizeRedirectionUrl } from "@homarr/validation/redirection-url";
import { userSignInSchema } from "@homarr/validation/user"; import { userSignInSchema } from "@homarr/validation/user";
type Provider = "credentials" | "ldap" | "oidc"; type Provider = "credentials" | "ldap" | "oidc";
@@ -71,7 +70,7 @@ export const LoginForm = ({ providers, oidcClientName, isOidcAutoLoginEnabled, c
// Redirect to the callback URL if the response is defined and comes from a credentials provider (ldap or credentials). oidc is redirected automatically. // Redirect to the callback URL if the response is defined and comes from a credentials provider (ldap or credentials). oidc is redirected automatically.
await revalidatePathActionAsync("/"); await revalidatePathActionAsync("/");
router.push(sanitizeRedirectionUrl(callbackUrl)); router.push(callbackUrl);
}, },
[t, router, callbackUrl], [t, router, callbackUrl],
); );
@@ -4,7 +4,6 @@ import { Card, Center, Stack, Text, Title } from "@mantine/core";
import { env } from "@homarr/auth/env"; import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server"; import { getScopedI18n } from "@homarr/translation/server";
import { sanitizeRedirectionUrl } from "@homarr/validation/redirection-url";
import { HomarrLogoWithTitle } from "~/components/layout/logo/homarr-logo"; import { HomarrLogoWithTitle } from "~/components/layout/logo/homarr-logo";
import { LoginForm } from "./_login-form"; import { LoginForm } from "./_login-form";
@@ -20,7 +19,7 @@ export default async function Login(props: LoginProps) {
const session = await auth(); const session = await auth();
if (session) { if (session) {
redirect(sanitizeRedirectionUrl(searchParams.callbackUrl)); redirect(searchParams.callbackUrl ?? "/");
} }
const t = await getScopedI18n("user.page.login"); const t = await getScopedI18n("user.page.login");
@@ -264,5 +264,6 @@ const usePreventLeaveWithDirty = (isDirty: boolean) => {
window.removeEventListener("popstate", handlePopState); window.removeEventListener("popstate", handlePopState);
window.removeEventListener("beforeunload", handleBeforeUnload); window.removeEventListener("beforeunload", handleBeforeUnload);
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDirty]); }, [isDirty]);
}; };
@@ -27,6 +27,7 @@ export const BoardReadyProvider = ({ children }: PropsWithChildren) => {
useEffect(() => { useEffect(() => {
setReadySections((previous) => previous.filter((id) => board.sections.some((section) => section.id === id))); setReadySections((previous) => previous.filter((id) => board.sections.some((section) => section.id === id)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [board.sections.length, setReadySections]); }, [board.sections.length, setReadySections]);
const markAsReady = useCallback((id: string) => { const markAsReady = useCallback((id: string) => {
+4
View File
@@ -26,6 +26,7 @@ import { Analytics } from "~/components/layout/analytics";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation"; import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
import { SearchEngineOptimization } from "~/components/layout/search-engine-optimization"; import { SearchEngineOptimization } from "~/components/layout/search-engine-optimization";
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme"; import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
import { initializeJobManager } from "~/lib/job-manager";
import { DayJsLoader } from "./_client-providers/dayjs-loader"; import { DayJsLoader } from "./_client-providers/dayjs-loader";
import { JotaiProvider } from "./_client-providers/jotai"; import { JotaiProvider } from "./_client-providers/jotai";
import { CustomMantineProvider } from "./_client-providers/mantine"; import { CustomMantineProvider } from "./_client-providers/mantine";
@@ -83,6 +84,9 @@ export default async function Layout(props: {
const colorScheme = await getCurrentColorSchemeAsync(); const colorScheme = await getCurrentColorSchemeAsync();
const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr"; const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr";
// Initialize job manager
await initializeJobManager();
const StackedProvider = composeWrappers([ const StackedProvider = composeWrappers([
(innerProps) => { (innerProps) => {
return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />; return <AuthProvider session={session} logoutUrl={env.AUTH_LOGOUT_REDIRECT_URL} {...innerProps} />;
@@ -14,7 +14,7 @@ import { ApiKeysManagement } from "./components/api-keys";
export async function generateMetadata() { export async function generateMetadata() {
const session = await auth(); const session = await auth();
if (!session?.user.permissions.includes("admin")) { if (!session?.user || !session.user.permissions.includes("admin")) {
return {}; return {};
} }
@@ -27,7 +27,7 @@ export async function generateMetadata() {
export default async function ApiPage() { export default async function ApiPage() {
const session = await auth(); const session = await auth();
if (!session?.user.permissions.includes("admin")) { if (!session?.user || !session.user.permissions.includes("admin")) {
notFound(); notFound();
} }
const document = openApiDocument(extractBaseUrlFromHeaders(await headers())); const document = openApiDocument(extractBaseUrlFromHeaders(await headers()));
@@ -76,7 +76,6 @@ const createColumns = (
accessorKey: "ports", accessorKey: "ports",
header: t("docker.field.ports.label"), header: t("docker.field.ports.label"),
Cell({ cell }) { Cell({ cell }) {
if (!cell.row.original.ports) return null;
if (!cell.row.original.ports.length) return null; if (!cell.row.original.ports.length) return null;
return ( return (
<OverflowBadge overflowCount={1} data={cell.row.original.ports.map((port) => port.PrivatePort.toString())} /> <OverflowBadge overflowCount={1} data={cell.row.original.ports.map((port) => port.PrivatePort.toString())} />
@@ -18,7 +18,7 @@ import { LogContextProvider } from "./log-context";
export async function generateMetadata() { export async function generateMetadata() {
const session = await auth(); const session = await auth();
if (!session?.user.permissions.includes("admin")) { if (!session?.user || !session.user.permissions.includes("admin")) {
return {}; return {};
} }
const t = await getScopedI18n("management"); const t = await getScopedI18n("management");
@@ -30,7 +30,7 @@ export async function generateMetadata() {
export default async function LogsManagementPage() { export default async function LogsManagementPage() {
const session = await auth(); const session = await auth();
if (!session?.user.permissions.includes("other-view-logs")) { if (!session?.user || !session.user.permissions.includes("other-view-logs")) {
notFound(); notFound();
} }
@@ -75,6 +75,7 @@ const executeHealthCheckSafelyAsync = async (
}, },
}; };
} catch (error) { } catch (error) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
logger.error(new ErrorWithMetadata("Healthcheck failed", { name }, { cause: error })); logger.error(new ErrorWithMetadata("Healthcheck failed", { name }, { cause: error }));
return { return {
status: "unhealthy", status: "unhealthy",
@@ -0,0 +1,20 @@
import { NextRequest, NextResponse } from "next/server";
import { getJobManager } from "~/lib/job-manager";
export async function POST(request: NextRequest) {
// Only allow internal requests
const internalHeader = request.headers.get("x-internal-request");
if (internalHeader !== "true") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const jobManager = getJobManager();
await jobManager.triggerJobsAsync();
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error triggering jobs:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
+2 -1
View File
@@ -9,6 +9,7 @@ import { ipAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error"; import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db"; import { db } from "@homarr/db";
import { getJobManager } from "~/lib/job-manager";
const logger = createLogger({ module: "trpcRoute" }); const logger = createLogger({ module: "trpcRoute" });
@@ -45,7 +46,7 @@ const handler = auth(async (req) => {
endpoint: trpcPath, endpoint: trpcPath,
router: appRouter, router: appRouter,
req, req,
createContext: () => createTRPCContext({ session, headers: req.headers }), createContext: () => createTRPCContext({ session, headers: req.headers, jobManager: getJobManager() }),
onError({ error, path, type }) { onError({ error, path, type }) {
logger.error(new ErrorWithMetadata("tRPC Error occured", { path, type }, { cause: error })); logger.error(new ErrorWithMetadata("tRPC Error occured", { path, type }, { cause: error }));
}, },
@@ -117,6 +117,7 @@ const InnerContent = ({ item, ...dimensions }: InnerContentProps) => {
when={ when={
widgetSupportsIntegrations && widgetSupportsIntegrations &&
item.integrationIds.length === 0 && item.integrationIds.length === 0 &&
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false) (!("integrationsRequired" in definition) || definition.integrationsRequired !== false)
} }
/> />
@@ -206,6 +206,7 @@ export const useGridstack = (section: Omit<Section, "items">, itemIds: string[])
} }
// Only run this effect when the section items change // Only run this effect when the section items change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [itemIds.length, columnCount]); }, [itemIds.length, columnCount]);
/** /**
+17
View File
@@ -0,0 +1,17 @@
import { JobManager } from "@homarr/job-scheduler";
import { jobGroup } from "@homarr/cron-jobs";
import { db } from "@homarr/db";
let jobManagerInstance: JobManager | null = null;
export function getJobManager(): JobManager {
if (!jobManagerInstance) {
jobManagerInstance = new JobManager(db, jobGroup);
}
return jobManagerInstance;
}
export async function initializeJobManager(): Promise<void> {
const manager = getJobManager();
await jobGroup.initializeAsync();
}
-9
View File
@@ -1,9 +0,0 @@
import baseConfig from "@homarr/eslint-config/base";
/** @type {import('typescript-eslint').Config} */
export default [
{
ignores: ["tasks.cjs"],
},
...baseConfig,
];
-58
View File
@@ -1,58 +0,0 @@
{
"name": "@homarr/tasks",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"main": "./src/main.ts",
"types": "./src/main.ts",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --loader:.scss=text --external:*.node --external:@opentelemetry/api --external:deasync --external:bcrypt --outfile=tasks.cjs",
"clean": "rm -rf .turbo node_modules",
"dev": "pnpm with-env tsx ./src/main.ts",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit",
"with-env": "dotenv -e ../../.env --"
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/analytics": "workspace:^0.1.0",
"@homarr/auth": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^",
"@homarr/cron-job-api": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0",
"@homarr/cron-jobs-core": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/icons": "workspace:^0.1.0",
"@homarr/integrations": "workspace:^0.1.0",
"@homarr/ping": "workspace:^0.1.0",
"@homarr/redis": "workspace:^0.1.0",
"@homarr/request-handler": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@homarr/widgets": "workspace:^0.1.0",
"dayjs": "^1.11.20",
"dotenv": "^17.3.1",
"fastify": "^5.8.2",
"superjson": "2.2.6",
"undici": "7.24.5"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/node": "^24.12.0",
"dotenv-cli": "^11.0.0",
"esbuild": "^0.27.4",
"eslint": "^9.39.4",
"prettier": "^3.8.1",
"tsx": "4.20.4",
"typescript": "^5.9.3"
}
}
-52
View File
@@ -1,52 +0,0 @@
// This import has to be the first import in the file so that the agent is overridden before any other modules are imported.
import "./overrides";
import type { FastifyTRPCPluginOptions } from "@trpc/server/adapters/fastify";
import { fastifyTRPCPlugin } from "@trpc/server/adapters/fastify";
import fastify from "fastify";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import type { JobRouter } from "@homarr/cron-job-api";
import { jobRouter } from "@homarr/cron-job-api";
import { CRON_JOB_API_KEY_HEADER, CRON_JOB_API_PATH, CRON_JOB_API_PORT } from "@homarr/cron-job-api/constants";
import { jobGroup } from "@homarr/cron-jobs";
import { db } from "@homarr/db";
import { JobManager } from "./job-manager";
import { onStartAsync } from "./on-start";
const logger = createLogger({ module: "tasksMain" });
const server = fastify({
maxParamLength: 5000,
});
server.register(fastifyTRPCPlugin, {
prefix: CRON_JOB_API_PATH,
trpcOptions: {
router: jobRouter,
createContext: ({ req }) => ({
manager: new JobManager(db, jobGroup),
apiKey: req.headers[CRON_JOB_API_KEY_HEADER] as string | undefined,
}),
onError({ path, error }) {
logger.error(new ErrorWithMetadata("Error in tasks tRPC handler", { path }, { cause: error }));
},
} satisfies FastifyTRPCPluginOptions<JobRouter>["trpcOptions"],
});
void (async () => {
await onStartAsync();
await jobGroup.initializeAsync();
await jobGroup.startAllAsync();
try {
await server.listen({ port: CRON_JOB_API_PORT });
logger.info("Tasks web server started successfully", { port: CRON_JOB_API_PORT });
} catch (err) {
logger.error(
new ErrorWithMetadata("Failed to start tasks web server", { port: CRON_JOB_API_PORT }, { cause: err }),
);
process.exit(1);
}
})();
-7
View File
@@ -1,7 +0,0 @@
import { invalidateUpdateCheckerCacheAsync } from "./invalidate-update-checker-cache";
import { cleanupSessionsAsync } from "./session-cleanup";
export async function onStartAsync() {
await cleanupSessionsAsync();
await invalidateUpdateCheckerCacheAsync();
}
@@ -1,18 +0,0 @@
import { createLogger } from "@homarr/core/infrastructure/logs";
import { updateCheckerRequestHandler } from "@homarr/request-handler/update-checker";
const logger = createLogger({ module: "invalidateUpdateCheckerCache" });
/**
* Invalidates the update checker cache on startup to ensure fresh data.
* It is important as we want to avoid showing pending updates after the update to latest version.
*/
export async function invalidateUpdateCheckerCacheAsync() {
try {
const handler = updateCheckerRequestHandler.handler({});
await handler.invalidateAsync();
logger.debug("Update checker cache invalidated");
} catch (error) {
logger.error(new Error("Failed to invalidate update checker cache", { cause: error }));
}
}
@@ -1,41 +0,0 @@
import { env } from "@homarr/auth/env";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { db, eq, inArray } from "@homarr/db";
import { sessions, users } from "@homarr/db/schema";
import { supportedAuthProviders } from "@homarr/definitions";
const logger = createLogger({ module: "sessionCleanup" });
/**
* Deletes sessions for users that have inactive auth providers.
* Sessions from other providers are deleted so they can no longer be used.
*/
export async function cleanupSessionsAsync() {
try {
const currentAuthProviders = env.AUTH_PROVIDERS;
const inactiveAuthProviders = supportedAuthProviders.filter((provider) => !currentAuthProviders.includes(provider));
const subQuery = db
.select({ id: users.id })
.from(users)
.where(inArray(users.provider, inactiveAuthProviders))
.as("sq");
const sessionsWithInactiveProviders = await db
.select({ userId: sessions.userId })
.from(sessions)
.rightJoin(subQuery, eq(sessions.userId, subQuery.id));
const userIds = sessionsWithInactiveProviders.map(({ userId }) => userId).filter((value) => value !== null);
await db.delete(sessions).where(inArray(sessions.userId, userIds));
if (sessionsWithInactiveProviders.length > 0) {
logger.info("Deleted sessions for inactive providers", {
count: userIds.length,
});
} else {
logger.debug("No sessions to delete");
}
} catch (error) {
logger.error(new Error("Failed to clean up sessions", { cause: error }));
}
}
-5
View File
@@ -1,5 +0,0 @@
import { setGlobalDispatcher } from "undici";
import { UndiciHttpAgent } from "@homarr/core/infrastructure/http";
setGlobalDispatcher(new UndiciHttpAgent());
-13
View File
@@ -1,13 +0,0 @@
{
"extends": "@homarr/tsconfig/base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["src/*"],
"@homarr/node-unifi": ["../../node_modules/@types/node-unifi"]
},
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
},
"include": ["."],
"exclude": ["node_modules"]
}
+1 -1
View File
@@ -27,7 +27,7 @@
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"tsx": "4.20.4", "tsx": "4.20.4",
"ws": "^8.20.0" "ws": "^8.19.0"
}, },
"devDependencies": { "devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
+3 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "homarr", "name": "homarr",
"version": "1.57.0", "version": "1.56.1",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "cross-env CI=true turbo build", "build": "cross-env CI=true turbo build",
@@ -88,9 +88,9 @@
"linkifyjs@<4.3.2": ">=4.3.2", "linkifyjs@<4.3.2": ">=4.3.2",
"nanoid@>=4.0.0 <5.0.9": ">=5.1.7", "nanoid@>=4.0.0 <5.0.9": ">=5.1.7",
"prismjs@<1.30.0": ">=1.30.0", "prismjs@<1.30.0": ">=1.30.0",
"proxmox-api>undici": "7.24.5", "proxmox-api>undici": "7.24.0",
"react-is": "^19.2.4", "react-is": "^19.2.4",
"rollup@>=4.0.0 <4.22.4": ">=4.60.0", "rollup@>=4.0.0 <4.22.4": ">=4.59.0",
"sha.js@<=2.4.11": ">=2.4.12", "sha.js@<=2.4.11": ">=2.4.12",
"tar-fs@>=3.0.0 <3.0.9": ">=3.1.2", "tar-fs@>=3.0.0 <3.0.9": ">=3.1.2",
"tar-fs@>=2.0.0 <2.1.3": ">=3.1.2", "tar-fs@>=2.0.0 <2.1.3": ">=3.1.2",
+6 -6
View File
@@ -42,16 +42,16 @@
"@homarr/validation": "workspace:^0.1.0", "@homarr/validation": "workspace:^0.1.0",
"@kubernetes/client-node": "^1.4.0", "@kubernetes/client-node": "^1.4.0",
"@tanstack/react-query": "^5.91.2", "@tanstack/react-query": "^5.91.2",
"@trpc/client": "^11.14.1", "@trpc/client": "^11.13.4",
"@trpc/react-query": "^11.14.1", "@trpc/react-query": "^11.13.4",
"@trpc/server": "^11.14.1", "@trpc/server": "^11.13.4",
"@trpc/tanstack-react-query": "^11.14.1", "@trpc/tanstack-react-query": "^11.13.4",
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"superjson": "2.2.6", "superjson": "2.2.6",
"trpc-to-openapi": "^3.2.0", "trpc-to-openapi": "^3.1.0",
"zod": "^4.2.1" "zod": "^4.2.1"
}, },
"devDependencies": { "devDependencies": {
+14 -15
View File
@@ -3,7 +3,6 @@ import z from "zod/v4";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import { cronExpressionSchema, jobGroupKeys, jobNameSchema } from "@homarr/cron-job-api"; import { cronExpressionSchema, jobGroupKeys, jobNameSchema } from "@homarr/cron-job-api";
import { cronJobApi } from "@homarr/cron-job-api/client";
import type { TaskStatus } from "@homarr/cron-job-status"; import type { TaskStatus } from "@homarr/cron-job-status";
import { createCronJobStatusChannel } from "@homarr/cron-job-status"; import { createCronJobStatusChannel } from "@homarr/cron-job-status";
@@ -15,20 +14,20 @@ export const cronJobsRouter = createTRPCRouter({
triggerJob: permissionRequiredProcedure triggerJob: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
.input(jobNameSchema) .input(jobNameSchema)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.trigger.mutate(input); await ctx.jobManager.triggerAsync(input);
}), }),
startJob: permissionRequiredProcedure startJob: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
.input(jobNameSchema) .input(jobNameSchema)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.start.mutate(input); await ctx.jobManager.startAsync(input);
}), }),
stopJob: permissionRequiredProcedure stopJob: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
.input(jobNameSchema) .input(jobNameSchema)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.stop.mutate(input); await ctx.jobManager.stopAsync(input);
}), }),
updateJobInterval: permissionRequiredProcedure updateJobInterval: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
@@ -38,23 +37,23 @@ export const cronJobsRouter = createTRPCRouter({
cron: cronExpressionSchema, cron: cronExpressionSchema,
}), }),
) )
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.updateInterval.mutate(input); await ctx.jobManager.updateIntervalAsync(input.name, input.cron);
}), }),
disableJob: permissionRequiredProcedure disableJob: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
.input(jobNameSchema) .input(jobNameSchema)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.disable.mutate(input); await ctx.jobManager.disableAsync(input);
}), }),
enableJob: permissionRequiredProcedure enableJob: permissionRequiredProcedure
.requiresPermission("admin") .requiresPermission("admin")
.input(jobNameSchema) .input(jobNameSchema)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await cronJobApi.enable.mutate(input); await ctx.jobManager.enableAsync(input);
}), }),
getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async () => { getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
return await cronJobApi.getAll.query(); return await ctx.jobManager.getAllAsync();
}), }),
subscribeToStatusUpdates: permissionRequiredProcedure.requiresPermission("admin").subscription(() => { subscribeToStatusUpdates: permissionRequiredProcedure.requiresPermission("admin").subscription(() => {
return observable<TaskStatus>((emit) => { return observable<TaskStatus>((emit) => {
+59
View File
@@ -0,0 +1,59 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { createTRPCRouter, protectedProcedure } from "../trpc";
import type { JobGroupKeys } from "@homarr/cron-jobs";
import { jobGroup } from "@homarr/cron-jobs";
import { cronExpressionSchema } from "@homarr/cron-job-api";
const jobNameSchema = z.enum(jobGroup.getKeys());
export const cronJobsRouter = createTRPCRouter({
start: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(jobNameSchema)
.mutation(async ({ input, ctx }) => {
// Use the job manager from context
await ctx.jobManager.startAsync(input);
}),
trigger: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(jobNameSchema)
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.triggerAsync(input);
}),
stop: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(jobNameSchema)
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.stopAsync(input);
}),
updateInterval: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(
z.object({
name: jobNameSchema,
cron: cronExpressionSchema,
}),
)
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.updateIntervalAsync(input.name, input.cron);
}),
disable: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(jobNameSchema)
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.disableAsync(input);
}),
enable: protectedProcedure
.meta({ requiredPermission: "admin" })
.input(jobNameSchema)
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.enableAsync(input);
}),
getAll: protectedProcedure
.meta({ requiredPermission: "admin" })
.query(async ({ ctx }) => {
return ctx.jobManager.getAllAsync();
}),
});
@@ -140,7 +140,7 @@ interface DockerContainer {
id: string; id: string;
state: ContainerState; state: ContainerState;
image: string; image: string;
ports: Port[] | undefined; ports: Port[];
iconUrl: string | null; iconUrl: string | null;
cpuUsage: number; cpuUsage: number;
memoryUsage: number; memoryUsage: number;
+2 -1
View File
@@ -34,7 +34,7 @@ const logger = createLogger({ module: "trpc" });
* *
* @see https://trpc.io/docs/server/context * @see https://trpc.io/docs/server/context
*/ */
export const createTRPCContext = (opts: { headers: Headers; session: Session | null }) => { export const createTRPCContext = (opts: { headers: Headers; session: Session | null; jobManager?: any }) => {
const session = opts.session; const session = opts.session;
const source = opts.headers.get("x-trpc-source") ?? "unknown"; const source = opts.headers.get("x-trpc-source") ?? "unknown";
@@ -44,6 +44,7 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
session, session,
deviceType: userAgent(opts.headers).device.type, deviceType: userAgent(opts.headers).device.type,
db, db,
jobManager: opts.jobManager,
}; };
}; };
+1 -1
View File
@@ -34,7 +34,7 @@
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"cookies": "^0.9.1", "cookies": "^0.9.1",
"ldapts": "8.1.7", "ldapts": "8.1.7",
"next": "16.2.1", "next": "16.2.0",
"next-auth": "5.0.0-beta.30", "next-auth": "5.0.0-beta.30",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
+2 -2
View File
@@ -30,11 +30,11 @@
"@paralleldrive/cuid2": "^3.3.0", "@paralleldrive/cuid2": "^3.3.0",
"cookie": "1.1.1", "cookie": "1.1.1",
"dayjs": "^1.11.20", "dayjs": "^1.11.20",
"next": "16.2.1", "next": "16.2.0",
"octokit": "^5.0.5", "octokit": "^5.0.5",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"undici": "7.24.5", "undici": "7.18.2",
"zod": "^4.2.1", "zod": "^4.2.1",
"zod-validation-error": "^5.0.0" "zod-validation-error": "^5.0.0"
}, },
+2 -2
View File
@@ -37,7 +37,7 @@
}, },
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@t3-oss/env-nextjs": "^0.13.11", "@t3-oss/env-nextjs": "^0.13.10",
"better-sqlite3": "^12.6.2", "better-sqlite3": "^12.6.2",
"dns-caching": "^0.2.9", "dns-caching": "^0.2.9",
"drizzle-orm": "^0.45.1", "drizzle-orm": "^0.45.1",
@@ -53,7 +53,7 @@
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/better-sqlite3": "7.6.13", "@types/better-sqlite3": "7.6.13",
"@types/pg": "^8.20.0", "@types/pg": "^8.18.0",
"eslint": "^9.39.4", "eslint": "^9.39.4",
"typescript": "^5.9.3" "typescript": "^5.9.3"
} }
+3 -3
View File
@@ -29,9 +29,9 @@
"@homarr/core": "workspace:^0.1.0", "@homarr/core": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0", "@homarr/cron-jobs": "workspace:^0.1.0",
"@tanstack/react-query": "^5.91.2", "@tanstack/react-query": "^5.91.2",
"@trpc/client": "^11.14.1", "@trpc/client": "^11.13.4",
"@trpc/server": "^11.14.1", "@trpc/server": "^11.13.4",
"@trpc/tanstack-react-query": "^11.14.1", "@trpc/tanstack-react-query": "^11.13.4",
"node-cron": "^4.2.1", "node-cron": "^4.2.1",
"react": "19.2.4", "react": "19.2.4",
"zod": "^4.2.1" "zod": "^4.2.1"
+1 -28
View File
@@ -1,12 +1,9 @@
import { createTask, validate } from "node-cron";
import { Stopwatch } from "@homarr/common"; import { Stopwatch } from "@homarr/common";
import type { MaybePromise } from "@homarr/common/types"; import type { MaybePromise } from "@homarr/common/types";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error"; import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db"; import { db } from "@homarr/db";
import type { Logger } from "./logger"; import type { Logger } from "./logger";
import type { ValidateCron } from "./validation";
export interface CreateCronJobCreatorOptions<TAllowedNames extends string> { export interface CreateCronJobCreatorOptions<TAllowedNames extends string> {
beforeCallback?: (name: TAllowedNames) => MaybePromise<void>; beforeCallback?: (name: TAllowedNames) => MaybePromise<void>;
@@ -74,28 +71,6 @@ const createCallback = <TAllowedNames extends string, TName extends TAllowedName
return { return {
name, name,
cronExpression: defaultCronExpression, cronExpression: defaultCronExpression,
async createTaskAsync() {
const configuration = await db.query.cronJobConfigurations.findFirst({
where: (cronJobConfigurations, { eq }) => eq(cronJobConfigurations.name, name),
});
const cronExpression = options.preventCustomInterval
? defaultCronExpression
: (configuration?.cronExpression ?? defaultCronExpression);
const scheduledTask = createTask(cronExpression, () => void catchingCallbackAsync(), {
name,
timezone: creatorOptions.timezone,
});
creatorOptions.logger.logDebug("The scheduled task for cron job was created", {
name,
cronExpression: defaultCronExpression,
timezone: creatorOptions.timezone,
runOnStart: options.runOnStart,
});
return scheduledTask;
},
async onStartAsync() { async onStartAsync() {
if (options.beforeStart) { if (options.beforeStart) {
creatorOptions.logger.logDebug("Running beforeStart for job", { creatorOptions.logger.logDebug("Running beforeStart for job", {
@@ -136,9 +111,7 @@ export const createCronJobCreator = <TAllowedNames extends string = string>(
name, name,
cronExpression: defaultCronExpression, cronExpression: defaultCronExpression,
}); });
if (!validate(defaultCronExpression)) { // Validation will be done by cron-parser when needed
throw new Error(`Invalid cron expression '${defaultCronExpression}' for job '${name}'`);
}
creatorOptions.logger.logDebug("Cron job expression for cron job is valid", { creatorOptions.logger.logDebug("Cron job expression for cron job is valid", {
name, name,
cronExpression: defaultCronExpression, cronExpression: defaultCronExpression,
+29 -38
View File
@@ -1,11 +1,9 @@
import type { ScheduledTask } from "node-cron";
import { objectEntries, objectKeys } from "@homarr/common"; import { objectEntries, objectKeys } from "@homarr/common";
import { db } from "@homarr/db"; import { db } from "@homarr/db";
import { jobRegistry } from "./registry";
import type { JobCallback } from "./creator"; import type { JobCallback } from "./creator";
import type { Logger } from "./logger"; import type { Logger } from "./logger";
import { jobRegistry } from "./registry";
type Jobs<TAllowedNames extends string> = { type Jobs<TAllowedNames extends string> = {
[name in TAllowedNames]: ReturnType<JobCallback<TAllowedNames, name>>; [name in TAllowedNames]: ReturnType<JobCallback<TAllowedNames, name>>;
@@ -34,86 +32,79 @@ export const createJobGroupCreator = <TAllowedNames extends string = string>(
}); });
} }
const tasks = new Map<string, ScheduledTask>();
return { return {
initializeAsync: async () => { initializeAsync: async () => {
// No tasks to create, just ensure jobs are registered
const configurations = await db.query.cronJobConfigurations.findMany(); const configurations = await db.query.cronJobConfigurations.findMany();
for (const job of jobRegistry.values()) { for (const job of jobs) {
const configuration = configurations.find(({ name }) => name === job.name); const configuration = configurations.find(({ name }) => name === job.name);
if (configuration?.isEnabled === false) { if (configuration?.isEnabled === false) {
continue; continue;
} }
if (tasks.has(job.name)) { // Run onStart if needed
continue; await job.onStartAsync();
}
const scheduledTask = await job.createTaskAsync();
tasks.set(job.name, scheduledTask);
} }
}, },
startAsync: async (name: keyof TJobs) => { startAsync: async (name: keyof TJobs) => {
const job = jobRegistry.get(name as string); // In new system, start means enable, but since we trigger manually, just log
const job = jobs[name];
if (!job) return; if (!job) return;
if (!tasks.has(job.name)) return;
options.logger.logInfo("Starting schedule of cron job.", { options.logger.logInfo("Enabling cron job.", {
name: job.name, name: job.name,
}); });
await job.onStartAsync(); await job.onStartAsync();
await tasks.get(name as string)?.start();
}, },
startAllAsync: async () => { startAllAsync: async () => {
for (const job of jobRegistry.values()) { for (const job of Object.values(jobs)) {
if (!tasks.has(job.name)) { options.logger.logInfo("Enabling cron job.", {
continue;
}
options.logger.logInfo("Starting schedule of cron job.", {
name: job.name, name: job.name,
}); });
await job.onStartAsync(); await job.onStartAsync();
await tasks.get(job.name)?.start();
} }
}, },
runManuallyAsync: async (name: keyof TJobs) => { runManuallyAsync: async (name: keyof TJobs) => {
const job = jobRegistry.get(name as string); const job = jobs[name];
if (!job) return; if (!job) return;
if (job.preventManualExecution) { if (job.preventManualExecution) {
throw new Error(`The job "${job.name}" can not be executed manually.`); throw new Error(`The job "${job.name}" can not be executed manually.`);
} }
options.logger.logInfo("Running schedule cron job manually.", { options.logger.logInfo("Running cron job manually.", {
name: job.name, name: job.name,
}); });
await tasks.get(name as string)?.execute(); await job.executeAsync();
}, },
stopAsync: async (name: keyof TJobs) => { stopAsync: async (name: keyof TJobs) => {
const job = jobRegistry.get(name as string); // In new system, stop means disable, but since no tasks, just log
const job = jobs[name];
if (!job) return; if (!job) return;
options.logger.logInfo("Stopping schedule of cron job.", { options.logger.logInfo("Disabling cron job.", {
name: job.name, name: job.name,
}); });
await tasks.get(name as string)?.stop();
}, },
stopAllAsync: async () => { stopAllAsync: async () => {
for (const job of jobRegistry.values()) { for (const job of Object.values(jobs)) {
options.logger.logInfo("Stopping schedule of cron job.", { options.logger.logInfo("Disabling cron job.", {
name: job.name, name: job.name,
}); });
await tasks.get(job.name)?.stop();
} }
}, },
getJobRegistry() { getJobRegistry() {
return jobRegistry as Map<TAllowedNames, ReturnType<JobCallback<TAllowedNames, TAllowedNames>>>; // Return a map of jobs
const registry = new Map();
for (const [key, job] of objectEntries(jobs)) {
registry.set(key, job);
}
return registry;
}, },
getTask(name: keyof TJobs) { getTask() {
return tasks.get(name as string) ?? null; // No tasks in new system
return null;
}, },
setTask(name: keyof TJobs, task: ScheduledTask) { setTask() {
tasks.set(name as string, task); // No tasks
}, },
getKeys() { getKeys() {
return objectKeys(jobs); return objectKeys(jobs);
+1 -1
View File
@@ -65,7 +65,7 @@
"@homarr/prettier-config": "workspace:^0.1.0", "@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0", "@homarr/tsconfig": "workspace:^0.1.0",
"@types/better-sqlite3": "7.6.13", "@types/better-sqlite3": "7.6.13",
"@types/pg": "^8.20.0", "@types/pg": "^8.18.0",
"dotenv-cli": "^11.0.0", "dotenv-cli": "^11.0.0",
"esbuild": "^0.27.4", "esbuild": "^0.27.4",
"eslint": "^9.39.4", "eslint": "^9.39.4",
+1 -1
View File
@@ -24,7 +24,7 @@
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"fast-xml-parser": "^5.5.8", "fast-xml-parser": "^5.5.7",
"zod": "^4.2.1" "zod": "^4.2.1"
}, },
"devDependencies": { "devDependencies": {
+1 -1
View File
@@ -217,7 +217,7 @@ export const integrationDefs = {
name: "Nextcloud", name: "Nextcloud",
secretKinds: [["username", "password"]], secretKinds: [["username", "password"]],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/nextcloud.svg", iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/nextcloud.svg",
category: ["calendar", "notifications"], category: ["calendar"],
documentationUrl: createDocumentationLink("/docs/integrations/nextcloud"), documentationUrl: createDocumentationLink("/docs/integrations/nextcloud"),
}, },
unifiController: { unifiController: {
+1 -1
View File
@@ -26,7 +26,7 @@
"dependencies": { "dependencies": {
"@homarr/common": "workspace:^0.1.0", "@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0", "@homarr/core": "workspace:^0.1.0",
"dockerode": "^4.0.10" "dockerode": "^4.0.9"
}, },
"devDependencies": { "devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0", "@homarr/eslint-config": "workspace:^0.2.0",
+1 -1
View File
@@ -47,7 +47,7 @@
"octokit": "^5.0.5", "octokit": "^5.0.5",
"proxmox-api": "1.1.1", "proxmox-api": "1.1.1",
"tsdav": "^2.1.8", "tsdav": "^2.1.8",
"undici": "7.24.5", "undici": "7.18.2",
"xml2js": "^0.6.2", "xml2js": "^0.6.2",
"zod": "^4.2.1" "zod": "^4.2.1"
}, },
@@ -33,7 +33,6 @@ export class DashDotIntegration extends Integration implements ISystemHealthMoni
const memoryLoad = await this.getCurrentMemoryLoadAsync(); const memoryLoad = await this.getCurrentMemoryLoadAsync();
const storageLoad = await this.getCurrentStorageLoadAsync(); const storageLoad = await this.getCurrentStorageLoadAsync();
const networkLoad = await this.getCurrentNetworkLoadAsync(); const networkLoad = await this.getCurrentNetworkLoadAsync();
const gpuLoad = await this.getCurrentGpuLoadAsync();
const channel = this.getChannel(); const channel = this.getChannel();
const history = await channel.getSliceUntilTimeAsync(dayjs().subtract(15, "minutes").toDate()); const history = await channel.getSliceUntilTimeAsync(dayjs().subtract(15, "minutes").toDate());
@@ -57,14 +56,6 @@ export class DashDotIntegration extends Integration implements ISystemHealthMoni
availablePkgUpdates: 0, availablePkgUpdates: 0,
rebootRequired: false, rebootRequired: false,
smart: [], // API endpoint does not provide S.M.A.R.T data. smart: [], // API endpoint does not provide S.M.A.R.T data.
gpu: gpuLoad.map((gpu, index) => ({
gpuId: `gpu-${index}`,
name: info.gpuNames[index] ?? `GPU ${index}`,
memoryUtilization: gpu.memory ?? 0,
processorUtilization: gpu.load ?? 0,
temperature: null,
fanSpeed: null,
})),
uptime: info.uptime, uptime: info.uptime,
version: `${info.operatingSystemVersion}`, version: `${info.operatingSystemVersion}`,
loadAverage: { loadAverage: {
@@ -85,7 +76,6 @@ export class DashDotIntegration extends Integration implements ISystemHealthMoni
cpuModel: serverInfo.cpu.model, cpuModel: serverInfo.cpu.model,
operatingSystemVersion: `${serverInfo.os.distro} ${serverInfo.os.release} (${serverInfo.os.kernel})`, operatingSystemVersion: `${serverInfo.os.distro} ${serverInfo.os.release} (${serverInfo.os.kernel})`,
uptime: serverInfo.os.uptime, uptime: serverInfo.os.uptime,
gpuNames: serverInfo.gpu.layout.map((gpu) => gpu.brand),
}; };
} }
@@ -160,17 +150,6 @@ export class DashDotIntegration extends Integration implements ISystemHealthMoni
return await networkLoadApi.parseAsync(JSON.parse(result)); return await networkLoadApi.parseAsync(JSON.parse(result));
} }
private async getCurrentGpuLoadAsync() {
try {
const response = await fetchWithTrustedCertificatesAsync(this.url("/load/gpu"));
const result = await response.json();
const data = await gpuLoadApi.parseAsync(result);
return data.layout;
} catch {
return [];
}
}
private getChannel() { private getChannel() {
return createChannelEventHistoryOld<z.infer<typeof cpuLoadPerCoreApiList>>( return createChannelEventHistoryOld<z.infer<typeof cpuLoadPerCoreApiList>>(
`integration:${this.integration.id}:history:cpu`, `integration:${this.integration.id}:history:cpu`,
@@ -219,25 +198,6 @@ const internalServerInfoApi = z.object({
), ),
}), }),
), ),
gpu: z.object({
layout: z
.array(
z.object({
brand: z.string(),
model: z.string().optional(),
}),
)
.default([]),
}),
}); });
const cpuLoadPerCoreApiList = z.array(cpuLoadPerCoreApi); const cpuLoadPerCoreApiList = z.array(cpuLoadPerCoreApi);
const gpuLoadApi = z.object({
layout: z.array(
z.object({
load: z.number().min(0).optional(),
memory: z.number().min(0).optional(),
}),
),
});
@@ -59,14 +59,6 @@ export class GlancesIntegration extends Integration implements ISystemHealthMoni
loadAverage: null, loadAverage: null,
smart: [], smart: [],
cpuTemp: undefined, cpuTemp: undefined,
gpu: stats.gpu.map((gpu) => ({
gpuId: gpu.gpu_id,
name: gpu.name,
memoryUtilization: gpu.mem ?? 0,
processorUtilization: gpu.proc ?? 0,
temperature: gpu.temperature ?? null,
fanSpeed: gpu.fan_speed ?? null,
})),
}; };
} }
@@ -158,16 +150,4 @@ const allSchema = z.object({
quicklook: z.object({ quicklook: z.object({
cpu_name: z.string(), cpu_name: z.string(),
}), }),
gpu: z
.array(
z.object({
gpu_id: z.string(),
name: z.string(),
mem: z.number().nullable().optional(),
proc: z.number().nullable().optional(),
temperature: z.number().nullable().optional(),
fan_speed: z.number().nullable().optional(),
}),
)
.default([]),
}); });
@@ -31,14 +31,6 @@ export interface SystemHealthMonitoring {
overallStatus: string; overallStatus: string;
healthy: boolean; healthy: boolean;
}[]; }[];
gpu: {
gpuId: string;
name: string;
memoryUtilization: number;
processorUtilization: number;
temperature: number | null;
fanSpeed: number | null;
}[];
} }
// TODO: in the future decouple this from the Proxmox integration // TODO: in the future decouple this from the Proxmox integration
@@ -36,16 +36,6 @@ export class SystemHealthMonitoringMockService implements ISystemHealthMonitorin
healthy: true, healthy: true,
}, },
], ],
gpu: [
{
gpuId: "mock0",
name: "Mock GPU RTX 4090",
memoryUtilization: Math.floor(Math.random() * 100),
processorUtilization: Math.floor(Math.random() * 100),
temperature: Math.floor(Math.random() * 90),
fanSpeed: Math.floor(Math.random() * 2000),
},
],
}); });
} }
} }
@@ -5,10 +5,8 @@ import utc from "dayjs/plugin/utc";
import type { RequestInit as NodeFetchRequestInit } from "node-fetch"; import type { RequestInit as NodeFetchRequestInit } from "node-fetch";
import * as ical from "node-ical"; import * as ical from "node-ical";
import { DAVClient } from "tsdav"; import { DAVClient } from "tsdav";
import { z } from "zod";
import { ResponseError } from "@homarr/common/server"; import { createHttpsAgentAsync } from "@homarr/core/infrastructure/http";
import { createHttpsAgentAsync, fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import { HandleIntegrationErrors } from "../base/errors/decorator"; import { HandleIntegrationErrors } from "../base/errors/decorator";
@@ -18,21 +16,6 @@ import { Integration } from "../base/integration";
import type { TestingResult } from "../base/test-connection/test-connection-service"; import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../interfaces/calendar/calendar-integration"; import type { ICalendarIntegration } from "../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../interfaces/calendar/calendar-types"; import type { CalendarEvent } from "../interfaces/calendar/calendar-types";
import type { Notification } from "../interfaces/notifications/notification-types";
import type { INotificationsIntegration } from "../interfaces/notifications/notifications-integration";
const notificationSchema = z.object({
ocs: z.object({
data: z.array(
z.object({
notification_id: z.number(),
datetime: z.string(),
subject: z.string(),
message: z.string(),
}),
),
}),
});
const logger = createLogger({ module: "nextcloudIntegration" }); const logger = createLogger({ module: "nextcloudIntegration" });
@@ -40,7 +23,7 @@ dayjs.extend(utc);
dayjs.extend(timezone); dayjs.extend(timezone);
@HandleIntegrationErrors([integrationTsdavHttpErrorHandler]) @HandleIntegrationErrors([integrationTsdavHttpErrorHandler])
export class NextcloudIntegration extends Integration implements ICalendarIntegration, INotificationsIntegration { export class NextcloudIntegration extends Integration implements ICalendarIntegration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> { protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const client = await this.createCalendarClientAsync(await createHttpsAgentAsync(input.options)); const client = await this.createCalendarClientAsync(await createHttpsAgentAsync(input.options));
await client.login(); await client.login();
@@ -121,29 +104,6 @@ export class NextcloudIntegration extends Integration implements ICalendarIntegr
.flat(); .flat();
} }
public async getNotificationsAsync(): Promise<Notification[]> {
const url = this.url("/ocs/v2.php/apps/notifications/api/v2/notifications", { format: "json" });
const response = await fetchWithTrustedCertificatesAsync(url, {
headers: {
Authorization: `Basic ${Buffer.from(
`${this.getSecretValue("username")}:${this.getSecretValue("password")}`,
).toString("base64")}`,
"OCS-APIRequest": "true",
},
});
if (!response.ok) throw new ResponseError(response);
const json = notificationSchema.parse(await response.json());
return json.ocs.data.map((notification) => ({
id: String(notification.notification_id),
time: new Date(notification.datetime),
title: notification.subject,
body: notification.message,
}));
}
private async createCalendarClientAsync(agent?: Agent) { private async createCalendarClientAsync(agent?: Agent) {
return new DAVClient({ return new DAVClient({
serverUrl: this.integration.url, serverUrl: this.integration.url,
@@ -86,7 +86,6 @@ export class OpenMediaVaultIntegration extends Integration implements ISystemHea
cpuTemp: cpuTempResult.success ? cpuTempResult.data.response.cputemp : undefined, cpuTemp: cpuTempResult.success ? cpuTempResult.data.response.cputemp : undefined,
fileSystem, fileSystem,
smart, smart,
gpu: [], // OpenMediaVault does not expose GPU monitoring via its RPC API.
}; };
} }
@@ -297,7 +297,6 @@ export class TrueNasIntegration extends Integration implements ISystemHealthMoni
version: systemInformation.version, version: systemInformation.version,
cpuModelName: systemInformation.model, cpuModelName: systemInformation.model,
rebootRequired: false, rebootRequired: false,
gpu: [],
}; };
} }
@@ -70,7 +70,6 @@ export class UnraidIntegration extends Integration implements ISystemHealthMonit
// See ArrayDiskStatus from https://studio.apollographql.com/public/Unraid-API/variant/current/explorer // See ArrayDiskStatus from https://studio.apollographql.com/public/Unraid-API/variant/current/explorer
healthy: disk.status === "DISK_OK", healthy: disk.status === "DISK_OK",
})), })),
gpu: [],
}; };
} }
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@homarr/job-scheduler",
"version": "0.1.0",
"private": true,
"main": "src/index.ts",
"types": "src/index.ts",
"dependencies": {
"@homarr/common": "workspace:*",
"@homarr/core": "workspace:*",
"@homarr/cron-job-api": "workspace:*",
"@homarr/cron-jobs": "workspace:*",
"@homarr/cron-jobs-core": "workspace:*",
"@homarr/cron-job-status": "workspace:*",
"@homarr/db": "workspace:*",
"@homarr/redis": "workspace:*",
"cron-parser": "^4.9.0"
}
}
+114
View File
@@ -0,0 +1,114 @@
import { objectEntries, objectKeys } from "@homarr/common";
import { db } from "@homarr/db";
import { jobRegistry } from "@homarr/cron-jobs-core";
import type { JobCallback } from "@homarr/cron-jobs-core";
import type { Logger } from "@homarr/cron-jobs-core";
type Jobs<TAllowedNames extends string> = {
[name in TAllowedNames]: ReturnType<JobCallback<TAllowedNames, name>>;
};
export interface CreateCronJobGroupCreatorOptions {
logger: Logger;
}
export const createJobGroupCreator = <TAllowedNames extends string = string>(
options: CreateCronJobGroupCreatorOptions,
) => {
return <TJobs extends Jobs<TAllowedNames>>(jobs: TJobs) => {
options.logger.logDebug("Creating job group.", {
jobCount: Object.keys(jobs).length,
});
for (const [key, job] of objectEntries(jobs)) {
if (typeof key !== "string" || typeof job.name !== "string") continue;
options.logger.logDebug("Registering job in the job registry.", {
name: job.name,
});
jobRegistry.set(key, {
...job,
name: job.name,
});
}
return {
initializeAsync: async () => {
// No tasks to create, just ensure jobs are registered
const configurations = await db.query.cronJobConfigurations.findMany();
for (const job of jobs) {
const configuration = configurations.find(({ name }) => name === job.name);
if (configuration?.isEnabled === false) {
continue;
}
// Run onStart if needed
await job.onStartAsync();
}
},
startAsync: async (name: keyof TJobs) => {
// In new system, start means enable, but since we trigger manually, just log
const job = jobs[name];
if (!job) return;
options.logger.logInfo("Enabling cron job.", {
name: job.name,
});
await job.onStartAsync();
},
startAllAsync: async () => {
for (const job of Object.values(jobs)) {
options.logger.logInfo("Enabling cron job.", {
name: job.name,
});
await job.onStartAsync();
}
},
runManuallyAsync: async (name: keyof TJobs) => {
const job = jobs[name];
if (!job) return;
if (job.preventManualExecution) {
throw new Error(`The job "${job.name}" can not be executed manually.`);
}
options.logger.logInfo("Running cron job manually.", {
name: job.name,
});
await job.executeAsync();
},
stopAsync: async (name: keyof TJobs) => {
// In new system, stop means disable, but since no tasks, just log
const job = jobs[name];
if (!job) return;
options.logger.logInfo("Disabling cron job.", {
name: job.name,
});
},
stopAllAsync: async () => {
for (const job of Object.values(jobs)) {
options.logger.logInfo("Disabling cron job.", {
name: job.name,
});
}
},
getJobRegistry() {
// Return a map of jobs
const registry = new Map();
for (const [key, job] of objectEntries(jobs)) {
registry.set(key, job);
}
return registry;
},
getTask() {
// No tasks in new system
return null;
},
setTask() {
// No tasks
},
getKeys() {
return objectKeys(jobs);
},
};
};
};
+1
View File
@@ -0,0 +1 @@
export { JobManager } from "./job-manager";
@@ -1,4 +1,4 @@
import { schedule, validate as validateCron } from "node-cron"; import { parseExpression } from "cron-parser";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import type { IJobManager } from "@homarr/cron-job-api"; import type { IJobManager } from "@homarr/cron-job-api";
@@ -10,58 +10,103 @@ import { cronJobConfigurations } from "@homarr/db/schema";
const logger = createLogger({ module: "jobManager" }); const logger = createLogger({ module: "jobManager" });
export class JobManager implements IJobManager { export class JobManager implements IJobManager {
private runningJobs = new Set<string>();
constructor( constructor(
private db: Database, private db: Database,
private jobGroup: typeof cronJobGroup, private jobGroup: typeof cronJobGroup,
) {} ) {}
public async startAsync(name: JobGroupKeys): Promise<void> { public async startAsync(name: JobGroupKeys): Promise<void> {
await this.jobGroup.startAsync(name); // In the new system, start just means enable
await this.enableAsync(name);
} }
public async triggerAsync(name: JobGroupKeys): Promise<void> { public async triggerAsync(name: JobGroupKeys): Promise<void> {
await this.jobGroup.runManuallyAsync(name); await this.jobGroup.runManuallyAsync(name);
} }
public async stopAsync(name: JobGroupKeys): Promise<void> { public async stopAsync(name: JobGroupKeys): Promise<void> {
await this.jobGroup.stopAsync(name); // In the new system, stop means disable
await this.disableAsync(name);
} }
public async updateIntervalAsync(name: JobGroupKeys, cron: string): Promise<void> { public async updateIntervalAsync(name: JobGroupKeys, cron: string): Promise<void> {
logger.info("Updating cron job interval", { name, expression: cron }); logger.info("Updating cron job interval", { name, expression: cron });
const job = this.jobGroup.getJobRegistry().get(name); const job = this.jobGroup.getJobRegistry().get(name);
if (!job) throw new Error(`Job ${name} not found`); if (!job) throw new Error(`Job ${name} not found`);
if (!validateCron(cron)) {
// Validate cron expression
try {
parseExpression(cron);
} catch {
throw new Error(`Invalid cron expression: ${cron}`); throw new Error(`Invalid cron expression: ${cron}`);
} }
if (job.preventCustomInterval && cron !== job.cronExpression) { if (job.preventCustomInterval && cron !== job.cronExpression) {
throw new Error(`Custom cron expressions are not allowed for job ${name}`); throw new Error(`Custom cron expressions are not allowed for job ${name}`);
} }
await this.updateConfigurationAsync(name, { cronExpression: cron }); await this.updateConfigurationAsync(name, { cronExpression: cron });
await this.jobGroup.getTask(name)?.destroy();
this.jobGroup.setTask(
name,
schedule(cron, () => void job.executeAsync(), {
name,
}),
);
logger.info("Cron job interval updated", { name, expression: cron }); logger.info("Cron job interval updated", { name, expression: cron });
} }
public async disableAsync(name: JobGroupKeys): Promise<void> { public async disableAsync(name: JobGroupKeys): Promise<void> {
logger.info("Disabling cron job", { name }); logger.info("Disabling cron job", { name });
const job = this.jobGroup.getJobRegistry().get(name); const job = this.jobGroup.getJobRegistry().get(name);
if (!job) throw new Error(`Job ${name} not found`); if (!job) throw new Error(`Job ${name} not found`);
await this.updateConfigurationAsync(name, { isEnabled: false }); await this.updateConfigurationAsync(name, { isEnabled: false });
await this.jobGroup.stopAsync(name);
logger.info("Cron job disabled", { name }); logger.info("Cron job disabled", { name });
} }
public async enableAsync(name: JobGroupKeys): Promise<void> { public async enableAsync(name: JobGroupKeys): Promise<void> {
logger.info("Enabling cron job", { name }); logger.info("Enabling cron job", { name });
await this.updateConfigurationAsync(name, { isEnabled: true }); await this.updateConfigurationAsync(name, { isEnabled: true });
await this.jobGroup.startAsync(name);
logger.info("Cron job enabled", { name }); logger.info("Cron job enabled", { name });
} }
// New method to trigger jobs based on current time
public async triggerJobsAsync(): Promise<void> {
const jobs = await this.getAllAsync();
const now = new Date();
for (const jobInfo of jobs) {
if (!jobInfo.isEnabled) continue;
if (this.runningJobs.has(jobInfo.name)) continue; // Prevent parallel execution
try {
const cronExpression = jobInfo.cron;
const interval = parseExpression(cronExpression);
const nextRun = interval.next();
const prevRun = interval.prev();
// Check if current time matches the cron (within a small tolerance)
const timeDiff = Math.abs(now.getTime() - nextRun.getTime());
if (timeDiff < 1000) { // Within 1 second
await this.executeJobAsync(jobInfo.name);
}
} catch (error) {
logger.error("Error checking job schedule", { name: jobInfo.name, error });
}
}
}
private async executeJobAsync(name: string): Promise<void> {
if (this.runningJobs.has(name)) return;
this.runningJobs.add(name);
try {
logger.info("Executing scheduled job", { name });
await this.jobGroup.runManuallyAsync(name as JobGroupKeys);
logger.info("Job executed successfully", { name });
} catch (error) {
logger.error("Job execution failed", { name, error });
} finally {
this.runningJobs.delete(name);
}
}
private async updateConfigurationAsync( private async updateConfigurationAsync(
name: JobGroupKeys, name: JobGroupKeys,
configuration: Omit<Partial<InferInsertModel<typeof cronJobConfigurations>>, "name">, configuration: Omit<Partial<InferInsertModel<typeof cronJobConfigurations>>, "name">,
@@ -79,7 +124,6 @@ export class JobManager implements IJobManager {
if (existingConfig) { if (existingConfig) {
await this.db await this.db
.update(cronJobConfigurations) .update(cronJobConfigurations)
// prevent updating the name, as it is the primary key
.set({ ...configuration, name: undefined }) .set({ ...configuration, name: undefined })
.where(eq(cronJobConfigurations.name, name)); .where(eq(cronJobConfigurations.name, name));
logger.debug("Cron job configuration updated", { logger.debug("Cron job configuration updated", {
@@ -97,7 +141,7 @@ export class JobManager implements IJobManager {
cronExpression: configuration.cronExpression ?? job.cronExpression, cronExpression: configuration.cronExpression ?? job.cronExpression,
isEnabled: configuration.isEnabled ?? true, isEnabled: configuration.isEnabled ?? true,
}); });
logger.debug("Cron job configuration updated", { logger.debug("Cron job configuration created", {
name, name,
configuration: JSON.stringify(configuration), configuration: JSON.stringify(configuration),
}); });
+1 -1
View File
@@ -36,7 +36,7 @@
"@mantine/core": "^8.3.18", "@mantine/core": "^8.3.18",
"@tabler/icons-react": "^3.40.0", "@tabler/icons-react": "^3.40.0",
"dayjs": "^1.11.20", "dayjs": "^1.11.20",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"zod": "^4.2.1" "zod": "^4.2.1"
@@ -57,12 +57,10 @@ export const AddBoardModal = createModal(({ actions }) => {
{...form.getInputProps("name")} {...form.getInputProps("name")}
description={ description={
boardNameStatus.description ? ( boardNameStatus.description ? (
<span> <Group c={boardNameStatus.description.color} gap="xs" align="center">
<Group c={boardNameStatus.description.color} gap="xs" align="center"> {boardNameStatus.description.icon ? <boardNameStatus.description.icon size={16} /> : null}
{boardNameStatus.description.icon ? <boardNameStatus.description.icon size={16} /> : null} <span>{boardNameStatus.description.label}</span>
<span>{boardNameStatus.description.label}</span> </Group>
</Group>
</span>
) : null ) : null
} }
/> />
@@ -21,7 +21,7 @@ export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(
{ {
initialValues: { initialValues: {
containerUrls: innerProps.selectedContainers.map((container) => { containerUrls: innerProps.selectedContainers.map((container) => {
if (Array.isArray(container.ports) && container.ports[0]) { if (container.ports[0]) {
return `http://${container.ports[0].IP}:${container.ports[0].PublicPort}`; return `http://${container.ports[0].IP}:${container.ports[0].PublicPort}`;
} }
+1 -1
View File
@@ -40,7 +40,7 @@
"@mantine/core": "^8.3.18", "@mantine/core": "^8.3.18",
"@mantine/hooks": "^8.3.18", "@mantine/hooks": "^8.3.18",
"adm-zip": "0.5.16", "adm-zip": "0.5.16",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"superjson": "2.2.6", "superjson": "2.2.6",
@@ -101,7 +101,6 @@ const optionMapping: OptionMapping = {
allowMicrophone: (oldOptions) => oldOptions.allowMicrophone, allowMicrophone: (oldOptions) => oldOptions.allowMicrophone,
allowGeolocation: (oldOptions) => oldOptions.allowGeolocation, allowGeolocation: (oldOptions) => oldOptions.allowGeolocation,
allowScrolling: (oldOptions) => oldOptions.allowScrolling, allowScrolling: (oldOptions) => oldOptions.allowScrolling,
allowModals: () => undefined,
}, },
video: { video: {
feedUrl: (oldOptions) => oldOptions.FeedUrl, feedUrl: (oldOptions) => oldOptions.FeedUrl,
@@ -162,7 +161,6 @@ const optionMapping: OptionMapping = {
sectionIndicatorRequirement: (oldOptions) => sectionIndicatorRequirement: (oldOptions) =>
"sectionIndicatorColor" in oldOptions ? oldOptions.sectionIndicatorColor : undefined, "sectionIndicatorColor" in oldOptions ? oldOptions.sectionIndicatorColor : undefined,
showUptime: () => undefined, showUptime: () => undefined,
gpu: () => undefined,
visibleClusterSections: (oldOptions) => { visibleClusterSections: (oldOptions) => {
if (!("showNode" in oldOptions)) return undefined; if (!("showNode" in oldOptions)) return undefined;
+1 -1
View File
@@ -33,7 +33,7 @@
"dayjs": "^1.11.20", "dayjs": "^1.11.20",
"octokit": "^5.0.5", "octokit": "^5.0.5",
"superjson": "2.2.6", "superjson": "2.2.6",
"undici": "7.24.5", "undici": "7.18.2",
"zod": "^4.2.1" "zod": "^4.2.1"
}, },
"devDependencies": { "devDependencies": {
+1 -2
View File
@@ -1,6 +1,5 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import type { ContainerInfo, ContainerStats } from "dockerode"; import type { ContainerInfo, ContainerStats } from "dockerode";
import type Dockerode from "dockerode";
import { db, like, or } from "@homarr/db"; import { db, like, or } from "@homarr/db";
import { icons } from "@homarr/db/schema"; import { icons } from "@homarr/db/schema";
@@ -73,7 +72,7 @@ async function getContainersWithStatsAsync() {
cpuUsage, cpuUsage,
memoryUsage, memoryUsage,
image: container.Image, image: container.Image,
ports: container.Ports as Dockerode.Port[] | undefined, ports: container.Ports,
}; };
}); });
+1 -1
View File
@@ -26,7 +26,7 @@
"@homarr/db": "workspace:^0.1.0", "@homarr/db": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0", "@homarr/server-settings": "workspace:^0.1.0",
"@mantine/dates": "^8.3.18", "@mantine/dates": "^8.3.18",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4" "react-dom": "19.2.4"
}, },
+1 -1
View File
@@ -38,7 +38,7 @@
"@mantine/spotlight": "^8.3.18", "@mantine/spotlight": "^8.3.18",
"@tabler/icons-react": "^3.40.0", "@tabler/icons-react": "^3.40.0",
"jotai": "^2.18.1", "jotai": "^2.18.1",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"use-deep-compare-effect": "^1.8.1" "use-deep-compare-effect": "^1.8.1"
@@ -94,6 +94,7 @@ const createSpotlightContext = (displayName: string) => {
context.unregisterItems(key); context.unregisterItems(key);
}; };
// We ignore the results // We ignore the results
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...dependencyArray, key]); }, [...dependencyArray, key]);
}; };
+1 -1
View File
@@ -32,7 +32,7 @@
"dayjs": "^1.11.20", "dayjs": "^1.11.20",
"deepmerge": "4.3.1", "deepmerge": "4.3.1",
"mantine-react-table": "2.0.0-beta.9", "mantine-react-table": "2.0.0-beta.9",
"next": "16.2.1", "next": "16.2.0",
"next-intl": "4.8.3", "next-intl": "4.8.3",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4" "react-dom": "19.2.4"
+50 -50
View File
@@ -1746,114 +1746,114 @@
"name": "Calendar", "name": "Calendar",
"description": "Display events from your integrations in a calendar view within a certain relative time period", "description": "Display events from your integrations in a calendar view within a certain relative time period",
"duration": { "duration": {
"allDay": "All day" "allDay": ""
}, },
"option": { "option": {
"releaseType": { "releaseType": {
"label": "Radarr release type", "label": "",
"options": { "options": {
"inCinemas": "In cinemas", "inCinemas": "",
"digitalRelease": "Digital release", "digitalRelease": "",
"physicalRelease": "Physical release" "physicalRelease": ""
} }
}, },
"filterPastMonths": { "filterPastMonths": {
"label": "Start from" "label": ""
}, },
"filterFutureMonths": { "filterFutureMonths": {
"label": "End at" "label": ""
}, },
"showUnmonitored": { "showUnmonitored": {
"label": "Show unmonitored" "label": ""
} }
} }
}, },
"weather": { "weather": {
"name": "Weather", "name": "",
"description": "Displays the current weather information of a set location.", "description": "",
"option": { "option": {
"isFormatFahrenheit": { "isFormatFahrenheit": {
"label": "Temperature in Fahrenheit" "label": ""
}, },
"disableTemperatureDecimals": { "disableTemperatureDecimals": {
"label": "Disable temperature decimals" "label": ""
}, },
"showCurrentWindSpeed": { "showCurrentWindSpeed": {
"label": "Show current wind speed", "label": "",
"description": "Only on current weather" "description": ""
}, },
"useImperialSpeed": { "useImperialSpeed": {
"label": "Use mph for windspeed" "label": ""
}, },
"location": { "location": {
"label": "Weather location" "label": ""
}, },
"showCity": { "showCity": {
"label": "Show city" "label": ""
}, },
"hasForecast": { "hasForecast": {
"label": "Show forecast" "label": ""
}, },
"forecastDayCount": { "forecastDayCount": {
"label": "Amount of forecast days", "label": "",
"description": "When the widget is not wide enough, less days are shown" "description": ""
}, },
"dateFormat": { "dateFormat": {
"label": "Date Format", "label": "",
"description": "How the date should look like" "description": ""
} }
}, },
"currentWindSpeed": "{currentWindSpeed} {unit}", "currentWindSpeed": "",
"dailyForecast": { "dailyForecast": {
"sunrise": "Sunrise", "sunrise": "",
"sunset": "Sunset", "sunset": "",
"maxWindSpeed": "Max wind speed: {maxWindSpeed} {unit}", "maxWindSpeed": "",
"maxWindGusts": "Max wind gusts: {maxWindGusts} {unit}" "maxWindGusts": ""
}, },
"kind": { "kind": {
"clear": "Clear", "clear": "",
"mainlyClear": "Mainly clear", "mainlyClear": "",
"fog": "Fog", "fog": "",
"drizzle": "Drizzle", "drizzle": "",
"freezingDrizzle": "Freezing drizzle", "freezingDrizzle": "",
"rain": "Rain", "rain": "Rain",
"freezingRain": "Freezing rain", "freezingRain": "Freezing rain",
"snowFall": "Snow fall", "snowFall": "Snow fall",
"snowGrains": "Snow grains", "snowGrains": "",
"rainShowers": "Rain showers", "rainShowers": "",
"snowShowers": "Snow showers", "snowShowers": "",
"thunderstorm": "Thunderstorm", "thunderstorm": "",
"thunderstormWithHail": "Thunderstorm with hail", "thunderstormWithHail": "",
"unknown": "Unknown" "unknown": ""
} }
}, },
"indexerManager": { "indexerManager": {
"name": "Indexer manager status", "name": "",
"description": "Status of your indexers", "description": "",
"option": { "option": {
"openIndexerSiteInNewTab": { "openIndexerSiteInNewTab": {
"label": "Open indexer site in new tab" "label": ""
} }
}, },
"title": "Indexer manager", "title": "",
"testAll": "Test all", "testAll": "",
"error": { "error": {
"internalServerError": "Failed to fetch indexers status" "internalServerError": ""
} }
}, },
"healthMonitoring": { "healthMonitoring": {
"name": "System Health Monitoring", "name": "",
"description": "Displays information showing the health and status of your system(s).", "description": "",
"tab": { "tab": {
"system": "System", "system": "",
"cluster": "Cluster" "cluster": ""
}, },
"option": { "option": {
"fahrenheit": { "fahrenheit": {
"label": "CPU Temp in Fahrenheit" "label": ""
}, },
"cpu": { "cpu": {
"label": "Show CPU Info" "label": ""
}, },
"memory": { "memory": {
"label": "" "label": ""
+1 -8
View File
@@ -1625,9 +1625,6 @@
}, },
"allowGeolocation": { "allowGeolocation": {
"label": "Allow geolocation" "label": "Allow geolocation"
},
"allowModals": {
"label": "Allow modals"
} }
}, },
"error": { "error": {
@@ -1861,9 +1858,6 @@
"memory": { "memory": {
"label": "Show Memory Info" "label": "Show Memory Info"
}, },
"gpu": {
"label": "Show GPU Info"
},
"showUptime": { "showUptime": {
"label": "Show Uptime" "label": "Show Uptime"
}, },
@@ -2039,6 +2033,7 @@
"directStream": "Direct Stream" "directStream": "Direct Stream"
} }
}, },
"recentActivity": { "recentActivity": {
"title": "Recent Activity", "title": "Recent Activity",
"empty": "No recent activity", "empty": "No recent activity",
@@ -2731,7 +2726,6 @@
"option": { "option": {
"cpu": "CPU", "cpu": "CPU",
"memory": "Memory", "memory": "Memory",
"gpu": "GPU",
"network": "Network" "network": "Network"
} }
}, },
@@ -2748,7 +2742,6 @@
"card": { "card": {
"cpu": "CPU", "cpu": "CPU",
"memory": "MEM", "memory": "MEM",
"gpu": "GPU",
"network": "NET", "network": "NET",
"up": "UP", "up": "UP",
"down": "DOWN" "down": "DOWN"
+11 -11
View File
@@ -27,7 +27,7 @@
"description": "Configurer le comportement d'importation" "description": "Configurer le comportement d'importation"
}, },
"boardSelection": { "boardSelection": {
"title": "{count} tableaux trouvés", "title": "Tableaux {count} trouvés",
"description": "Choisissez tous les tableaux avec la taille que vous souhaitez importer", "description": "Choisissez tous les tableaux avec la taille que vous souhaitez importer",
"action": { "action": {
"selectAll": "Tout sélectionner", "selectAll": "Tout sélectionner",
@@ -1997,20 +1997,20 @@
} }
}, },
"tracearr": { "tracearr": {
"name": "Tracearr", "name": "",
"description": "Surveillance avancée du serveur multimédia avec des données détaillées de flux et de transcodage", "description": "",
"option": { "option": {
"showStreams": { "showStreams": {
"label": "" "label": ""
}, },
"showStats": { "showStats": {
"label": "Afficher le résumé des statistiques" "label": ""
}, },
"showRecentActivity": { "showRecentActivity": {
"label": "Afficher l'activité récente" "label": "Afficher l'activité récente"
}, },
"showViolations": { "showViolations": {
"label": "Afficher les violations" "label": ""
} }
}, },
"stats": { "stats": {
@@ -2022,7 +2022,7 @@
"streams": { "streams": {
"empty": "", "empty": "",
"user": "Utilisateur", "user": "Utilisateur",
"media": "Média", "media": "",
"state": "", "state": "",
"quality": "Qualité", "quality": "Qualité",
"device": "Appareil", "device": "Appareil",
@@ -2040,15 +2040,15 @@
"partial": "" "partial": ""
}, },
"violations": { "violations": {
"title": "Violations", "title": "",
"empty": "Aucune violation récente", "empty": "",
"rule": "Règle", "rule": "Règle",
"user": "Utilisateur" "user": "Utilisateur"
}, },
"noSectionsEnabled": "", "noSectionsEnabled": "",
"error": { "error": {
"noIntegration": "Aucune intégration Tracearr configurée", "noIntegration": "",
"internalServerError": "Impossible de récupérer les données de Tracearr" "internalServerError": ""
} }
}, },
"common": { "common": {
@@ -3575,7 +3575,7 @@
"label": "Météo" "label": "Météo"
}, },
"tracearr": { "tracearr": {
"label": "Tracearr" "label": ""
} }
}, },
"interval": { "interval": {
+1 -1
View File
@@ -36,7 +36,7 @@
"@tabler/icons-react": "^3.40.0", "@tabler/icons-react": "^3.40.0",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"mantine-react-table": "2.0.0-beta.9", "mantine-react-table": "2.0.0-beta.9",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"svgson": "^5.3.1" "svgson": "^5.3.1"
@@ -1,14 +0,0 @@
/**
* Sanitizes the URL from malicious payloads.
* Prevents open redirects such as //example.com/path
* and prevents XSS such as javascript:().
* Returns / as a default or when unsafe.
* @param url The URL to sanitize
*/
export const sanitizeRedirectionUrl = (url?: string) => {
if (url && url.startsWith("/") && !url.startsWith("//")) {
return url;
} else {
return "/"; // Safe default
}
};
+1 -1
View File
@@ -72,7 +72,7 @@
"dayjs": "^1.11.20", "dayjs": "^1.11.20",
"mantine-form-zod-resolver": "^1.3.0", "mantine-form-zod-resolver": "^1.3.0",
"mantine-react-table": "2.0.0-beta.9", "mantine-react-table": "2.0.0-beta.9",
"next": "16.2.1", "next": "16.2.0",
"react": "19.2.4", "react": "19.2.4",
"react-dom": "19.2.4", "react-dom": "19.2.4",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
@@ -19,9 +19,6 @@ export const { definition, componentLoader } = createWidgetDefinition("healthMon
memory: factory.switch({ memory: factory.switch({
defaultValue: true, defaultValue: true,
}), }),
gpu: factory.switch({
defaultValue: true,
}),
showUptime: factory.switch({ showUptime: factory.switch({
defaultValue: true, defaultValue: true,
}), }),
@@ -1,64 +0,0 @@
import { Center, RingProgress, Stack, Text, Tooltip } from "@mantine/core";
import { IconDeviceDesktop } from "@tabler/icons-react";
import { progressColor } from "../system-health";
interface GpuRingProps {
gpu: {
gpuId: string;
name: string;
memoryUtilization: number;
processorUtilization: number;
temperature: number | null;
fanSpeed: number | null;
};
isTiny: boolean;
fahrenheit: boolean;
}
export const GpuRing = ({ gpu, isTiny, fahrenheit }: GpuRingProps) => {
const tempDisplay =
gpu.temperature != null
? fahrenheit
? `${(gpu.temperature * 1.8 + 32).toFixed(0)}°F`
: `${gpu.temperature}°C`
: null;
return (
<Tooltip
label={
<Stack gap={2}>
<Text size="xs" fw={600}>
{gpu.name}
</Text>
<Text size="xs">VRAM: {gpu.memoryUtilization.toFixed(1)}%</Text>
{tempDisplay && <Text size="xs">Temp: {tempDisplay}</Text>}
{gpu.fanSpeed != null && <Text size="xs">Fan: {gpu.fanSpeed} RPM</Text>}
</Stack>
}
multiline
>
<RingProgress
className={`health-monitoring-gpu health-monitoring-gpu-${gpu.gpuId}`}
roundCaps
size={isTiny ? 50 : 100}
thickness={isTiny ? 4 : 8}
label={
<Center style={{ flexDirection: "column" }}>
<Text
className="health-monitoring-gpu-utilization-value"
size={isTiny ? "8px" : "xs"}
>{`${gpu.processorUtilization.toFixed(0)}%`}</Text>
<IconDeviceDesktop className="health-monitoring-gpu-utilization-icon" size={isTiny ? 8 : 16} />
</Center>
}
sections={[
{
value: Number(gpu.processorUtilization.toFixed(2)),
color: progressColor(Number(gpu.processorUtilization.toFixed(2))),
},
]}
/>
</Tooltip>
);
};
@@ -39,7 +39,6 @@ import { useI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
import { CpuRing } from "./rings/cpu-ring"; import { CpuRing } from "./rings/cpu-ring";
import { CpuTempRing } from "./rings/cpu-temp-ring"; import { CpuTempRing } from "./rings/cpu-temp-ring";
import { GpuRing } from "./rings/gpu-ring";
import { formatMemoryUsage, MemoryRing } from "./rings/memory-ring"; import { formatMemoryUsage, MemoryRing } from "./rings/memory-ring";
import classes from "./system-health.module.css"; import classes from "./system-health.module.css";
@@ -188,10 +187,6 @@ export const SystemHealthMonitoring = ({
isTiny={isTiny} isTiny={isTiny}
/> />
)} )}
{options.gpu &&
healthInfo.gpu.map((gpu) => (
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
))}
</Flex> </Flex>
{ {
<Text className="health-monitoring-status-update-time" c="dimmed" size="xs" ta="center"> <Text className="health-monitoring-status-update-time" c="dimmed" size="xs" ta="center">
@@ -105,10 +105,6 @@ const getSandboxFlags = (
baseSandbox.push("allow-popups-to-escape-sandbox"); baseSandbox.push("allow-popups-to-escape-sandbox");
} }
if (permissions.allowModals) {
baseSandbox.push("allow-modals");
}
return baseSandbox; return baseSandbox;
}; };
@@ -119,5 +115,4 @@ const permissionMapping = {
allowGeolocation: "geolocation", allowGeolocation: "geolocation",
allowMicrophone: "microphone", allowMicrophone: "microphone",
allowPayment: "payment", allowPayment: "payment",
allowModals: "allow-modals",
} satisfies Record<keyof Omit<WidgetComponentProps<"iframe">["options"], "embedUrl" | "allowScrolling">, string>; } satisfies Record<keyof Omit<WidgetComponentProps<"iframe">["options"], "embedUrl" | "allowScrolling">, string>;
-1
View File
@@ -17,7 +17,6 @@ export const { definition, componentLoader } = createWidgetDefinition("iframe",
allowMicrophone: factory.switch(), allowMicrophone: factory.switch(),
allowCamera: factory.switch(), allowCamera: factory.switch(),
allowGeolocation: factory.switch(), allowGeolocation: factory.switch(),
allowModals: factory.switch(),
})); }));
}, },
}).withDynamicImport(() => import("./component")); }).withDynamicImport(() => import("./component"));
@@ -1,52 +0,0 @@
import { Paper, Text } from "@mantine/core";
import { IconDeviceDesktop } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import type { LabelDisplayModeOption } from "..";
import { CommonChart } from "./common-chart";
export const SystemResourceGPUChart = ({
gpuUsageOverTime,
hasShadow,
labelDisplayMode,
}: {
gpuUsageOverTime: number[];
hasShadow: boolean;
labelDisplayMode: LabelDisplayModeOption;
}) => {
const chartData = gpuUsageOverTime.map((usage, index) => ({ index, usage }));
const t = useScopedI18n("widget.systemResources.card");
return (
<CommonChart
data={chartData}
dataKey={"index"}
series={[{ name: "usage", color: "grape.5" }]}
title={t("gpu")}
icon={IconDeviceDesktop}
lastValue={
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
gpuUsageOverTime.length > 0 ? `${Math.round(gpuUsageOverTime[gpuUsageOverTime.length - 1]!)}%` : undefined
}
chartType={hasShadow ? "area" : "line"}
yAxisProps={{ domain: [0, 100] }}
labelDisplayMode={labelDisplayMode}
tooltipProps={{
content: ({ payload }) => {
if (!payload) {
return null;
}
const value = payload[0] ? Number(payload[0].value) : 0;
return (
<Paper px={3} py={2} withBorder shadow="md" radius="md">
<Text c="dimmed" size="xs">
{value.toFixed(0)}%
</Text>
</Paper>
);
},
}}
/>
);
};
@@ -9,7 +9,6 @@ import { clientApi } from "@homarr/api/client";
import type { WidgetComponentProps } from "../definition"; import type { WidgetComponentProps } from "../definition";
import { CombinedNetworkTrafficChart } from "./chart/combined-network-traffic"; import { CombinedNetworkTrafficChart } from "./chart/combined-network-traffic";
import { SystemResourceCPUChart } from "./chart/cpu-chart"; import { SystemResourceCPUChart } from "./chart/cpu-chart";
import { SystemResourceGPUChart } from "./chart/gpu-chart";
import { SystemResourceMemoryChart } from "./chart/memory-chart"; import { SystemResourceMemoryChart } from "./chart/memory-chart";
import { NetworkTrafficChart } from "./chart/network-traffic"; import { NetworkTrafficChart } from "./chart/network-traffic";
@@ -24,16 +23,10 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
const memoryCapacityInBytes = const memoryCapacityInBytes =
(data[0]?.healthInfo.memAvailableInBytes ?? 0) + (data[0]?.healthInfo.memUsedInBytes ?? 0); (data[0]?.healthInfo.memAvailableInBytes ?? 0) + (data[0]?.healthInfo.memUsedInBytes ?? 0);
const [items, setItems] = useState< const [items, setItems] = useState<{ cpu: number; memory: number; network: { up: number; down: number } | null }[]>(
{ cpu: number; memory: number; gpu: number; network: { up: number; down: number } | null }[]
>(
data.map((item) => ({ data.map((item) => ({
cpu: item.healthInfo.cpuUtilization, cpu: item.healthInfo.cpuUtilization,
memory: item.healthInfo.memUsedInBytes, memory: item.healthInfo.memUsedInBytes,
gpu:
item.healthInfo.gpu.length > 0
? item.healthInfo.gpu.reduce((acc, g) => acc + g.processorUtilization, 0) / item.healthInfo.gpu.length
: 0,
network: item.healthInfo.network, network: item.healthInfo.network,
})), })),
); );
@@ -48,10 +41,6 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
const next = { const next = {
cpu: data.healthInfo.cpuUtilization, cpu: data.healthInfo.cpuUtilization,
memory: data.healthInfo.memUsedInBytes, memory: data.healthInfo.memUsedInBytes,
gpu:
data.healthInfo.gpu.length > 0
? data.healthInfo.gpu.reduce((acc, g) => acc + g.processorUtilization, 0) / data.healthInfo.gpu.length
: 0,
network: data.healthInfo.network, network: data.healthInfo.network,
}; };
@@ -86,15 +75,6 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
/> />
</Box> </Box>
)} )}
{options.visibleCharts.includes("gpu") && (
<Box h={rowHeight}>
<SystemResourceGPUChart
gpuUsageOverTime={items.map((item) => item.gpu)}
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
</Box>
)}
{showNetwork && {showNetwork &&
(width > 256 ? ( (width > 256 ? (
<Group h={rowHeight} gap="xs" grow> <Group h={rowHeight} gap="xs" grow>
@@ -19,7 +19,7 @@ export const { definition, componentLoader } = createWidgetDefinition("systemRes
return optionsBuilder.from((factory) => ({ return optionsBuilder.from((factory) => ({
hasShadow: factory.switch({ defaultValue: true }), hasShadow: factory.switch({ defaultValue: true }),
visibleCharts: factory.multiSelect({ visibleCharts: factory.multiSelect({
options: (["cpu", "memory", "gpu", "network"] as const).map((key) => ({ options: (["cpu", "memory", "network"] as const).map((key) => ({
value: key, value: key,
label: (t) => t(`widget.systemResources.option.visibleCharts.option.${key}`), label: (t) => t(`widget.systemResources.option.visibleCharts.option.${key}`),
})), })),
+1
View File
@@ -79,6 +79,7 @@ const Feed = ({ options }: Pick<WidgetComponentProps<"video">, "options">) => {
], ],
}); });
// All other properties are updated with other useEffect // All other properties are updated with other useEffect
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [videoRef]); }, [videoRef]);
useEffect(() => { useEffect(() => {
+267 -246
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
const http = require('http');
function triggerJobs() {
const options = {
hostname: 'localhost',
port: 3000,
path: '/api/internal/trigger-jobs',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-internal-request': 'true'
}
};
const req = http.request(options, (res) => {
if (res.statusCode !== 200) {
console.error(`Failed to trigger jobs: ${res.statusCode}`);
}
});
req.on('error', (err) => {
console.error('Error triggering jobs:', err);
});
req.end();
}
// Trigger jobs every second
setInterval(triggerJobs, 1000);
// Initial trigger
triggerJobs();
+8 -1
View File
@@ -54,10 +54,17 @@ WSS_PID=$!
node apps/nextjs/server.js & node apps/nextjs/server.js &
NEXTJS_PID=$! NEXTJS_PID=$!
# Wait a bit for NextJS to start
sleep 5
# Start job scheduler
node scripts/job-scheduler.js &
SCHEDULER_PID=$!
# Function to handle SIGTERM and shut down services # Function to handle SIGTERM and shut down services
terminate() { terminate() {
echo "Received SIGTERM. Shutting down..." echo "Received SIGTERM. Shutting down..."
kill -TERM $NGINX_PID $TASKS_PID $WSS_PID $NEXTJS_PID 2>/dev/null kill -TERM $NGINX_PID $SCHEDULER_PID $WSS_PID $NEXTJS_PID 2>/dev/null
wait wait
# kill redis-server last because of logging of other services and only if $REDIS_PID is set # kill redis-server last because of logging of other services and only if $REDIS_PID is set
if [ -n "$REDIS_PID" ]; then if [ -n "$REDIS_PID" ]; then
+1 -1
View File
@@ -17,7 +17,7 @@
}, },
"prettier": "@homarr/prettier-config", "prettier": "@homarr/prettier-config",
"dependencies": { "dependencies": {
"@next/eslint-plugin-next": "16.2.1", "@next/eslint-plugin-next": "16.2.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-config-turbo": "^2.8.20", "eslint-config-turbo": "^2.8.20",
"eslint-plugin-import": "^2.32.0", "eslint-plugin-import": "^2.32.0",