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
47 changed files with 440 additions and 409 deletions

No files matched your search

+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/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/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
# Automatically leverage output traces to reduce image size
@@ -13,7 +13,6 @@ import type { useForm } from "@homarr/form";
import { useZodForm } from "@homarr/form";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
import { sanitizeRedirectionUrl } from "@homarr/validation/redirection-url";
import { userSignInSchema } from "@homarr/validation/user";
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.
await revalidatePathActionAsync("/");
router.push(sanitizeRedirectionUrl(callbackUrl));
router.push(callbackUrl);
},
[t, router, callbackUrl],
);
@@ -4,7 +4,6 @@ import { Card, Center, Stack, Text, Title } from "@mantine/core";
import { env } from "@homarr/auth/env";
import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { sanitizeRedirectionUrl } from "@homarr/validation/redirection-url";
import { HomarrLogoWithTitle } from "~/components/layout/logo/homarr-logo";
import { LoginForm } from "./_login-form";
@@ -20,7 +19,7 @@ export default async function Login(props: LoginProps) {
const session = await auth();
if (session) {
redirect(sanitizeRedirectionUrl(searchParams.callbackUrl));
redirect(searchParams.callbackUrl ?? "/");
}
const t = await getScopedI18n("user.page.login");
@@ -264,5 +264,6 @@ const usePreventLeaveWithDirty = (isDirty: boolean) => {
window.removeEventListener("popstate", handlePopState);
window.removeEventListener("beforeunload", handleBeforeUnload);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDirty]);
};
@@ -27,6 +27,7 @@ export const BoardReadyProvider = ({ children }: PropsWithChildren) => {
useEffect(() => {
setReadySections((previous) => previous.filter((id) => board.sections.some((section) => section.id === id)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [board.sections.length, setReadySections]);
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 { SearchEngineOptimization } from "~/components/layout/search-engine-optimization";
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
import { initializeJobManager } from "~/lib/job-manager";
import { DayJsLoader } from "./_client-providers/dayjs-loader";
import { JotaiProvider } from "./_client-providers/jotai";
import { CustomMantineProvider } from "./_client-providers/mantine";
@@ -83,6 +84,9 @@ export default async function Layout(props: {
const colorScheme = await getCurrentColorSchemeAsync();
const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr";
// Initialize job manager
await initializeJobManager();
const StackedProvider = composeWrappers([
(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() {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
if (!session?.user || !session.user.permissions.includes("admin")) {
return {};
}
@@ -27,7 +27,7 @@ export async function generateMetadata() {
export default async function ApiPage() {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
if (!session?.user || !session.user.permissions.includes("admin")) {
notFound();
}
const document = openApiDocument(extractBaseUrlFromHeaders(await headers()));
@@ -18,7 +18,7 @@ import { LogContextProvider } from "./log-context";
export async function generateMetadata() {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
if (!session?.user || !session.user.permissions.includes("admin")) {
return {};
}
const t = await getScopedI18n("management");
@@ -30,7 +30,7 @@ export async function generateMetadata() {
export default async function LogsManagementPage() {
const session = await auth();
if (!session?.user.permissions.includes("other-view-logs")) {
if (!session?.user || !session.user.permissions.includes("other-view-logs")) {
notFound();
}
@@ -75,6 +75,7 @@ const executeHealthCheckSafelyAsync = async (
},
};
} catch (error) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
logger.error(new ErrorWithMetadata("Healthcheck failed", { name }, { cause: error }));
return {
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 { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
import { getJobManager } from "~/lib/job-manager";
const logger = createLogger({ module: "trpcRoute" });
@@ -45,7 +46,7 @@ const handler = auth(async (req) => {
endpoint: trpcPath,
router: appRouter,
req,
createContext: () => createTRPCContext({ session, headers: req.headers }),
createContext: () => createTRPCContext({ session, headers: req.headers, jobManager: getJobManager() }),
onError({ error, path, type }) {
logger.error(new ErrorWithMetadata("tRPC Error occured", { path, type }, { cause: error }));
},
@@ -117,6 +117,7 @@ const InnerContent = ({ item, ...dimensions }: InnerContentProps) => {
when={
widgetSupportsIntegrations &&
item.integrationIds.length === 0 &&
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
(!("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
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [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"]
}
+14 -15
View File
@@ -3,7 +3,6 @@ import z from "zod/v4";
import { createLogger } from "@homarr/core/infrastructure/logs";
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 { createCronJobStatusChannel } from "@homarr/cron-job-status";
@@ -15,20 +14,20 @@ export const cronJobsRouter = createTRPCRouter({
triggerJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.trigger.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.triggerAsync(input);
}),
startJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.start.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.startAsync(input);
}),
stopJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.stop.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.stopAsync(input);
}),
updateJobInterval: permissionRequiredProcedure
.requiresPermission("admin")
@@ -38,23 +37,23 @@ export const cronJobsRouter = createTRPCRouter({
cron: cronExpressionSchema,
}),
)
.mutation(async ({ input }) => {
await cronJobApi.updateInterval.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.updateIntervalAsync(input.name, input.cron);
}),
disableJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.disable.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.disableAsync(input);
}),
enableJob: permissionRequiredProcedure
.requiresPermission("admin")
.input(jobNameSchema)
.mutation(async ({ input }) => {
await cronJobApi.enable.mutate(input);
.mutation(async ({ input, ctx }) => {
await ctx.jobManager.enableAsync(input);
}),
getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async () => {
return await cronJobApi.getAll.query();
getJobs: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
return await ctx.jobManager.getAllAsync();
}),
subscribeToStatusUpdates: permissionRequiredProcedure.requiresPermission("admin").subscription(() => {
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();
}),
});
+2 -1
View File
@@ -34,7 +34,7 @@ const logger = createLogger({ module: "trpc" });
*
* @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 source = opts.headers.get("x-trpc-source") ?? "unknown";
@@ -44,6 +44,7 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
session,
deviceType: userAgent(opts.headers).device.type,
db,
jobManager: opts.jobManager,
};
};
+1 -1
View File
@@ -34,7 +34,7 @@
"octokit": "^5.0.5",
"react": "19.2.4",
"react-dom": "19.2.4",
"undici": "7.24.5",
"undici": "7.18.2",
"zod": "^4.2.1",
"zod-validation-error": "^5.0.0"
},
+1 -28
View File
@@ -1,12 +1,9 @@
import { createTask, validate } from "node-cron";
import { Stopwatch } from "@homarr/common";
import type { MaybePromise } from "@homarr/common/types";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
import type { Logger } from "./logger";
import type { ValidateCron } from "./validation";
export interface CreateCronJobCreatorOptions<TAllowedNames extends string> {
beforeCallback?: (name: TAllowedNames) => MaybePromise<void>;
@@ -74,28 +71,6 @@ const createCallback = <TAllowedNames extends string, TName extends TAllowedName
return {
name,
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() {
if (options.beforeStart) {
creatorOptions.logger.logDebug("Running beforeStart for job", {
@@ -136,9 +111,7 @@ export const createCronJobCreator = <TAllowedNames extends string = string>(
name,
cronExpression: defaultCronExpression,
});
if (!validate(defaultCronExpression)) {
throw new Error(`Invalid cron expression '${defaultCronExpression}' for job '${name}'`);
}
// Validation will be done by cron-parser when needed
creatorOptions.logger.logDebug("Cron job expression for cron job is valid", {
name,
cronExpression: defaultCronExpression,
+29 -38
View File
@@ -1,11 +1,9 @@
import type { ScheduledTask } from "node-cron";
import { objectEntries, objectKeys } from "@homarr/common";
import { db } from "@homarr/db";
import { jobRegistry } from "./registry";
import type { JobCallback } from "./creator";
import type { Logger } from "./logger";
import { jobRegistry } from "./registry";
type Jobs<TAllowedNames extends string> = {
[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 {
initializeAsync: async () => {
// No tasks to create, just ensure jobs are registered
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);
if (configuration?.isEnabled === false) {
continue;
}
if (tasks.has(job.name)) {
continue;
}
const scheduledTask = await job.createTaskAsync();
tasks.set(job.name, scheduledTask);
// Run onStart if needed
await job.onStartAsync();
}
},
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 (!tasks.has(job.name)) return;
options.logger.logInfo("Starting schedule of cron job.", {
options.logger.logInfo("Enabling cron job.", {
name: job.name,
});
await job.onStartAsync();
await tasks.get(name as string)?.start();
},
startAllAsync: async () => {
for (const job of jobRegistry.values()) {
if (!tasks.has(job.name)) {
continue;
}
options.logger.logInfo("Starting schedule of cron job.", {
for (const job of Object.values(jobs)) {
options.logger.logInfo("Enabling cron job.", {
name: job.name,
});
await job.onStartAsync();
await tasks.get(job.name)?.start();
}
},
runManuallyAsync: async (name: keyof TJobs) => {
const job = jobRegistry.get(name as string);
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 schedule cron job manually.", {
options.logger.logInfo("Running cron job manually.", {
name: job.name,
});
await tasks.get(name as string)?.execute();
await job.executeAsync();
},
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;
options.logger.logInfo("Stopping schedule of cron job.", {
options.logger.logInfo("Disabling cron job.", {
name: job.name,
});
await tasks.get(name as string)?.stop();
},
stopAllAsync: async () => {
for (const job of jobRegistry.values()) {
options.logger.logInfo("Stopping schedule of cron job.", {
for (const job of Object.values(jobs)) {
options.logger.logInfo("Disabling cron job.", {
name: job.name,
});
await tasks.get(job.name)?.stop();
}
},
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) {
return tasks.get(name as string) ?? null;
getTask() {
// No tasks in new system
return null;
},
setTask(name: keyof TJobs, task: ScheduledTask) {
tasks.set(name as string, task);
setTask() {
// No tasks
},
getKeys() {
return objectKeys(jobs);
+1 -1
View File
@@ -217,7 +217,7 @@ export const integrationDefs = {
name: "Nextcloud",
secretKinds: [["username", "password"]],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/nextcloud.svg",
category: ["calendar", "notifications"],
category: ["calendar"],
documentationUrl: createDocumentationLink("/docs/integrations/nextcloud"),
},
unifiController: {
+1 -1
View File
@@ -47,7 +47,7 @@
"octokit": "^5.0.5",
"proxmox-api": "1.1.1",
"tsdav": "^2.1.8",
"undici": "7.24.5",
"undici": "7.18.2",
"xml2js": "^0.6.2",
"zod": "^4.2.1"
},
@@ -5,10 +5,8 @@ import utc from "dayjs/plugin/utc";
import type { RequestInit as NodeFetchRequestInit } from "node-fetch";
import * as ical from "node-ical";
import { DAVClient } from "tsdav";
import { z } from "zod";
import { ResponseError } from "@homarr/common/server";
import { createHttpsAgentAsync, fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { createHttpsAgentAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs";
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 { ICalendarIntegration } from "../interfaces/calendar/calendar-integration";
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" });
@@ -40,7 +23,7 @@ dayjs.extend(utc);
dayjs.extend(timezone);
@HandleIntegrationErrors([integrationTsdavHttpErrorHandler])
export class NextcloudIntegration extends Integration implements ICalendarIntegration, INotificationsIntegration {
export class NextcloudIntegration extends Integration implements ICalendarIntegration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const client = await this.createCalendarClientAsync(await createHttpsAgentAsync(input.options));
await client.login();
@@ -121,29 +104,6 @@ export class NextcloudIntegration extends Integration implements ICalendarIntegr
.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) {
return new DAVClient({
serverUrl: this.integration.url,
+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 type { IJobManager } from "@homarr/cron-job-api";
@@ -10,58 +10,103 @@ import { cronJobConfigurations } from "@homarr/db/schema";
const logger = createLogger({ module: "jobManager" });
export class JobManager implements IJobManager {
private runningJobs = new Set<string>();
constructor(
private db: Database,
private jobGroup: typeof cronJobGroup,
) {}
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> {
await this.jobGroup.runManuallyAsync(name);
}
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> {
logger.info("Updating cron job interval", { name, expression: cron });
const job = this.jobGroup.getJobRegistry().get(name);
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}`);
}
if (job.preventCustomInterval && cron !== job.cronExpression) {
throw new Error(`Custom cron expressions are not allowed for job ${name}`);
}
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 });
}
public async disableAsync(name: JobGroupKeys): Promise<void> {
logger.info("Disabling cron job", { name });
const job = this.jobGroup.getJobRegistry().get(name);
if (!job) throw new Error(`Job ${name} not found`);
await this.updateConfigurationAsync(name, { isEnabled: false });
await this.jobGroup.stopAsync(name);
logger.info("Cron job disabled", { name });
}
public async enableAsync(name: JobGroupKeys): Promise<void> {
logger.info("Enabling cron job", { name });
await this.updateConfigurationAsync(name, { isEnabled: true });
await this.jobGroup.startAsync(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(
name: JobGroupKeys,
configuration: Omit<Partial<InferInsertModel<typeof cronJobConfigurations>>, "name">,
@@ -79,7 +124,6 @@ export class JobManager implements IJobManager {
if (existingConfig) {
await this.db
.update(cronJobConfigurations)
// prevent updating the name, as it is the primary key
.set({ ...configuration, name: undefined })
.where(eq(cronJobConfigurations.name, name));
logger.debug("Cron job configuration updated", {
@@ -97,7 +141,7 @@ export class JobManager implements IJobManager {
cronExpression: configuration.cronExpression ?? job.cronExpression,
isEnabled: configuration.isEnabled ?? true,
});
logger.debug("Cron job configuration updated", {
logger.debug("Cron job configuration created", {
name,
configuration: JSON.stringify(configuration),
});
@@ -125,4 +169,4 @@ export class JobManager implements IJobManager {
};
});
}
}
}
@@ -57,12 +57,10 @@ export const AddBoardModal = createModal(({ actions }) => {
{...form.getInputProps("name")}
description={
boardNameStatus.description ? (
<span>
<Group c={boardNameStatus.description.color} gap="xs" align="center">
{boardNameStatus.description.icon ? <boardNameStatus.description.icon size={16} /> : null}
<span>{boardNameStatus.description.label}</span>
</Group>
</span>
<Group c={boardNameStatus.description.color} gap="xs" align="center">
{boardNameStatus.description.icon ? <boardNameStatus.description.icon size={16} /> : null}
<span>{boardNameStatus.description.label}</span>
</Group>
) : null
}
/>
@@ -101,7 +101,6 @@ const optionMapping: OptionMapping = {
allowMicrophone: (oldOptions) => oldOptions.allowMicrophone,
allowGeolocation: (oldOptions) => oldOptions.allowGeolocation,
allowScrolling: (oldOptions) => oldOptions.allowScrolling,
allowModals: () => undefined,
},
video: {
feedUrl: (oldOptions) => oldOptions.FeedUrl,
+1 -1
View File
@@ -33,7 +33,7 @@
"dayjs": "^1.11.20",
"octokit": "^5.0.5",
"superjson": "2.2.6",
"undici": "7.24.5",
"undici": "7.18.2",
"zod": "^4.2.1"
},
"devDependencies": {
@@ -94,6 +94,7 @@ const createSpotlightContext = (displayName: string) => {
context.unregisterItems(key);
};
// We ignore the results
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...dependencyArray, key]);
};
+1 -3
View File
@@ -1625,9 +1625,6 @@
},
"allowGeolocation": {
"label": "Allow geolocation"
},
"allowModals": {
"label": "Allow modals"
}
},
"error": {
@@ -2036,6 +2033,7 @@
"directStream": "Direct Stream"
}
},
"recentActivity": {
"title": "Recent Activity",
"empty": "No recent activity",
@@ -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
}
};
@@ -105,10 +105,6 @@ const getSandboxFlags = (
baseSandbox.push("allow-popups-to-escape-sandbox");
}
if (permissions.allowModals) {
baseSandbox.push("allow-modals");
}
return baseSandbox;
};
@@ -119,5 +115,4 @@ const permissionMapping = {
allowGeolocation: "geolocation",
allowMicrophone: "microphone",
allowPayment: "payment",
allowModals: "allow-modals",
} 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(),
allowCamera: factory.switch(),
allowGeolocation: factory.switch(),
allowModals: factory.switch(),
}));
},
}).withDynamicImport(() => import("./component"));
+1
View File
@@ -79,6 +79,7 @@ const Feed = ({ options }: Pick<WidgetComponentProps<"video">, "options">) => {
],
});
// All other properties are updated with other useEffect
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [videoRef]);
useEffect(() => {
+32 -20
View File
@@ -438,8 +438,8 @@ importers:
specifier: 2.2.6
version: 2.2.6
undici:
specifier: 7.24.5
version: 7.24.5
specifier: 7.18.2
version: 7.18.2
devDependencies:
'@homarr/eslint-config':
specifier: workspace:^0.2.0
@@ -862,8 +862,8 @@ importers:
specifier: 19.2.4
version: 19.2.4(react@19.2.4)
undici:
specifier: 7.24.5
version: 7.24.5
specifier: 7.18.2
version: 7.18.2
zod:
specifier: ^4.2.1
version: 4.2.1
@@ -1455,7 +1455,7 @@ importers:
version: link:../image-proxy
'@homarr/node-unifi':
specifier: ^2.6.0
version: 2.6.0(undici@7.24.5)
version: 2.6.0(undici@7.18.2)
'@homarr/redis':
specifier: workspace:^0.1.0
version: link:../redis
@@ -1493,8 +1493,8 @@ importers:
specifier: ^2.1.8
version: 2.1.8
undici:
specifier: 7.24.5
version: 7.24.5
specifier: 7.18.2
version: 7.18.2
xml2js:
specifier: ^0.6.2
version: 0.6.2
@@ -1864,8 +1864,8 @@ importers:
specifier: 2.2.6
version: 2.2.6
undici:
specifier: 7.24.5
version: 7.24.5
specifier: 7.18.2
version: 7.18.2
zod:
specifier: ^4.2.1
version: 4.2.1
@@ -10424,12 +10424,20 @@ packages:
resolution: {integrity: sha512-VfQPToRA5FZs/qJxLIinmU59u0r7LXqoJkCzinq3ckNJp3vKEh7jTWN589YQ5+aoAC/TGRLyJLCPKcLQbM8r9g==}
engines: {node: '>=18.17'}
undici@7.18.2:
resolution: {integrity: sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw==}
engines: {node: '>=20.18.1'}
undici@7.21.0:
resolution: {integrity: sha512-Hn2tCQpoDt1wv23a68Ctc8Cr/BHpUSfaPYrkajTXOS9IKpxVRx/X5m1K2YkbK2ipgZgxXSgsUinl3x+2YdSSfg==}
engines: {node: '>=20.18.1'}
undici@7.24.0:
resolution: {integrity: sha512-jxytwMHhsbdpBXxLAcuu0fzlQeXCNnWdDyRHpvWsUl8vd98UwYdl9YTyn8/HcpcJPC3pwUveefsa3zTxyD/ERg==}
engines: {node: '>=20.18.1'}
undici@7.24.5:
resolution: {integrity: sha512-3IWdCpjgxp15CbJnsi/Y9TCDE7HWVN19j1hmzVhoAkY/+CJx449tVxT5wZc1Gwg8J+P0LWvzlBzxYRnHJ+1i7Q==}
undici@7.24.4:
resolution: {integrity: sha512-BM/JzwwaRXxrLdElV2Uo6cTLEjhSb3WXboncJamZ15NgUURmvlXvxa6xkwIOILIjPNo9i8ku136ZvWV0Uly8+w==}
engines: {node: '>=20.18.1'}
unicode-emoji-modifier-base@1.0.0:
@@ -11896,11 +11904,11 @@ snapshots:
'@homarr/gridstack@1.12.0': {}
'@homarr/node-unifi@2.6.0(undici@7.24.5)':
'@homarr/node-unifi@2.6.0(undici@7.18.2)':
dependencies:
axios: 1.9.0
eventemitter2: 6.4.9
http-cookie-agent: 6.0.8(tough-cookie@5.1.2)(undici@7.24.5)
http-cookie-agent: 6.0.8(tough-cookie@5.1.2)(undici@7.18.2)
tough-cookie: 5.1.2
ws: 8.19.0
transitivePeerDependencies:
@@ -12876,7 +12884,7 @@ snapshots:
p-filter: 4.1.0
semantic-release: 25.0.3(typescript@5.9.3)
tinyglobby: 0.2.15
undici: 7.24.5
undici: 7.18.2
url-join: 5.0.0
transitivePeerDependencies:
- supports-color
@@ -16585,12 +16593,12 @@ snapshots:
html-url-attributes@3.0.1: {}
http-cookie-agent@6.0.8(tough-cookie@5.1.2)(undici@7.24.5):
http-cookie-agent@6.0.8(tough-cookie@5.1.2)(undici@7.18.2):
dependencies:
agent-base: 7.1.3
tough-cookie: 5.1.2
optionalDependencies:
undici: 7.24.5
undici: 7.18.2
http-errors@2.0.0:
dependencies:
@@ -17072,7 +17080,7 @@ snapshots:
saxes: 6.0.0
symbol-tree: 3.2.4
tough-cookie: 6.0.0
undici: 7.24.5
undici: 7.21.0
w3c-xmlserializer: 5.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
@@ -17099,7 +17107,7 @@ snapshots:
saxes: 6.0.0
symbol-tree: 3.2.4
tough-cookie: 6.0.1
undici: 7.24.5
undici: 7.24.4
w3c-xmlserializer: 5.0.0
webidl-conversions: 8.0.1
whatwg-mimetype: 5.0.0
@@ -19732,7 +19740,7 @@ snapshots:
ssh-remote-port-forward: 1.0.4
tar-fs: 3.1.2
tmp: 0.2.5
undici: 7.24.5
undici: 7.24.4
transitivePeerDependencies:
- bare-buffer
- supports-color
@@ -20072,9 +20080,13 @@ snapshots:
undici@6.23.0: {}
undici@7.18.2: {}
undici@7.21.0: {}
undici@7.24.0: {}
undici@7.24.5: {}
undici@7.24.4: {}
unicode-emoji-modifier-base@1.0.0: {}
+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 &
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
terminate() {
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
# kill redis-server last because of logging of other services and only if $REDIS_PID is set
if [ -n "$REDIS_PID" ]; then