Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Warm Workloads route and chart caches

rcourtman0c8628c23efb
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 9e79209a4f..a5c86788f4 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -287,6 +287,9 @@ once login succeeds, `frontend-modern/src/App.tsx` must resolve `/login`
through the canonical post-auth landing route instead of leaving the
assistant-capable authenticated shell stranded on a route that only exists for
logged-out presentation.
+App-shell route preloading may include the Patrol route module, but it must
+remain module-only. It must not prefetch AI settings, model state, findings,
+chat sessions, or assistant context while the drawer is closed.
`docs/release-control/v6/internal/subsystems/registry.json` must therefore keep
`frontend-modern/src/stores/aiRuntimeState.ts` and
`frontend-modern/src/components/AI/Chat/` on the explicit AI runtime proof
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 4c04240e7e..b4be546eda 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -1385,6 +1385,11 @@ That same landing contract also owns authenticated `/login`: once the browser
has a valid session, `frontend-modern/src/App.tsx` must route `/login`
through that same runtime-home landing boundary instead of leaving the
authenticated app shell on a not-found compatibility path.
+Authenticated app-shell route and chart prewarming may run from
+`frontend-modern/src/App.tsx` and `frontend-modern/src/useAppRuntimeState.ts`
+only as auth-neutral performance work: it must not change hosted organization
+bootstrap, presentation-policy loading, commercial posture loading, or upgrade
+prompt visibility.
The Pro license settings surface now follows the same rule as well. Changes to
`frontend-modern/src/components/Settings/ProLicensePanel.tsx` must carry this
contract and the dedicated Pro-license proof file instead of remaining an
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 2debaa8776..f741d42e73 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -783,6 +783,15 @@ work extends shared components instead of creating new local variants.
the `Add infrastructure` source picker, instead of preserving a separate
root-only compatibility shell or an agent-only install jump that drifts from
the rest of the onboarding contract.
+ The authenticated app shell's boot-time route preloads must be owned by
+ `frontend-modern/src/routing/routePreload.ts` so top-level cold-tab
+ readiness cannot drift from the route-module preloader. Workloads,
+ Recovery, Patrol, Alerts, Storage, and Settings are part of that shared
+ preload contract.
+ Route-module preloads and idle chart-cache prewarming are separate shell
+ responsibilities: the shared route preload inventory must stay module-only,
+ while chart payload warming must route through the owning summary-cache
+ utilities instead of mounting hidden pages or adding page-local boot logic.
The same entry-shell contract must also canonicalize authenticated
`/login`: once auth succeeds, the shared shell must resolve that route back
onto the governed Infrastructure landing path instead of rendering a page-local
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 09b21af1b1..dc8b698d5f 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -327,6 +327,11 @@ the dashboard overview retirement. When live mock ticks advance, monitoring
must repopulate the canonical 24-hour aggregate `/api/charts/storage-summary`
cache inside the sampler path instead of leaving the first operator request
after each tick to rebuild per-pool mock storage charts on demand.
+The same mock sampler path must also prewarm the default Workloads guest-chart
+cache through `GetGuestMetricsForChartBatch`, using canonical `ReadState`
+workload identities for VMs, system containers, Kubernetes pods, and app
+containers so `/api/charts/workloads` and `/api/charts/workloads-summary` do
+not rebuild every guest sparkline on the first post-tick request.
That same metrics-hot-path ownership also includes metric-type selection for
compact summary reads. When infrastructure or storage summary routes request
only a subset of canonical chart series,
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index f68bc7c627..573b425a1c 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -119,6 +119,7 @@ regression protection.
97. `frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx`
98. `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`
99. `frontend-modern/src/components/Infrastructure/infrastructureSummaryModel.ts`
+100. `frontend-modern/src/utils/workloadsSummaryCache.ts`
103. `frontend-modern/src/components/Storage/StorageSummary.tsx`
104. `frontend-modern/src/utils/storageSummaryCache.ts`
105. `frontend-modern/src/pages/Workloads.tsx`
@@ -208,6 +209,13 @@ regression protection.
presentation helper via the workload filter config model instead of the
hot-path shell hard-coding local `All ...` strings.
26. Keep long-range workload chart capping time-proportional across `frontend-modern/src/components/Workloads/WorkloadsSummary.tsx`, `frontend-modern/src/api/charts.ts`, and `internal/api/router.go`: when the workload hot path caps mixed-cadence history for top cards, it must bucket by time window rather than raw point index so 7-day and 30-day workload cards stay visually even without relaxing the protected payload budget.
+ Workload summary chart caching and app-shell prewarming belong to
+ `frontend-modern/src/utils/workloadsSummaryCache.ts`, not to page-local
+ component state. `frontend-modern/src/components/Workloads/WorkloadsSummary.tsx`
+ may hydrate from that shared in-memory/local cache and refresh it, while
+ `frontend-modern/src/useAppRuntimeState.ts` may warm the same cache after
+ authenticated bootstrap without mounting the Workloads route or starting a
+ second polling loop.
27. Keep summary hover/focus and sticky-card behavior on shared hot paths: infrastructure, workloads, and storage summary shells must reuse one page/group/entity scope model plus `frontend-modern/src/components/shared/StickySummarySection.tsx` inside the app scroll shell instead of per-page scroll listeners or per-card hover derivations, so row scrubbing highlights all cards, workload group headers, infrastructure cluster headers, and storage pool-group headers scope the summary coherently, pinned group focus remains route-backed and reversible, and the hot path does not multiply render or scroll work. That hot path stays row-first rather than adding fallback chrome: the on-screen row or group header is the scoped state, and any explicit reset belongs to one compact shared table-header action plus the shared `Escape` path, not to page-level scope strips, search-row widgets, or filter-bar badges. Background whitespace clearing may exist as a convenience, but the hot path must not depend on brittle dead-space hit testing as the only reversible control. The same hot path must therefore keep one page-level reset owner for filters plus pinned summary selections, and it must keep chart-backed summary-card geometry explicit and stable so hover rerenders, synchronized readouts, or idle header metadata cannot feed layout loops that grow or shrink the top cards over time. Recovery’s summary rail is not part of this interactive hot path; it may share summary-card framing, but it must remain non-interactive until a separately governed model says otherwise.
The input path for that hot summary contract must stay shared too:
`frontend-modern/src/components/shared/summaryInteractionA11y.ts` owns
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 79ca212144..b0086fda4f 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -4175,6 +4175,7 @@
"frontend-modern/src/pages/Workloads.tsx",
"frontend-modern/src/utils/thresholdSliderPresentation.ts",
"frontend-modern/src/utils/throughputPresentation.ts",
+ "frontend-modern/src/utils/workloadsSummaryCache.ts",
"internal/api/router_bench_test.go",
"internal/api/slo.go",
"internal/api/slo_bench_test.go"
@@ -4205,6 +4206,7 @@
"frontend-modern/src/components/Workloads/MetricBar.test.tsx",
"frontend-modern/src/components/Workloads/StackedMemoryBar.test.tsx",
"frontend-modern/src/components/Workloads/ThresholdSlider.test.tsx",
+ "frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx",
"internal/api/router_bench_test.go",
"internal/api/slo_bench_test.go",
"pkg/metrics/store_bench_test.go",
@@ -4302,7 +4304,8 @@
"frontend-modern/src/components/Workloads/workloadTopology.ts",
"frontend-modern/src/components/Workloads/workloadUrlSyncModel.ts",
"frontend-modern/src/pages/Workloads.tsx",
- "frontend-modern/src/utils/thresholdSliderPresentation.ts"
+ "frontend-modern/src/utils/thresholdSliderPresentation.ts",
+ "frontend-modern/src/utils/workloadsSummaryCache.ts"
],
"allow_same_subsystem_tests": false,
"test_prefixes": [],
@@ -4338,7 +4341,8 @@
"frontend-modern/src/components/Workloads/ThresholdSlider.test.tsx",
"frontend-modern/src/components/Workloads/WorkloadsSummary.test.tsx",
"frontend-modern/src/pages/__tests__/Workloads.helpers.test.ts",
- "frontend-modern/src/utils/__tests__/thresholdSliderPresentation.test.ts"
+ "frontend-modern/src/utils/__tests__/thresholdSliderPresentation.test.ts",
+ "frontend-modern/src/utils/__tests__/workloadsSummaryCache.test.ts"
]
},
{
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index ebbd7e07fd..74357d8345 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -381,6 +381,10 @@ querying, and the operator-facing storage health presentation layer.
dialogs: background assistant affordances may hide while a modal owns the
viewport, but storage/recovery routes must not grow their own parallel
modal-stack bookkeeping just because they share `App.tsx`.
+ App-shell route preloading may include Storage and Recovery modules so
+ top-level tabs are warm after authentication, but it must not fetch storage
+ summary charts, recovery history, provider state, or preview data from
+ `frontend-modern/src/App.tsx` itself.
36. Keep public self-hosted purchase handoff and activation routes on the
adjacent commercial/auth boundary. When `internal/api/router.go`,
`internal/api/router_routes_cloud.go`, `internal/api/licensing_handlers.go`,
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index 58c28f8d96..d370604329 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -29,7 +29,7 @@ import {
buildStoragePath,
buildWorkloadsPath,
} from './routing/resourceLinks';
-import { preloadRouteModule } from '@/routing/routePreload';
+import { APP_SHELL_ROUTE_PRELOAD_PATHS, preloadRouteModule } from '@/routing/routePreload';
import { AppLayout } from '@/AppLayout';
import RuntimeHomePage from '@/pages/RuntimeHome';
import { useAppRuntimeState } from '@/useAppRuntimeState';
@@ -70,13 +70,6 @@ const ROOT_WORKLOADS_PATH = buildWorkloadsPath();
const STORAGE_PATH = buildStoragePath();
const RECOVERY_ROUTE_PATH = buildRecoveryPath();
const ROOT_PATROL_PATH = PATROL_PATH;
-const APP_SHELL_ROUTE_PRELOAD_PATHS = [
- RECOVERY_ROUTE_PATH,
- ROOT_PATROL_PATH,
- '/alerts',
- STORAGE_PATH,
- '/settings',
-] as const;
async function preloadAppShellRoutes() {
await Promise.all(
diff --git a/frontend-modern/src/__tests__/App.architecture.test.ts b/frontend-modern/src/__tests__/App.architecture.test.ts
index a8706a6114..2ec3cf9462 100644
--- a/frontend-modern/src/__tests__/App.architecture.test.ts
+++ b/frontend-modern/src/__tests__/App.architecture.test.ts
@@ -29,10 +29,13 @@ describe('App architecture', () => {
expect(appSource).toContain('clearPendingAppShellRestoreTop');
expect(appSource).toContain('const INFRASTRUCTURE_ROUTE_PATH = buildInfrastructurePath();');
expect(appSource).toContain('const ROOT_PATROL_PATH = PATROL_PATH;');
- expect(appSource).toContain("import { preloadRouteModule } from '@/routing/routePreload';");
- expect(appSource).toContain('const APP_SHELL_ROUTE_PRELOAD_PATHS = [');
- expect(appSource).toContain('RECOVERY_ROUTE_PATH,');
- expect(appSource).toContain('ROOT_PATROL_PATH,');
+ expect(appSource).toContain(
+ "import { APP_SHELL_ROUTE_PRELOAD_PATHS, preloadRouteModule } from '@/routing/routePreload';",
+ );
+ expect(routePreloadSource).toContain('export const APP_SHELL_ROUTE_PRELOAD_PATHS = [');
+ expect(routePreloadSource).toContain('ROOT_WORKLOADS_PATH,');
+ expect(routePreloadSource).toContain('RECOVERY_ROUTE_PATH,');
+ expect(routePreloadSource).toContain('PATROL_PATH,');
expect(appSource).toContain('await preloadRouteModule(route);');
expect(appSource).toContain('const timeoutId = window.setTimeout(() => {');
expect(appSource).toContain('void preloadAppShellRoutes();');
@@ -256,6 +259,7 @@ describe('App architecture', () => {
expect(appRuntimeStateSource).not.toContain('startMetricsCollector();');
expect(appRuntimeStateSource).not.toContain('function AppLayout(');
expect(routePreloadSource).toContain('const ROUTE_PRELOADERS: readonly RoutePreloader[] = [');
+ expect(routePreloadSource).toContain('export const APP_SHELL_ROUTE_PRELOAD_PATHS = [');
expect(routePreloadSource).toContain("id: 'recovery',");
expect(routePreloadSource).toContain("id: 'patrol',");
expect(routePreloadSource).toContain(
diff --git a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
index f6ec119427..a208872374 100644
--- a/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
+++ b/frontend-modern/src/__tests__/useAppRuntimeState.test.ts
@@ -1,4 +1,5 @@
import { createRoot } from 'solid-js';
+import { waitFor } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
type UseAppRuntimeStateModule = typeof import('@/useAppRuntimeState');
@@ -22,6 +23,10 @@ describe('useAppRuntimeState', () => {
let setOrgIDMock: ReturnType<typeof vi.fn>;
let showToastMock: ReturnType<typeof vi.fn>;
let aiChatSetEnabledMock: ReturnType<typeof vi.fn>;
+ let fetchInfrastructureSummaryAndCacheMock: ReturnType<typeof vi.fn>;
+ let hasFreshInfrastructureSummaryCacheMock: ReturnType<typeof vi.fn>;
+ let fetchWorkloadsSummaryAndCacheMock: ReturnType<typeof vi.fn>;
+ let hasFreshWorkloadsSummaryCacheMock: ReturnType<typeof vi.fn>;
beforeEach(async () => {
vi.resetModules();
@@ -75,6 +80,10 @@ describe('useAppRuntimeState', () => {
setOrgIDMock = vi.fn();
showToastMock = vi.fn();
aiChatSetEnabledMock = vi.fn();
+ fetchInfrastructureSummaryAndCacheMock = vi.fn().mockResolvedValue(undefined);
+ hasFreshInfrastructureSummaryCacheMock = vi.fn().mockReturnValue(false);
+ fetchWorkloadsSummaryAndCacheMock = vi.fn().mockResolvedValue(undefined);
+ hasFreshWorkloadsSummaryCacheMock = vi.fn().mockReturnValue(false);
vi.doMock('@/stores/websocket-global', () => ({
getGlobalWebSocketStore: () => ({
@@ -172,12 +181,19 @@ describe('useAppRuntimeState', () => {
}));
vi.doMock('@/utils/infrastructureSummaryCache', () => ({
- fetchInfrastructureSummaryAndCache: vi.fn().mockResolvedValue(undefined),
- hasFreshInfrastructureSummaryCache: vi.fn().mockReturnValue(false),
+ fetchInfrastructureSummaryAndCache: fetchInfrastructureSummaryAndCacheMock,
+ hasFreshInfrastructureSummaryCache: hasFreshInfrastructureSummaryCacheMock,
+ }));
+
+ vi.doMock('@/utils/workloadsSummaryCache', () => ({
+ WORKLOAD_CHART_DEFAULT_POINT_LIMIT: 180,
+ fetchWorkloadsSummaryAndCache: fetchWorkloadsSummaryAndCacheMock,
+ hasFreshWorkloadsSummaryCache: hasFreshWorkloadsSummaryCacheMock,
}));
vi.doMock('@/routing/resourceLinks', () => ({
buildInfrastructurePath: () => '/infrastructure',
+ buildWorkloadsPath: () => '/workloads',
}));
vi.doMock('@/stores/alertsActivation', () => ({
@@ -398,6 +414,23 @@ describe('useAppRuntimeState', () => {
dispose();
});
+ it('prewarms authenticated app-shell chart caches without mounting target routes', async () => {
+ window.history.replaceState({}, '', '/settings');
+ const { dispose } = mountHook();
+
+ await waitFor(() => {
+ expect(fetchInfrastructureSummaryAndCacheMock).toHaveBeenCalledWith('1h', {
+ caller: 'App prewarm',
+ });
+ expect(fetchWorkloadsSummaryAndCacheMock).toHaveBeenCalledWith('1h', {
+ caller: 'App workloads prewarm',
+ maxPoints: 180,
+ });
+ });
+
+ dispose();
+ });
+
it('skips the protected state bootstrap probe on the login route until a local auth hint exists', async () => {
window.history.replaceState({}, '', '/login');
hasStoredAuthSessionMock.mockReturnValue(false);
diff --git a/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx b/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
index 0e3293627f..cef092570b 100644
--- a/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
+++ b/frontend-modern/src/components/Workloads/WorkloadsSummary.tsx
@@ -1,4 +1,4 @@
-import { Component, Show, createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
+import { Component, Show, createEffect, createMemo, createSignal, onCleanup, untrack } from 'solid-js';
import {
InteractiveSparkline,
type InteractiveSparklineSeries,
@@ -16,7 +16,6 @@ import type { SummarySeriesGroupScope } from '@/components/shared/summaryCardInt
import { buildDensityMapSynchronizedReadout } from '@/components/shared/densityMapModel';
import { buildInteractiveSparklineSynchronizedReadout } from '@/components/shared/interactiveSparklineModel';
import {
- ChartsAPI,
type ChartData,
type MetricPoint,
type TimeRange,
@@ -26,6 +25,18 @@ import { getOrgID } from '@/utils/apiClient';
import { normalizeOrgScope } from '@/utils/orgScope';
import { eventBus } from '@/stores/events';
import { formatThroughputRate } from '@/utils/throughputPresentation';
+import {
+ WORKLOAD_CHART_DEFAULT_POINT_LIMIT,
+ fetchWorkloadsSummaryAndCache,
+ readInMemoryWorkloadsSummaryCache,
+ readWorkloadsSummaryCache,
+ workloadsSummaryCacheScopeKey,
+ __resetWorkloadsSummaryCacheForTests,
+} from '@/utils/workloadsSummaryCache';
+
+export {
+ __resetWorkloadsSummaryCacheForTests as __resetInMemoryWorkloadCacheForTests,
+} from '@/utils/workloadsSummaryCache';
interface WorkloadsSummaryProps {
timeRange?: TimeRange;
@@ -108,160 +119,9 @@ const WORKLOAD_COLORS = [
'#6366f1',
];
-const WORKLOADS_SUMMARY_CACHE_PREFIX = 'pulse.workloadsSummaryCharts.';
-const WORKLOADS_SUMMARY_CACHE_VERSION = 6;
-const WORKLOADS_SUMMARY_CACHE_MAX_AGE_MS = 5 * 60_000;
-const WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES = 360;
-const WORKLOADS_SUMMARY_CACHE_MAX_CHARS = 900_000;
-const WORKLOAD_CHART_DEFAULT_POINT_LIMIT = 180;
const WORKLOADS_IDLE_THRESHOLD_MS = 2 * 60_000;
const WORKLOADS_DEEP_IDLE_THRESHOLD_MS = 10 * 60_000;
-// In-memory full-resolution cache keyed by scope key (org::range::node).
-// Survives component unmount/remount (page navigation) without the
-// downsampling artifacts that localStorage cache introduces.
-// Capped at MAX_IN_MEMORY_ENTRIES to prevent unbounded growth.
-const MAX_IN_MEMORY_WORKLOAD_ENTRIES = 20;
-const inMemoryWorkloadCache = new Map<string, WorkloadChartsResponse>();
-
-/** @internal Test-only reset for in-memory workload cache. */
-export function __resetInMemoryWorkloadCacheForTests(): void {
- inMemoryWorkloadCache.clear();
-}
-
-// Clear in-memory cache on org switch to prevent cross-org data leakage.
-const unsubscribeWorkloadOrgSwitch = eventBus.on('org_switched', () => {
- inMemoryWorkloadCache.clear();
-});
-
-if (import.meta.hot) {
- import.meta.hot.dispose(() => {
- unsubscribeWorkloadOrgSwitch();
- });
-}
-
-type CachedChartData = Pick<
- ChartData,
- 'cpu' | 'memory' | 'disk' | 'diskread' | 'diskwrite' | 'netin' | 'netout'
->;
-
-interface CachedWorkloadsSummary {
- version: number;
- range: TimeRange;
- nodeScope: string;
- cachedAt: number;
- data: Record<string, CachedChartData>;
- dockerData: Record<string, CachedChartData>;
-}
-
-const cacheKeyFor = (range: TimeRange, nodeScope: string, orgScope: string) =>
- `${WORKLOADS_SUMMARY_CACHE_PREFIX}${encodeURIComponent(orgScope)}::${range}::${encodeURIComponent(nodeScope || '__all__')}`;
-
-const trimPoints = <T,>(points: T[] | undefined, max: number): T[] => {
- if (!points || points.length === 0) return [];
- if (points.length <= max) return points;
- if (max <= 1) return points.slice(points.length - 1);
-
- const start = Math.max(0, points.length - max * 2);
- const sliced = points.slice(start);
- if (sliced.length <= max) return sliced;
-
- const step = Math.ceil(sliced.length / max);
- const result: T[] = [];
- for (let i = 0; i < sliced.length; i += step) {
- result.push(sliced[i]);
- }
- if (result[result.length - 1] !== sliced[sliced.length - 1]) {
- result.push(sliced[sliced.length - 1]);
- }
- return result.length > max ? result.slice(result.length - max) : result;
-};
-
-const toCachedChartData = (data: ChartData): CachedChartData => ({
- cpu: trimPoints(data.cpu, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- memory: trimPoints(data.memory, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- disk: trimPoints(data.disk, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- diskread: trimPoints(data.diskread, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- diskwrite: trimPoints(data.diskwrite, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- netin: trimPoints(data.netin, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
- netout: trimPoints(data.netout, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
-});
-
-const persistWorkloadsSummaryCache = (
- range: TimeRange,
- nodeScope: string,
- orgScope: string,
- response: WorkloadChartsResponse,
-): void => {
- if (typeof window === 'undefined') return;
- try {
- const data: Record<string, CachedChartData> = {};
- const dockerData: Record<string, CachedChartData> = {};
- for (const [id, chartData] of Object.entries(response.data || {})) {
- data[id] = toCachedChartData(chartData);
- }
- for (const [id, chartData] of Object.entries(response.dockerData || {})) {
- dockerData[id] = toCachedChartData(chartData);
- }
-
- const payload: CachedWorkloadsSummary = {
- version: WORKLOADS_SUMMARY_CACHE_VERSION,
- range,
- nodeScope,
- cachedAt: Date.now(),
- data,
- dockerData,
- };
- const serialized = JSON.stringify(payload);
- if (serialized.length > WORKLOADS_SUMMARY_CACHE_MAX_CHARS) {
- window.localStorage.removeItem(cacheKeyFor(range, nodeScope, orgScope));
- return;
- }
- window.localStorage.setItem(cacheKeyFor(range, nodeScope, orgScope), serialized);
- } catch {
- // Ignore cache write failures.
- }
-};
-
-const readWorkloadsSummaryCache = (
- range: TimeRange,
- nodeScope: string,
- orgScope: string,
-): WorkloadChartsResponse | null => {
- if (typeof window === 'undefined') return null;
- try {
- const raw = window.localStorage.getItem(cacheKeyFor(range, nodeScope, orgScope));
- if (!raw) return null;
-
- const parsed = JSON.parse(raw) as CachedWorkloadsSummary;
- if (
- parsed?.version !== WORKLOADS_SUMMARY_CACHE_VERSION ||
- parsed.range !== range ||
- parsed.nodeScope !== nodeScope ||
- typeof parsed.cachedAt !== 'number'
- ) {
- window.localStorage.removeItem(cacheKeyFor(range, nodeScope, orgScope));
- return null;
- }
- if (Date.now() - parsed.cachedAt > WORKLOADS_SUMMARY_CACHE_MAX_AGE_MS) {
- window.localStorage.removeItem(cacheKeyFor(range, nodeScope, orgScope));
- return null;
- }
-
- return {
- data: parsed.data || {},
- dockerData: parsed.dockerData || {},
- guestTypes: {},
- timestamp: parsed.cachedAt,
- stats: {
- oldestDataTimestamp: 0,
- },
- };
- } catch {
- return null;
- }
-};
-
const refreshIntervalForRange = (range: TimeRange): number => {
switch (range) {
case '5m':
@@ -434,8 +294,7 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
const selectedRange = createMemo<TimeRange>(() => props.timeRange || '1h');
const selectedNodeScope = createMemo(() => props.selectedNodeId?.trim() || '');
const activeScopeKey = createMemo(
- () =>
- `${WORKLOADS_SUMMARY_CACHE_VERSION}::${orgScope()}::${selectedRange()}::${selectedNodeScope()}`,
+ () => workloadsSummaryCacheScopeKey(selectedRange(), selectedNodeScope(), orgScope()),
);
const hasCurrentRangeData = createMemo(() => loadedScopeKey() === activeScopeKey());
@@ -475,20 +334,14 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
activeFetchController = controller;
try {
- const response = await ChartsAPI.getWorkloadCharts(range, controller.signal, {
+ const response = await fetchWorkloadsSummaryAndCache(range, {
+ caller: 'WorkloadsSummary',
+ maxPoints: untrack(workloadPointLimit),
nodeId,
- maxPoints: workloadPointLimit(),
+ orgScope: currentOrgScope,
+ signal: controller.signal,
});
if (activeFetchController !== controller) return;
- persistWorkloadsSummaryCache(range, selectedNodeScope(), currentOrgScope, response);
- if (
- !inMemoryWorkloadCache.has(scopeKey) &&
- inMemoryWorkloadCache.size >= MAX_IN_MEMORY_WORKLOAD_ENTRIES
- ) {
- const oldest = inMemoryWorkloadCache.keys().next().value;
- if (oldest !== undefined) inMemoryWorkloadCache.delete(oldest);
- }
- inMemoryWorkloadCache.set(scopeKey, response);
setCharts(response);
setLoadedScopeKey(scopeKey);
setFetchFailed(false);
@@ -520,18 +373,20 @@ export const WorkloadsSummary: Component<WorkloadsSummaryProps> = (props) => {
clearRefreshTimer();
- // Hydrate from in-memory cache (full-resolution, no curve shift).
- // Only falls back to skeleton if this scope was never fetched in this session.
- const memCached = inMemoryWorkloadCache.get(scopeKey);
- if (memCached) {
- setCharts(memCached);
+ // Prefer in-memory cache for full-resolution session continuity, then
+ // localStorage for cold remounts while the live request refreshes.
+ const cached =
+ readInMemoryWorkloadsSummaryCache(selectedRange(), selectedNodeScope(), orgScope()) ??
+ readWorkloadsSummaryCache(selectedRange(), selectedNodeScope(), orgScope());
+ if (cached) {
+ setCharts(cached);
setLoadedScopeKey(scopeKey);
} else {
setCharts(null);
setLoadedScopeKey(null);
}
setFetchFailed(false);
- void fetchCharts({ prioritize: true }).finally(() => scheduleNextFetch(token));
+ void untrack(() => fetchCharts({ prioritize: true })).finally(() => scheduleNextFetch(token));
});
const unsubscribeOrgSwitch = eventBus.on('org_switched', (nextOrgID) => {
diff --git a/frontend-modern/src/routing/__tests__/routePreload.test.ts b/frontend-modern/src/routing/__tests__/routePreload.test.ts
new file mode 100644
index 0000000000..62beac6af8
--- /dev/null
+++ b/frontend-modern/src/routing/__tests__/routePreload.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { APP_SHELL_ROUTE_PRELOAD_PATHS } from '../routePreload';
+import { PATROL_PATH, buildRecoveryPath, buildStoragePath, buildWorkloadsPath } from '../resourceLinks';
+
+describe('route preloading', () => {
+ it('keeps Workloads in the authenticated app-shell preload set', () => {
+ expect(APP_SHELL_ROUTE_PRELOAD_PATHS).toContain(buildWorkloadsPath());
+ });
+
+ it('keeps all cold top-level app shell targets in the shared preload set', () => {
+ expect([...APP_SHELL_ROUTE_PRELOAD_PATHS]).toEqual([
+ buildWorkloadsPath(),
+ buildRecoveryPath(),
+ PATROL_PATH,
+ '/alerts',
+ buildStoragePath(),
+ '/settings',
+ ]);
+ });
+});
diff --git a/frontend-modern/src/routing/routePreload.ts b/frontend-modern/src/routing/routePreload.ts
index 4b96792952..c5511b73fa 100644
--- a/frontend-modern/src/routing/routePreload.ts
+++ b/frontend-modern/src/routing/routePreload.ts
@@ -20,6 +20,15 @@ const ALERTS_PATH = '/alerts';
const SETTINGS_PATH = '/settings';
const routePreloadCache = new Map<string, Promise<void>>();
+export const APP_SHELL_ROUTE_PRELOAD_PATHS = [
+ ROOT_WORKLOADS_PATH,
+ RECOVERY_ROUTE_PATH,
+ PATROL_PATH,
+ ALERTS_PATH,
+ STORAGE_PATH,
+ SETTINGS_PATH,
+] as const;
+
function normalizeRoute(route: string): string {
const [pathname] = route.split(/[?#]/, 1);
if (!pathname) return '';
diff --git a/frontend-modern/src/useAppRuntimeState.ts b/frontend-modern/src/useAppRuntimeState.ts
index 497cb3a54d..3428fb461e 100644
--- a/frontend-modern/src/useAppRuntimeState.ts
+++ b/frontend-modern/src/useAppRuntimeState.ts
@@ -30,7 +30,12 @@ import {
fetchInfrastructureSummaryAndCache,
hasFreshInfrastructureSummaryCache,
} from '@/utils/infrastructureSummaryCache';
-import { buildInfrastructurePath } from '@/routing/resourceLinks';
+import {
+ WORKLOAD_CHART_DEFAULT_POINT_LIMIT,
+ fetchWorkloadsSummaryAndCache,
+ hasFreshWorkloadsSummaryCache,
+} from '@/utils/workloadsSummaryCache';
+import { buildInfrastructurePath, buildWorkloadsPath } from '@/routing/resourceLinks';
import { useAlertsActivation } from '@/stores/alertsActivation';
import {
applyThemeClass,
@@ -80,6 +85,7 @@ export type AppConnectionStatus = {
};
const ROOT_INFRASTRUCTURE_PATH = buildInfrastructurePath();
+const ROOT_WORKLOADS_PATH = buildWorkloadsPath();
const isPreAuthLoginBootstrapPath = (pathname: string): boolean =>
pathname === '/' || pathname === '/login';
@@ -100,8 +106,9 @@ export const useAppRuntimeState = () => {
let hasPreloadedRoutes = false;
let hasFetchedVersionInfo = false;
let hasPrewarmedInfrastructureCharts = false;
+ let hasPrewarmedWorkloadsCharts = false;
- const getInfrastructureTrendRangeForPrewarm = (): TimeRange => '1h';
+ const getAppShellChartRangeForPrewarm = (): TimeRange => '1h';
const hasLocalAuthBootstrapHint = (): boolean => {
if (hasStoredAuthSession()) {
@@ -119,7 +126,7 @@ export const useAppRuntimeState = () => {
}
};
- const shouldPrewarmInfrastructure = (): boolean => {
+ const shouldPrewarmBackgroundCharts = (activeRoutePath: string): boolean => {
if (typeof window === 'undefined') return false;
const connection = (
@@ -136,16 +143,21 @@ export const useAppRuntimeState = () => {
const pathname = window.location.pathname;
if (!pathname) return true;
- if (pathname === ROOT_INFRASTRUCTURE_PATH) return false;
+ if (pathname === activeRoutePath) return false;
return true;
};
+ const shouldPrewarmInfrastructure = (): boolean =>
+ shouldPrewarmBackgroundCharts(ROOT_INFRASTRUCTURE_PATH);
+
+ const shouldPrewarmWorkloads = (): boolean => shouldPrewarmBackgroundCharts(ROOT_WORKLOADS_PATH);
+
const prewarmInfrastructureCharts = () => {
if (hasPrewarmedInfrastructureCharts || !shouldPrewarmInfrastructure()) {
return;
}
- const range = getInfrastructureTrendRangeForPrewarm();
+ const range = getAppShellChartRangeForPrewarm();
if (hasFreshInfrastructureSummaryCache(range)) {
hasPrewarmedInfrastructureCharts = true;
return;
@@ -157,6 +169,31 @@ export const useAppRuntimeState = () => {
});
};
+ const prewarmWorkloadsCharts = () => {
+ if (hasPrewarmedWorkloadsCharts || !shouldPrewarmWorkloads()) {
+ return;
+ }
+
+ const range = getAppShellChartRangeForPrewarm();
+ if (hasFreshWorkloadsSummaryCache(range)) {
+ hasPrewarmedWorkloadsCharts = true;
+ return;
+ }
+
+ hasPrewarmedWorkloadsCharts = true;
+ void fetchWorkloadsSummaryAndCache(range, {
+ caller: 'App workloads prewarm',
+ maxPoints: WORKLOAD_CHART_DEFAULT_POINT_LIMIT,
+ }).catch(() => {
+ // Non-blocking prewarm; ignore failures.
+ });
+ };
+
+ const prewarmAppShellCharts = () => {
+ prewarmInfrastructureCharts();
+ prewarmWorkloadsCharts();
+ };
+
const preloadLazyRoutes = () => {
if (hasPreloadedRoutes || typeof window === 'undefined') {
return;
@@ -471,7 +508,11 @@ export const useAppRuntimeState = () => {
});
createEffect(() => {
- if (isLoading() || needsAuth() || hasPrewarmedInfrastructureCharts) {
+ if (
+ isLoading() ||
+ needsAuth() ||
+ (hasPrewarmedInfrastructureCharts && hasPrewarmedWorkloadsCharts)
+ ) {
return;
}
if (typeof window === 'undefined') {
@@ -480,7 +521,7 @@ export const useAppRuntimeState = () => {
if (typeof window.requestIdleCallback === 'function') {
const id = window.requestIdleCallback(() => {
- prewarmInfrastructureCharts();
+ prewarmAppShellCharts();
}, { timeout: 2_000 });
onCleanup(() => {
window.cancelIdleCallback(id);
@@ -489,7 +530,7 @@ export const useAppRuntimeState = () => {
}
const timeout = window.setTimeout(() => {
- prewarmInfrastructureCharts();
+ prewarmAppShellCharts();
}, 500);
onCleanup(() => {
window.clearTimeout(timeout);
diff --git a/frontend-modern/src/utils/__tests__/workloadsSummaryCache.test.ts b/frontend-modern/src/utils/__tests__/workloadsSummaryCache.test.ts
new file mode 100644
index 0000000000..6724aacaaa
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/workloadsSummaryCache.test.ts
@@ -0,0 +1,115 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { WorkloadChartsResponse } from '@/api/charts';
+import {
+ __resetWorkloadsSummaryCacheForTests,
+ fetchWorkloadsSummaryAndCache,
+ hasFreshWorkloadsSummaryCache,
+ readInMemoryWorkloadsSummaryCache,
+ readWorkloadsSummaryCache,
+} from '@/utils/workloadsSummaryCache';
+
+const mockGetWorkloadCharts = vi.fn();
+
+vi.mock('@/api/charts', async () => {
+ const actual = await vi.importActual<typeof import('@/api/charts')>('@/api/charts');
+ return {
+ ...actual,
+ ChartsAPI: {
+ ...actual.ChartsAPI,
+ getWorkloadCharts: (...args: unknown[]) => mockGetWorkloadCharts(...args),
+ },
+ };
+});
+
+vi.mock('@/utils/apiClient', () => ({
+ getOrgID: () => 'default',
+}));
+
+vi.mock('@/stores/events', () => ({
+ eventBus: {
+ on: vi.fn(() => () => {}),
+ },
+}));
+
+const makeResponse = (): WorkloadChartsResponse => ({
+ data: {
+ 'cluster-a:pve1:101': {
+ cpu: [
+ { timestamp: 1, value: 10 },
+ { timestamp: 2, value: 20 },
+ ],
+ memory: [
+ { timestamp: 1, value: 30 },
+ { timestamp: 2, value: 40 },
+ ],
+ disk: [
+ { timestamp: 1, value: 50 },
+ { timestamp: 2, value: 60 },
+ ],
+ diskread: [
+ { timestamp: 1, value: 70 },
+ { timestamp: 2, value: 80 },
+ ],
+ diskwrite: [
+ { timestamp: 1, value: 90 },
+ { timestamp: 2, value: 100 },
+ ],
+ netin: [
+ { timestamp: 1, value: 110 },
+ { timestamp: 2, value: 120 },
+ ],
+ netout: [
+ { timestamp: 1, value: 130 },
+ { timestamp: 2, value: 140 },
+ ],
+ },
+ },
+ dockerData: {},
+ guestTypes: {},
+ timestamp: Date.now(),
+ stats: {
+ oldestDataTimestamp: 1,
+ },
+});
+
+describe('workloadsSummaryCache', () => {
+ beforeEach(() => {
+ mockGetWorkloadCharts.mockReset();
+ __resetWorkloadsSummaryCacheForTests();
+ localStorage.clear();
+ });
+
+ it('fetches workload charts once and warms memory plus local cache', async () => {
+ const response = makeResponse();
+ mockGetWorkloadCharts.mockResolvedValueOnce(response);
+
+ await fetchWorkloadsSummaryAndCache('1h', {
+ maxPoints: 180,
+ });
+
+ expect(mockGetWorkloadCharts).toHaveBeenCalledWith('1h', undefined, {
+ nodeId: undefined,
+ maxPoints: 180,
+ });
+ expect(readInMemoryWorkloadsSummaryCache('1h')).toBe(response);
+ expect(readWorkloadsSummaryCache('1h')).toEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ 'cluster-a:pve1:101': expect.any(Object),
+ }),
+ }),
+ );
+ expect(hasFreshWorkloadsSummaryCache('1h')).toBe(true);
+ });
+
+ it('deduplicates concurrent app-shell prewarm requests', async () => {
+ const response = makeResponse();
+ mockGetWorkloadCharts.mockResolvedValueOnce(response);
+
+ const first = fetchWorkloadsSummaryAndCache('1h');
+ const second = fetchWorkloadsSummaryAndCache('1h');
+
+ await expect(Promise.all([first, second])).resolves.toEqual([response, response]);
+ expect(mockGetWorkloadCharts).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend-modern/src/utils/workloadsSummaryCache.ts b/frontend-modern/src/utils/workloadsSummaryCache.ts
new file mode 100644
index 0000000000..6f8a725b3b
--- /dev/null
+++ b/frontend-modern/src/utils/workloadsSummaryCache.ts
@@ -0,0 +1,264 @@
+import {
+ ChartsAPI,
+ type ChartData,
+ type TimeRange,
+ type WorkloadChartsResponse,
+} from '@/api/charts';
+import { getOrgID } from '@/utils/apiClient';
+import { normalizeOrgScope } from '@/utils/orgScope';
+import { eventBus } from '@/stores/events';
+
+export const WORKLOADS_SUMMARY_CACHE_VERSION = 6;
+export const WORKLOAD_CHART_DEFAULT_POINT_LIMIT = 180;
+
+const WORKLOADS_SUMMARY_CACHE_PREFIX = 'pulse.workloadsSummaryCharts.';
+const WORKLOADS_SUMMARY_CACHE_MAX_AGE_MS = 5 * 60_000;
+const WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES = 360;
+const WORKLOADS_SUMMARY_CACHE_MAX_CHARS = 900_000;
+const MAX_IN_MEMORY_WORKLOAD_ENTRIES = 20;
+
+type CachedChartData = Pick<
+ ChartData,
+ 'cpu' | 'memory' | 'disk' | 'diskread' | 'diskwrite' | 'netin' | 'netout'
+>;
+
+type CachedWorkloadsSummary = {
+ version: number;
+ range: TimeRange;
+ nodeScope: string;
+ cachedAt: number;
+ data: Record<string, CachedChartData>;
+ dockerData: Record<string, CachedChartData>;
+};
+
+type FetchWorkloadsSummaryAndCacheOptions = {
+ caller?: string;
+ maxPoints?: number | null;
+ nodeId?: string | null;
+ orgScope?: string | null;
+ signal?: AbortSignal;
+};
+
+const inMemoryWorkloadCache = new Map<string, WorkloadChartsResponse>();
+const inFlightWorkloadFetches = new Map<string, Promise<WorkloadChartsResponse>>();
+
+const normalizeNodeScope = (nodeScope: string | null | undefined): string => nodeScope?.trim() ?? '';
+
+const normalizeMaxPoints = (maxPoints: number | null | undefined): number | undefined => {
+ if (typeof maxPoints !== 'number' || !Number.isFinite(maxPoints) || maxPoints <= 0) {
+ return undefined;
+ }
+ return Math.round(maxPoints);
+};
+
+const resolveOrgScope = (orgScope?: string | null): string => normalizeOrgScope(orgScope ?? getOrgID());
+
+const storageCacheKeyFor = (range: TimeRange, nodeScope: string, orgScope: string): string =>
+ `${WORKLOADS_SUMMARY_CACHE_PREFIX}${encodeURIComponent(orgScope)}::${range}::${encodeURIComponent(nodeScope || '__all__')}`;
+
+export function workloadsSummaryCacheScopeKey(
+ range: TimeRange,
+ nodeScope: string | null | undefined = '',
+ orgScope?: string | null,
+): string {
+ return `${WORKLOADS_SUMMARY_CACHE_VERSION}::${resolveOrgScope(orgScope)}::${range}::${normalizeNodeScope(nodeScope)}`;
+}
+
+const trimPoints = <T,>(points: T[] | undefined, max: number): T[] => {
+ if (!points || points.length === 0) return [];
+ if (points.length <= max) return points;
+ if (max <= 1) return points.slice(points.length - 1);
+
+ const start = Math.max(0, points.length - max * 2);
+ const sliced = points.slice(start);
+ if (sliced.length <= max) return sliced;
+
+ const step = Math.ceil(sliced.length / max);
+ const result: T[] = [];
+ for (let i = 0; i < sliced.length; i += step) {
+ result.push(sliced[i]);
+ }
+ if (result[result.length - 1] !== sliced[sliced.length - 1]) {
+ result.push(sliced[sliced.length - 1]);
+ }
+ return result.length > max ? result.slice(result.length - max) : result;
+};
+
+const toCachedChartData = (data: ChartData): CachedChartData => ({
+ cpu: trimPoints(data.cpu, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ memory: trimPoints(data.memory, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ disk: trimPoints(data.disk, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ diskread: trimPoints(data.diskread, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ diskwrite: trimPoints(data.diskwrite, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ netin: trimPoints(data.netin, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+ netout: trimPoints(data.netout, WORKLOADS_SUMMARY_CACHE_MAX_POINTS_PER_SERIES),
+});
+
+const writeInMemoryWorkloadsSummaryCache = (
+ range: TimeRange,
+ nodeScope: string,
+ orgScope: string,
+ response: WorkloadChartsResponse,
+): void => {
+ const scopeKey = workloadsSummaryCacheScopeKey(range, nodeScope, orgScope);
+ if (!inMemoryWorkloadCache.has(scopeKey) && inMemoryWorkloadCache.size >= MAX_IN_MEMORY_WORKLOAD_ENTRIES) {
+ const oldest = inMemoryWorkloadCache.keys().next().value;
+ if (oldest !== undefined) inMemoryWorkloadCache.delete(oldest);
+ }
+ inMemoryWorkloadCache.set(scopeKey, response);
+};
+
+export function readInMemoryWorkloadsSummaryCache(
+ range: TimeRange,
+ nodeScope: string | null | undefined = '',
+ orgScope?: string | null,
+): WorkloadChartsResponse | null {
+ return inMemoryWorkloadCache.get(workloadsSummaryCacheScopeKey(range, nodeScope, orgScope)) ?? null;
+}
+
+export function persistWorkloadsSummaryCache(
+ range: TimeRange,
+ nodeScope: string | null | undefined,
+ orgScope: string | null | undefined,
+ response: WorkloadChartsResponse,
+): void {
+ const normalizedNodeScope = normalizeNodeScope(nodeScope);
+ const normalizedOrgScope = resolveOrgScope(orgScope);
+
+ writeInMemoryWorkloadsSummaryCache(range, normalizedNodeScope, normalizedOrgScope, response);
+
+ if (typeof window === 'undefined') return;
+ try {
+ const data: Record<string, CachedChartData> = {};
+ const dockerData: Record<string, CachedChartData> = {};
+ for (const [id, chartData] of Object.entries(response.data || {})) {
+ data[id] = toCachedChartData(chartData);
+ }
+ for (const [id, chartData] of Object.entries(response.dockerData || {})) {
+ dockerData[id] = toCachedChartData(chartData);
+ }
+
+ const payload: CachedWorkloadsSummary = {
+ version: WORKLOADS_SUMMARY_CACHE_VERSION,
+ range,
+ nodeScope: normalizedNodeScope,
+ cachedAt: Date.now(),
+ data,
+ dockerData,
+ };
+ const serialized = JSON.stringify(payload);
+ const cacheKey = storageCacheKeyFor(range, normalizedNodeScope, normalizedOrgScope);
+ if (serialized.length > WORKLOADS_SUMMARY_CACHE_MAX_CHARS) {
+ window.localStorage.removeItem(cacheKey);
+ return;
+ }
+ window.localStorage.setItem(cacheKey, serialized);
+ } catch {
+ // Ignore cache write failures.
+ }
+}
+
+export function readWorkloadsSummaryCache(
+ range: TimeRange,
+ nodeScope: string | null | undefined = '',
+ orgScope?: string | null,
+): WorkloadChartsResponse | null {
+ if (typeof window === 'undefined') return null;
+
+ const normalizedNodeScope = normalizeNodeScope(nodeScope);
+ const normalizedOrgScope = resolveOrgScope(orgScope);
+ const cacheKey = storageCacheKeyFor(range, normalizedNodeScope, normalizedOrgScope);
+
+ try {
+ const raw = window.localStorage.getItem(cacheKey);
+ if (!raw) return null;
+
+ const parsed = JSON.parse(raw) as CachedWorkloadsSummary;
+ if (
+ parsed?.version !== WORKLOADS_SUMMARY_CACHE_VERSION ||
+ parsed.range !== range ||
+ parsed.nodeScope !== normalizedNodeScope ||
+ typeof parsed.cachedAt !== 'number'
+ ) {
+ window.localStorage.removeItem(cacheKey);
+ return null;
+ }
+ if (Date.now() - parsed.cachedAt > WORKLOADS_SUMMARY_CACHE_MAX_AGE_MS) {
+ window.localStorage.removeItem(cacheKey);
+ return null;
+ }
+
+ const response = {
+ data: parsed.data || {},
+ dockerData: parsed.dockerData || {},
+ guestTypes: {},
+ timestamp: parsed.cachedAt,
+ stats: {
+ oldestDataTimestamp: 0,
+ },
+ };
+ writeInMemoryWorkloadsSummaryCache(range, normalizedNodeScope, normalizedOrgScope, response);
+ return response;
+ } catch {
+ return null;
+ }
+}
+
+export function hasFreshWorkloadsSummaryCache(
+ range: TimeRange,
+ nodeScope: string | null | undefined = '',
+ orgScope?: string | null,
+): boolean {
+ return (
+ readInMemoryWorkloadsSummaryCache(range, nodeScope, orgScope) !== null ||
+ readWorkloadsSummaryCache(range, nodeScope, orgScope) !== null
+ );
+}
+
+export function fetchWorkloadsSummaryAndCache(
+ range: TimeRange,
+ options: FetchWorkloadsSummaryAndCacheOptions = {},
+): Promise<WorkloadChartsResponse> {
+ const nodeScope = normalizeNodeScope(options.nodeId);
+ const orgScope = resolveOrgScope(options.orgScope);
+ const maxPoints = normalizeMaxPoints(options.maxPoints);
+ const requestKey = `${workloadsSummaryCacheScopeKey(range, nodeScope, orgScope)}::${maxPoints ?? 'default'}`;
+
+ if (!options.signal) {
+ const inFlight = inFlightWorkloadFetches.get(requestKey);
+ if (inFlight) return inFlight;
+ }
+
+ const promise = ChartsAPI.getWorkloadCharts(range, options.signal, {
+ nodeId: nodeScope || undefined,
+ maxPoints,
+ }).then((response) => {
+ persistWorkloadsSummaryCache(range, nodeScope, orgScope, response);
+ return response;
+ });
+
+ if (!options.signal) {
+ inFlightWorkloadFetches.set(requestKey, promise);
+ void promise.finally(() => {
+ inFlightWorkloadFetches.delete(requestKey);
+ });
+ }
+
+ return promise;
+}
+
+export function __resetWorkloadsSummaryCacheForTests(): void {
+ inMemoryWorkloadCache.clear();
+ inFlightWorkloadFetches.clear();
+}
+
+const unsubscribeWorkloadOrgSwitch = eventBus.on('org_switched', () => {
+ inMemoryWorkloadCache.clear();
+ inFlightWorkloadFetches.clear();
+});
+
+if (import.meta.hot) {
+ import.meta.hot.dispose(() => {
+ unsubscribeWorkloadOrgSwitch();
+ });
+}
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index 1fa5a4f203..48957699ee 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/mock"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
)
@@ -45,6 +46,8 @@ const (
mockChartPointTargetExtended = 64
)
+const mockDashboardWorkloadPrewarmDuration = time.Hour
+
var storageChartMetricTypes = []string{"usage", "used", "avail", "total"}
var storageSummaryChartMetricTypes = []string{"used", "avail"}
@@ -1122,12 +1125,153 @@ func (m *Monitor) invalidateMockChartCaches() {
}
}
+type mockWorkloadChartPrewarmRequests struct {
+ vms []GuestChartRequest
+ containers []GuestChartRequest
+ pods []GuestChartRequest
+ dockerContainers []GuestChartRequest
+}
+
+func appendMockGuestChartRequest(
+ requests []GuestChartRequest,
+ seen map[string]struct{},
+ inMemoryKey string,
+ sqlResourceID string,
+) []GuestChartRequest {
+ inMemoryKey = strings.TrimSpace(inMemoryKey)
+ sqlResourceID = strings.TrimSpace(sqlResourceID)
+ if inMemoryKey == "" || sqlResourceID == "" {
+ return requests
+ }
+
+ identity := inMemoryKey + "\x00" + sqlResourceID
+ if _, ok := seen[identity]; ok {
+ return requests
+ }
+ seen[identity] = struct{}{}
+
+ return append(requests, GuestChartRequest{
+ InMemoryKey: inMemoryKey,
+ SQLResourceID: sqlResourceID,
+ })
+}
+
+func mockMetricIDFromTargetOrSource(target *unifiedresources.MetricsTarget, sourceID string) string {
+ if target != nil {
+ if metricID := strings.TrimSpace(target.ResourceID); metricID != "" {
+ return metricID
+ }
+ }
+ return strings.TrimSpace(sourceID)
+}
+
+func mockKubernetesPodChartMetricID(pod *unifiedresources.PodView) string {
+ if pod == nil {
+ return ""
+ }
+
+ clusterKey := strings.TrimSpace(pod.ClusterID())
+ if clusterKey == "" {
+ clusterKey = strings.TrimSpace(pod.ClusterName())
+ }
+ podKey := strings.TrimSpace(pod.PodUID())
+ if podKey == "" {
+ namespace := strings.TrimSpace(pod.Namespace())
+ name := strings.TrimSpace(pod.Name())
+ if namespace != "" || name != "" {
+ podKey = namespace + "/" + name
+ }
+ }
+ if clusterKey == "" || podKey == "" {
+ return ""
+ }
+ return "k8s:" + clusterKey + ":pod:" + podKey
+}
+
+func mockWorkloadChartRequestsForReadState(
+ readState unifiedresources.ReadState,
+) mockWorkloadChartPrewarmRequests {
+ if readState == nil {
+ return mockWorkloadChartPrewarmRequests{}
+ }
+
+ requests := mockWorkloadChartPrewarmRequests{
+ vms: make([]GuestChartRequest, 0, len(readState.VMs())),
+ containers: make([]GuestChartRequest, 0, len(readState.Containers())),
+ pods: make([]GuestChartRequest, 0, len(readState.Pods())),
+ dockerContainers: make([]GuestChartRequest, 0, len(readState.DockerContainers())),
+ }
+ seenVMs := make(map[string]struct{}, len(readState.VMs()))
+ seenContainers := make(map[string]struct{}, len(readState.Containers()))
+ seenPods := make(map[string]struct{}, len(readState.Pods()))
+ seenDockerContainers := make(map[string]struct{}, len(readState.DockerContainers()))
+
+ for _, vm := range readState.VMs() {
+ if vm == nil {
+ continue
+ }
+ metricID := mockMetricIDFromTargetOrSource(vm.MetricsTarget(), vm.SourceID())
+ requests.vms = appendMockGuestChartRequest(requests.vms, seenVMs, metricID, metricID)
+ }
+ for _, container := range readState.Containers() {
+ if container == nil {
+ continue
+ }
+ metricID := mockMetricIDFromTargetOrSource(container.MetricsTarget(), container.SourceID())
+ requests.containers = appendMockGuestChartRequest(
+ requests.containers,
+ seenContainers,
+ metricID,
+ metricID,
+ )
+ }
+ for _, pod := range readState.Pods() {
+ metricID := mockKubernetesPodChartMetricID(pod)
+ requests.pods = appendMockGuestChartRequest(requests.pods, seenPods, metricID, metricID)
+ }
+ for _, container := range readState.DockerContainers() {
+ if container == nil {
+ continue
+ }
+ metricID := mockMetricIDFromTargetOrSource(container.MetricsTarget(), container.ContainerID())
+ requests.dockerContainers = appendMockGuestChartRequest(
+ requests.dockerContainers,
+ seenDockerContainers,
+ "docker:"+metricID,
+ metricID,
+ )
+ }
+
+ return requests
+}
+
+func (m *Monitor) prewarmMockWorkloadChartCaches(duration time.Duration) {
+ if m == nil || duration <= 0 {
+ return
+ }
+
+ requests := mockWorkloadChartRequestsForReadState(m.GetUnifiedReadStateOrSnapshot())
+ if len(requests.vms) > 0 {
+ _ = m.GetGuestMetricsForChartBatch("vm", requests.vms, duration)
+ }
+ if len(requests.containers) > 0 {
+ _ = m.GetGuestMetricsForChartBatch("container", requests.containers, duration)
+ }
+ if len(requests.pods) > 0 {
+ _ = m.GetGuestMetricsForChartBatch("k8s", requests.pods, duration)
+ }
+ if len(requests.dockerContainers) > 0 {
+ _ = m.GetGuestMetricsForChartBatch("dockerContainer", requests.dockerContainers, duration)
+ }
+}
+
func (m *Monitor) prewarmMockDashboardChartCaches() {
if m == nil || !mock.IsMockEnabled() {
return
}
_, _ = m.mockStorageSummaryCapacityTrendCached(24 * time.Hour)
+ m.prewarmMockWorkloadChartCaches(mockDashboardWorkloadPrewarmDuration)
}
func (m *Monitor) mockGuestMetricsForChart(
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index 77c499d814..d41e9b2eee 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -1,6 +1,7 @@
package monitoring
import (
+ "context"
"fmt"
"os"
"sort"
@@ -51,6 +52,73 @@ func suppressMonitoringTestLogs(t *testing.T) {
t.Helper()
}
+func TestStartMockMetricsSampler_PrewarmsDefaultWorkloadChartCaches(t *testing.T) {
+ setMockSamplerTestEnv(t, time.Hour, 5*time.Minute)
+
+ previousEnabled := mock.IsMockEnabled()
+ previousConfig := mock.GetConfig()
+ t.Cleanup(func() {
+ mock.SetEnabled(false)
+ mock.SetMockConfig(previousConfig)
+ if previousEnabled {
+ mock.SetEnabled(true)
+ mock.SetMockConfig(previousConfig)
+ }
+ })
+
+ cfg := compactMockFixtureConfig()
+ cfg.VMsPerNode = 1
+ cfg.LXCsPerNode = 1
+ cfg.DockerHostCount = 1
+ cfg.DockerContainersPerHost = 1
+ cfg.K8sClusterCount = 1
+ cfg.K8sNodesPerCluster = 1
+ cfg.K8sPodsPerCluster = 1
+
+ mock.SetEnabled(false)
+ mock.SetMockConfig(cfg)
+ mock.SetEnabled(true)
+
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(128, 24*time.Hour),
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ monitor.startMockMetricsSampler(ctx)
+ defer monitor.stopMockMetricsSampler()
+
+ requests := mockWorkloadChartRequestsForReadState(monitor.GetUnifiedReadStateOrSnapshot())
+ assertPrewarmed := func(resourceType string, requests []GuestChartRequest) {
+ t.Helper()
+ if len(requests) == 0 {
+ t.Fatalf("expected %s workload chart prewarm requests", resourceType)
+ }
+
+ request := requests[0]
+ key := mockChartMetricMapCacheKey{
+ kind: "guest",
+ resourceType: resourceType,
+ resourceID: request.SQLResourceID,
+ aux: request.InMemoryKey,
+ duration: mockDashboardWorkloadPrewarmDuration,
+ }
+ cached, ok := monitor.readMockChartMetricMapCache(key)
+ if !ok {
+ t.Fatalf("expected prewarmed %s cache entry for %+v", resourceType, key)
+ }
+ if len(cached["cpu"]) == 0 {
+ t.Fatalf("expected prewarmed %s cache entry to include cpu points", resourceType)
+ }
+ }
+
+ assertPrewarmed("vm", requests.vms)
+ assertPrewarmed("container", requests.containers)
+ assertPrewarmed("k8s", requests.pods)
+ assertPrewarmed("dockerContainer", requests.dockerContainers)
+}
+
func newChartBatchSLOMonitor(t *testing.T) *Monitor {
t.Helper()
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index f3099d3db4..6f346a0ea0 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -3055,6 +3055,7 @@ index 1111111..2222222 100644
"frontend-modern/src/components/Workloads/__tests__/workloadUrlSyncModel.test.ts",
"frontend-modern/src/pages/__tests__/Workloads.helpers.test.ts",
"frontend-modern/src/utils/__tests__/thresholdSliderPresentation.test.ts",
+ "frontend-modern/src/utils/__tests__/workloadsSummaryCache.test.ts",
],
}
],