perf: implement Phase 1 homepage diet via Next.js Cache Components
P1-0: V8 heap cap (HOMARR_MAX_OLD_SPACE_SIZE, default 512MB)
P1-1: Module graph cuts
- Dynamic integration imports (55 static → lazy loaders)
- Conditional DB driver loading (only configured driver loaded)
- Replace jsdom with linkedom for SVG sanitization
- Delete eager widget barrel (55 import * as → 0)
- Extract createRetryableLoader to @homarr/common
P1-2: Enable cacheComponents + restructure root layout
- Suspense boundaries around session-dependent providers
- ColorSchemeScript replaces server-side cookie reads
- Board/manage/auth layouts wrapped in Suspense
P1-3: Cache read paths
- Cache tag registry + invalidation helpers
- Cache invalidation wired into all mutation routers
- Translation deep-merge memoized per locale
P1-4: Prerendered shells + loading.tsx files
P1-5: Shared integration data cache (60s TTL, stale-while-revalidate)
P1-6: Redis-backed Next.js cache handler (@homarr/next-cache-handler)
P1-7: Redis optional (memory channel fallback), TTL on pubSub:last:*,
Redis clients consolidated from 6 to 2
This commit is contained in:
86 files changed
+2219
-1232
No files matched your search
@@ -3,7 +3,8 @@ import { randomUUID } from "crypto";
|
||||
import type { MaybePromise } from "@homarr/common/types";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
|
||||
import { createRedisConnection } from "./connection";
|
||||
import { getSubscriberClient, usesMemoryFallback } from "./connection";
|
||||
import { memorySubscribe } from "./memory-channel";
|
||||
|
||||
const logger = createLogger({ module: "channelSubscriptionTracker" });
|
||||
|
||||
@@ -18,7 +19,8 @@ type SubscriptionCallback = (message: string) => MaybePromise<void>;
|
||||
*/
|
||||
export class ChannelSubscriptionTracker {
|
||||
private static subscriptions = new Map<string, Map<string, SubscriptionCallback>>();
|
||||
private static redis = createRedisConnection();
|
||||
private static redis = getSubscriberClient();
|
||||
private static memoryUnsubscribers = new Map<string, () => void>();
|
||||
private static listenerActive = false;
|
||||
|
||||
/**
|
||||
@@ -30,19 +32,27 @@ export class ChannelSubscriptionTracker {
|
||||
public static subscribe(channelName: string, callback: SubscriptionCallback) {
|
||||
logger.debug("Adding redis channel callback", { channel: channelName });
|
||||
|
||||
// We only want to activate the listener once
|
||||
if (!this.listenerActive) {
|
||||
this.activateListener();
|
||||
this.listenerActive = true;
|
||||
}
|
||||
|
||||
const channelSubscriptions = this.subscriptions.get(channelName) ?? new Map<string, SubscriptionCallback>();
|
||||
const id = randomUUID();
|
||||
|
||||
// If there are no subscriptions to the channel, subscribe to it
|
||||
if (channelSubscriptions.size === 0) {
|
||||
logger.debug("Subscribing to redis channel", { channel: channelName });
|
||||
void this.redis.subscribe(channelName);
|
||||
if (usesMemoryFallback()) {
|
||||
const unsub = memorySubscribe(channelName, (message) => {
|
||||
this.dispatchMessage(channelName, message);
|
||||
});
|
||||
this.memoryUnsubscribers.set(channelName, unsub);
|
||||
} else {
|
||||
if (!this.listenerActive) {
|
||||
this.activateListener();
|
||||
this.listenerActive = true;
|
||||
}
|
||||
const redis = this.redis;
|
||||
if (redis) {
|
||||
void redis.subscribe(channelName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Adding redis channel callback", { channel: channelName, id });
|
||||
@@ -65,30 +75,44 @@ export class ChannelSubscriptionTracker {
|
||||
}
|
||||
|
||||
logger.debug("Unsubscribing from redis channel", { channel: channelName });
|
||||
void this.redis.unsubscribe(channelName);
|
||||
if (usesMemoryFallback()) {
|
||||
this.memoryUnsubscribers.get(channelName)?.();
|
||||
this.memoryUnsubscribers.delete(channelName);
|
||||
} else {
|
||||
const redis = this.redis;
|
||||
if (redis) {
|
||||
void redis.unsubscribe(channelName);
|
||||
}
|
||||
}
|
||||
this.subscriptions.delete(channelName);
|
||||
};
|
||||
}
|
||||
|
||||
private static dispatchMessage(channel: string, message: string) {
|
||||
const channelSubscriptions = this.subscriptions.get(channel);
|
||||
if (!channelSubscriptions) {
|
||||
logger.warn("Received message on unknown channel", { channel });
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [id, callback] of channelSubscriptions.entries()) {
|
||||
// Don't log messages from the logging channel as it would create an infinite loop
|
||||
if (channel !== "pubSub:logging") {
|
||||
logger.debug("Calling subscription callback", { channel, id });
|
||||
}
|
||||
void callback(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates the listener for the redis client.
|
||||
*/
|
||||
private static activateListener() {
|
||||
logger.debug("Activating listener");
|
||||
this.redis.on("message", (channel, message) => {
|
||||
const channelSubscriptions = this.subscriptions.get(channel);
|
||||
if (!channelSubscriptions) {
|
||||
logger.warn("Received message on unknown channel", { channel });
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [id, callback] of channelSubscriptions.entries()) {
|
||||
// Don't log messages from the logging channel as it would create an infinite loop
|
||||
if (channel !== "pubSub:logging") {
|
||||
logger.debug("Calling subscription callback", { channel, id });
|
||||
}
|
||||
void callback(message);
|
||||
}
|
||||
const redis = this.redis;
|
||||
if (!redis) return;
|
||||
redis.on("message", (channel, message) => {
|
||||
this.dispatchMessage(channel, message);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,12 @@ import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("./connection", () => ({
|
||||
createRedisConnection: () => null,
|
||||
getDataClient: () => null,
|
||||
getSubscriberClient: () => null,
|
||||
usesMemoryFallback: () => true,
|
||||
}));
|
||||
|
||||
import { createLockChannel } from "./channel";
|
||||
import { createLockChannel, createSubPubChannel } from "./channel";
|
||||
|
||||
describe("createLockChannel", () => {
|
||||
test("degrades gracefully when Redis connections are disabled", async () => {
|
||||
@@ -19,3 +22,31 @@ describe("createLockChannel", () => {
|
||||
await expect(lock.releaseAsync(token)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createSubPubChannel with memory fallback", () => {
|
||||
test("publish and subscribe deliver messages in-process", async () => {
|
||||
const channel = createSubPubChannel<{ value: number }>("test-pubsub");
|
||||
|
||||
const received: { value: number }[] = [];
|
||||
channel.subscribe((data) => {
|
||||
received.push(data);
|
||||
});
|
||||
|
||||
await channel.publishAsync({ value: 42 });
|
||||
|
||||
expect(received).toEqual([{ value: 42 }]);
|
||||
await expect(channel.getLastDataAsync()).resolves.toEqual({ value: 42 });
|
||||
});
|
||||
|
||||
test("subscribe replays last persisted data", async () => {
|
||||
const channel = createSubPubChannel<string>("test-replay");
|
||||
await channel.publishAsync("hello");
|
||||
|
||||
const replayed: string[] = [];
|
||||
channel.subscribe((data) => {
|
||||
replayed.push(data);
|
||||
});
|
||||
|
||||
expect(replayed).toEqual(["hello"]);
|
||||
});
|
||||
});
|
||||
@@ -3,10 +3,12 @@ import superjson from "superjson";
|
||||
import { createId } from "@homarr/common";
|
||||
|
||||
import { ChannelSubscriptionTracker } from "./channel-subscription-tracker";
|
||||
import { createRedisConnection } from "./connection";
|
||||
import { getDataClient, usesMemoryFallback } from "./connection";
|
||||
import { memoryGetLast, memoryPublish } from "./memory-channel";
|
||||
|
||||
const publisher = createRedisConnection();
|
||||
const lastDataClient = createRedisConnection();
|
||||
const LAST_DATA_TTL_SECONDS = 86_400;
|
||||
|
||||
const dataClient = getDataClient();
|
||||
|
||||
/**
|
||||
* Creates a new pub/sub channel.
|
||||
@@ -23,11 +25,18 @@ export const createSubPubChannel = <TData>(name: string, { persist }: { persist:
|
||||
*/
|
||||
subscribe: (callback: (data: TData) => void) => {
|
||||
if (persist) {
|
||||
void lastDataClient.get(lastChannelName).then((data) => {
|
||||
if (usesMemoryFallback()) {
|
||||
const data = memoryGetLast(lastChannelName);
|
||||
if (data) {
|
||||
callback(superjson.parse(data));
|
||||
}
|
||||
});
|
||||
} else if (dataClient) {
|
||||
void dataClient.get(lastChannelName).then((data) => {
|
||||
if (data) {
|
||||
callback(superjson.parse(data));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return ChannelSubscriptionTracker.subscribe(channelName, (message) => {
|
||||
callback(superjson.parse(message));
|
||||
@@ -38,20 +47,31 @@ export const createSubPubChannel = <TData>(name: string, { persist }: { persist:
|
||||
* @param data data to be published
|
||||
*/
|
||||
publishAsync: async (data: TData) => {
|
||||
const serialized = superjson.stringify(data);
|
||||
if (persist) {
|
||||
await lastDataClient.set(lastChannelName, superjson.stringify(data));
|
||||
if (usesMemoryFallback()) {
|
||||
memoryPublish(lastChannelName, data);
|
||||
} else if (dataClient) {
|
||||
await dataClient.set(lastChannelName, serialized, "EX", LAST_DATA_TTL_SECONDS);
|
||||
}
|
||||
}
|
||||
if (usesMemoryFallback()) {
|
||||
memoryPublish(channelName, data);
|
||||
} else if (dataClient) {
|
||||
await dataClient.publish(channelName, serialized);
|
||||
}
|
||||
await publisher.publish(channelName, superjson.stringify(data));
|
||||
},
|
||||
getLastDataAsync: async () => {
|
||||
const data = await lastDataClient.get(lastChannelName);
|
||||
if (usesMemoryFallback()) {
|
||||
const data = memoryGetLast(lastChannelName);
|
||||
return data ? superjson.parse<TData>(data) : null;
|
||||
}
|
||||
const data = await dataClient?.get(lastChannelName);
|
||||
return data ? superjson.parse<TData>(data) : null;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const getSetClient = createRedisConnection();
|
||||
|
||||
/**
|
||||
* Creates a new redis channel for a list
|
||||
* @param name name of channel
|
||||
@@ -65,7 +85,8 @@ export const createListChannel = <TItem>(name: string) => {
|
||||
* @returns an array of all items
|
||||
*/
|
||||
getAllAsync: async () => {
|
||||
const items = await getSetClient.lrange(listChannelName, 0, -1);
|
||||
if (!dataClient) return [];
|
||||
const items = await dataClient.lrange(listChannelName, 0, -1);
|
||||
return items.map((item) => superjson.parse<TItem>(item));
|
||||
},
|
||||
/**
|
||||
@@ -73,20 +94,23 @@ export const createListChannel = <TItem>(name: string) => {
|
||||
* @param item item to remove
|
||||
*/
|
||||
removeAsync: async (item: TItem) => {
|
||||
await getSetClient.lrem(listChannelName, 0, superjson.stringify(item));
|
||||
if (!dataClient) return;
|
||||
await dataClient.lrem(listChannelName, 0, superjson.stringify(item));
|
||||
},
|
||||
/**
|
||||
* Clear all items from the channels list
|
||||
*/
|
||||
clearAsync: async () => {
|
||||
await getSetClient.del(listChannelName);
|
||||
if (!dataClient) return;
|
||||
await dataClient.del(listChannelName);
|
||||
},
|
||||
/**
|
||||
* Add an item to the channels list
|
||||
* @param item item to add
|
||||
*/
|
||||
addAsync: async (item: TItem) => {
|
||||
await getSetClient.lpush(listChannelName, superjson.stringify(item));
|
||||
if (!dataClient) return;
|
||||
await dataClient.lpush(listChannelName, superjson.stringify(item));
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -102,7 +126,8 @@ export const createGetSetChannel = <TData>(name: string) => {
|
||||
* @returns data or null if not found
|
||||
*/
|
||||
getAsync: async () => {
|
||||
const data = await getSetClient.get(name);
|
||||
if (!dataClient) return null;
|
||||
const data = await dataClient.get(name);
|
||||
return data ? superjson.parse<TData>(data) : null;
|
||||
},
|
||||
/**
|
||||
@@ -111,17 +136,19 @@ export const createGetSetChannel = <TData>(name: string) => {
|
||||
* @param options optional TTL in seconds
|
||||
*/
|
||||
setAsync: async (data: TData, options?: { ttlSeconds?: number }) => {
|
||||
if (!dataClient) return;
|
||||
if (options?.ttlSeconds) {
|
||||
await getSetClient.set(name, superjson.stringify(data), "EX", options.ttlSeconds);
|
||||
await dataClient.set(name, superjson.stringify(data), "EX", options.ttlSeconds);
|
||||
return;
|
||||
}
|
||||
await getSetClient.set(name, superjson.stringify(data));
|
||||
await dataClient.set(name, superjson.stringify(data));
|
||||
},
|
||||
/**
|
||||
* Remove data from the channel
|
||||
*/
|
||||
removeAsync: async () => {
|
||||
await getSetClient.del(name);
|
||||
if (!dataClient) return;
|
||||
await dataClient.del(name);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -136,17 +163,15 @@ export const createLockChannel = (name: string) => {
|
||||
return {
|
||||
acquireAsync: async (ttlSeconds: number) => {
|
||||
const token = createId();
|
||||
const client = getSetClient as typeof getSetClient | null;
|
||||
if (!client) return token;
|
||||
if (!dataClient) return token;
|
||||
|
||||
const result = await client.set(name, token, "EX", ttlSeconds, "NX");
|
||||
const result = await dataClient.set(name, token, "EX", ttlSeconds, "NX");
|
||||
return result === "OK" ? token : null;
|
||||
},
|
||||
releaseAsync: async (token: string) => {
|
||||
const client = getSetClient as typeof getSetClient | null;
|
||||
if (!client) return;
|
||||
if (!dataClient) return;
|
||||
|
||||
await client.eval(
|
||||
await dataClient.eval(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
|
||||
1,
|
||||
name,
|
||||
@@ -157,9 +182,8 @@ export const createLockChannel = (name: string) => {
|
||||
};
|
||||
|
||||
export const invalidateIntegrationCacheAsync = async (integrationId: string): Promise<void> => {
|
||||
const client = getSetClient as typeof getSetClient | null;
|
||||
if (!client) return;
|
||||
await client.del(`session-store:${integrationId}`);
|
||||
if (!dataClient) return;
|
||||
await dataClient.del(`session-store:${integrationId}`);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -167,11 +191,12 @@ export const invalidateIntegrationCacheAsync = async (integrationId: string): Pr
|
||||
*/
|
||||
export const createChannelEventHistoryOld = <TData>(channelName: string, maxElements = 15) => {
|
||||
const popElementsOverMaxAsync = async () => {
|
||||
const length = await getSetClient.llen(channelName);
|
||||
if (!dataClient) return;
|
||||
const length = await dataClient.llen(channelName);
|
||||
if (length <= maxElements) {
|
||||
return;
|
||||
}
|
||||
await getSetClient.ltrim(channelName, 0, maxElements - 1);
|
||||
await dataClient.ltrim(channelName, 0, maxElements - 1);
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -181,33 +206,39 @@ export const createChannelEventHistoryOld = <TData>(channelName: string, maxElem
|
||||
});
|
||||
},
|
||||
publishAndPushAsync: async (data: TData) => {
|
||||
await publisher.publish(channelName, superjson.stringify(data));
|
||||
await getSetClient.lpush(channelName, superjson.stringify({ data, timestamp: new Date() }));
|
||||
if (!dataClient) return;
|
||||
await dataClient.publish(channelName, superjson.stringify(data));
|
||||
await dataClient.lpush(channelName, superjson.stringify({ data, timestamp: new Date() }));
|
||||
await popElementsOverMaxAsync();
|
||||
},
|
||||
pushAsync: async (data: TData) => {
|
||||
await getSetClient.lpush(channelName, superjson.stringify({ data, timestamp: new Date() }));
|
||||
if (!dataClient) return;
|
||||
await dataClient.lpush(channelName, superjson.stringify({ data, timestamp: new Date() }));
|
||||
await popElementsOverMaxAsync();
|
||||
},
|
||||
clearAsync: async () => {
|
||||
await getSetClient.del(channelName);
|
||||
if (!dataClient) return;
|
||||
await dataClient.del(channelName);
|
||||
},
|
||||
getLastAsync: async () => {
|
||||
const length = await getSetClient.llen(channelName);
|
||||
const data = await getSetClient.lrange(channelName, length - 1, length);
|
||||
if (!dataClient) return null;
|
||||
const length = await dataClient.llen(channelName);
|
||||
const data = await dataClient.lrange(channelName, length - 1, length);
|
||||
if (data.length !== 1) return null;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return superjson.parse<{ data: TData; timestamp: Date }>(data[0]!);
|
||||
},
|
||||
getSliceAsync: async (startIndex: number, endIndex: number) => {
|
||||
const range = await getSetClient.lrange(channelName, startIndex, endIndex);
|
||||
if (!dataClient) return [];
|
||||
const range = await dataClient.lrange(channelName, startIndex, endIndex);
|
||||
return range.map((item) => superjson.parse<{ data: TData; timestamp: Date }>(item));
|
||||
},
|
||||
getSliceUntilTimeAsync: async (time: Date) => {
|
||||
const length = await getSetClient.llen(channelName);
|
||||
if (!dataClient) return [];
|
||||
const length = await dataClient.llen(channelName);
|
||||
const items: TData[] = [];
|
||||
const itemsInCollection = await getSetClient.lrange(channelName, 0, length - 1);
|
||||
const itemsInCollection = await dataClient.lrange(channelName, 0, length - 1);
|
||||
|
||||
for (let i = 0; i < length - 1; i++) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
@@ -220,14 +251,13 @@ export const createChannelEventHistoryOld = <TData>(channelName: string, maxElem
|
||||
return items;
|
||||
},
|
||||
getLengthAsync: async () => {
|
||||
return await getSetClient.llen(channelName);
|
||||
if (!dataClient) return 0;
|
||||
return await dataClient.llen(channelName);
|
||||
},
|
||||
name: channelName,
|
||||
};
|
||||
};
|
||||
|
||||
const queueClient = createRedisConnection();
|
||||
|
||||
type WithId<TItem> = TItem & { _id: string };
|
||||
|
||||
/**
|
||||
@@ -238,11 +268,13 @@ type WithId<TItem> = TItem & { _id: string };
|
||||
export const createQueueChannel = <TItem>(name: string) => {
|
||||
const queueChannelName = `queue:${name}`;
|
||||
const getDataAsync = async () => {
|
||||
const data = await queueClient.get(queueChannelName);
|
||||
if (!dataClient) return [];
|
||||
const data = await dataClient.get(queueChannelName);
|
||||
return data ? superjson.parse<WithId<TItem>[]>(data) : [];
|
||||
};
|
||||
const setDataAsync = async (data: WithId<TItem>[]) => {
|
||||
await queueClient.set(queueChannelName, superjson.stringify(data));
|
||||
if (!dataClient) return;
|
||||
await dataClient.set(queueChannelName, superjson.stringify(data));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -289,5 +321,6 @@ export const createQueueChannel = <TItem>(name: string) => {
|
||||
};
|
||||
|
||||
export const handshakeAsync = async () => {
|
||||
await getSetClient.hello();
|
||||
if (!dataClient) return;
|
||||
await dataClient.hello();
|
||||
};
|
||||
@@ -1,15 +1,32 @@
|
||||
import type { RedisClient } from "@homarr/core/infrastructure/redis";
|
||||
import { createRedisClient } from "@homarr/core/infrastructure/redis";
|
||||
|
||||
/**
|
||||
* Creates a new Redis connection
|
||||
* @returns redis client
|
||||
*/
|
||||
export const createRedisConnection = () => {
|
||||
if (Boolean(process.env.CI) || Boolean(process.env.DISABLE_REDIS_LOGS)) {
|
||||
// Return null if we are in CI as we don't want to connect to Redis
|
||||
return null as unknown as RedisClient;
|
||||
}
|
||||
let dataClient: RedisClient | undefined;
|
||||
let subscriberClient: RedisClient | undefined;
|
||||
|
||||
return createRedisClient();
|
||||
const isRedisExplicitlyDisabled = () =>
|
||||
Boolean(process.env.CI) || Boolean(process.env.DISABLE_REDIS_LOGS);
|
||||
|
||||
/**
|
||||
* In-process pub/sub fallback for single-instance deployments when Redis is unavailable.
|
||||
* Never used when REDIS_IS_EXTERNAL=true (multi-instance requires real Redis).
|
||||
*/
|
||||
export const usesMemoryFallback = (): boolean =>
|
||||
process.env.REDIS_IS_EXTERNAL !== "true" && isRedisExplicitlyDisabled();
|
||||
|
||||
/** Shared client for SET/GET/PUBLISH and other non-subscribe Redis commands. */
|
||||
export const getDataClient = (): RedisClient | null => {
|
||||
if (usesMemoryFallback()) return null;
|
||||
dataClient ??= createRedisClient();
|
||||
return dataClient;
|
||||
};
|
||||
|
||||
/** Dedicated client for SUBSCRIBE — ioredis requires a separate connection for pub/sub. */
|
||||
export const getSubscriberClient = (): RedisClient | null => {
|
||||
if (usesMemoryFallback()) return null;
|
||||
subscriberClient ??= createRedisClient();
|
||||
return subscriberClient;
|
||||
};
|
||||
|
||||
/** @deprecated Prefer getDataClient() — kept for test mocks. */
|
||||
export const createRedisConnection = () => getDataClient();
|
||||
@@ -0,0 +1,34 @@
|
||||
import EventEmitter from "node:events";
|
||||
|
||||
import superjson from "superjson";
|
||||
|
||||
const emitter = new EventEmitter();
|
||||
emitter.setMaxListeners(100);
|
||||
|
||||
const lastData = new Map<string, { data: string; timestamp: number }>();
|
||||
const MAX_ENTRIES = 500;
|
||||
|
||||
export const memoryPublish = (channel: string, data: unknown) => {
|
||||
const serialized = superjson.stringify(data);
|
||||
lastData.set(channel, { data: serialized, timestamp: Date.now() });
|
||||
|
||||
// Bounded: evict oldest if over limit
|
||||
if (lastData.size > MAX_ENTRIES) {
|
||||
const oldest = lastData.keys().next().value;
|
||||
if (oldest) lastData.delete(oldest);
|
||||
}
|
||||
|
||||
emitter.emit(channel, serialized);
|
||||
};
|
||||
|
||||
export const memorySubscribe = (channel: string, callback: (data: string) => void) => {
|
||||
emitter.on(channel, callback);
|
||||
return () => {
|
||||
emitter.off(channel, callback);
|
||||
};
|
||||
};
|
||||
|
||||
export const memoryGetLast = (channel: string): string | null => {
|
||||
const entry = lastData.get(channel);
|
||||
return entry?.data ?? null;
|
||||
};
|
||||
Reference in new issue
Block a user