This commit is contained in:
seb
2026-10-13 17:49:52 +02:00
parent 345d6f5752
commit bc583a180f
3 changed files with 930 additions and 299 deletions

View File

@@ -2,6 +2,13 @@
* @file orderAutomat.js * @file orderAutomat.js
* @description Manages cached and chunk-paginated company sales orders (`GET /api/order`). * @description Manages cached and chunk-paginated company sales orders (`GET /api/order`).
* *
* Implements a multi-filter chunk cache:
* - Each filter combination has its own isolated cache entry (total, items array, loadedChunks).
* - Total chunk capacity across all filter combinations is bounded by a global LRU (Least Recently Used) limit of 50 chunks.
* - When filter settings change, previously loaded chunks remain cached in memory up to the 50-chunk limit.
* - Switching back to a previously used filter is instant with zero network requests if its chunks are in RAM.
* - Real-time stats and events can be observed via `subscribeChunkStats` or the dev ChunkCacheMonitor.
*
* Upstream Triggers: * Upstream Triggers:
* - `authAutomat`: Triggers `actions.reset()` on `'anon'` or when `selectedCompanyId` changes. * - `authAutomat`: Triggers `actions.reset()` on `'anon'` or when `selectedCompanyId` changes.
* - UI / Routes: Calls `getItems()`, `requireChunk(chunkIndex)`, `loadChunk(chunkIndex)`, or `reload()`. * - UI / Routes: Calls `getItems()`, `requireChunk(chunkIndex)`, `loadChunk(chunkIndex)`, or `reload()`.
@@ -40,11 +47,18 @@ import authAutomat from './authAutomat';
* @typedef {Object} OrderAutomatState * @typedef {Object} OrderAutomatState
* @property {Order[]|null} items Pre-filled array of orders/nulls, initially null. * @property {Order[]|null} items Pre-filled array of orders/nulls, initially null.
* @property {number} total Total unpaged count for pagination calculation. * @property {number} total Total unpaged count for pagination calculation.
* @property {string} filter Search term.
* @property {boolean} onlyUnpaid Unpaid orders only.
* @property {boolean} onlyUndelivered Undelivered orders only.
* @property {number} seekMonths Seek month count.
* @property {number} seekYears Seek year count.
* @property {number} negativeSeekMonths Negative seek months offset.
* @property {'idle'|'loading'|'ready'|'failed'} status Load lifecycle state. * @property {'idle'|'loading'|'ready'|'failed'} status Load lifecycle state.
* @property {Error|string|null} error Last load error. * @property {Error|string|null} error Last load error.
*/ */
export const CHUNK_SIZE = 50; export const CHUNK_SIZE = 50;
export const MAX_LRU_CHUNKS = 50;
const PREFETCH_CHUNKS = 1; const PREFETCH_CHUNKS = 1;
const CHUNK_DEBOUNCE_MS = 130; const CHUNK_DEBOUNCE_MS = 130;
@@ -67,24 +81,194 @@ let filterDebounceTimer = null;
let chunkDebounceTimer = null; let chunkDebounceTimer = null;
let currentEventTick = 0; let currentEventTick = 0;
let lastRequireChunkTick = -1; let lastRequireChunkTick = -1;
const pendingTargetChunks = new Set(); const pendingTargetChunks = new Set();
let pendingChunkPromise = null; let pendingChunkPromise = null;
let pendingChunkResolve = null; let pendingChunkResolve = null;
let pendingChunkReject = null; let pendingChunkReject = null;
const loadedChunks = new Set();
// Multi-Filter Cache & Global LRU Management
// filterCaches: Map<filterKey, FilterCacheEntry>
const filterCaches = new Map();
// lruChunks: Map<lruKey, { filterKey, chunkIndex, loadedAt, accessedAt, orderCount }>
// In JS, Map keys iteration preserves insertion order. Oldest (LRU) is lruChunks.keys().next().value.
const lruChunks = new Map();
// inflightChunks: Map<inflightKey, Promise>
const inflightChunks = new Map(); const inflightChunks = new Map();
// Dev / Observability: Chunk event history and subscriber registry // Dev / Observability: Chunk event history and subscriber registry
const MAX_CHUNK_EVENTS = 120; const MAX_CHUNK_EVENTS = 150;
let nextEventId = 0; let nextEventId = 0;
const chunkEvents = []; const chunkEvents = [];
const chunkStatsListeners = new Set(); const chunkStatsListeners = new Set();
export function makeLruKey(filterKey, chunkIndex) {
return `${filterKey}:::${chunkIndex}`;
}
export function parseLruKey(key) {
const [filterKey, chunkStr] = key.split(':::');
return { filterKey, chunkIndex: Number(chunkStr) };
}
// MARK: pure filter helpers
export function getFilterParams(state = automat?.state || initialState) {
const filter = String(state.filter ?? '').trim();
const onlyUnpaid = Boolean(state.onlyUnpaid);
const onlyUndelivered = Boolean(state.onlyUndelivered);
const negativeSeekMonths = (state.negativeSeekMonths != null && Number(state.negativeSeekMonths) < 0)
? Number(state.negativeSeekMonths)
: 0;
return { filter, onlyUnpaid, onlyUndelivered, negativeSeekMonths };
}
export function getFilterKey(state = automat?.state || initialState) {
const { filter, onlyUnpaid, onlyUndelivered, negativeSeekMonths } = getFilterParams(state);
return JSON.stringify({ f: filter, u: onlyUnpaid, d: onlyUndelivered, s: negativeSeekMonths });
}
export function formatFilterLabel(filterKeyOrState) {
let f, u, d, s;
if (typeof filterKeyOrState === 'string') {
try {
const parsed = JSON.parse(filterKeyOrState);
f = parsed.f;
u = parsed.u;
d = parsed.d;
s = parsed.s;
} catch {
return filterKeyOrState;
}
} else if (filterKeyOrState && typeof filterKeyOrState === 'object') {
if ('f' in filterKeyOrState) {
f = filterKeyOrState.f;
u = filterKeyOrState.u;
d = filterKeyOrState.d;
s = filterKeyOrState.s;
} else {
const params = getFilterParams(filterKeyOrState);
f = params.filter;
u = params.onlyUnpaid;
d = params.onlyUndelivered;
s = params.negativeSeekMonths;
}
}
const parts = [];
if (f) parts.push(`Suche: „${f}“`);
if (u) parts.push('Nur unbezahlt');
if (d) parts.push('Nur ungeliefert');
if (s < 0) parts.push(`Seek: ${formatNegativeSeek(s)}`);
if (parts.length === 0) return 'Standard (Alle Aufträge)';
return parts.join(' · ');
}
function countNonNullItems(items) {
if (!Array.isArray(items)) return 0;
let count = 0;
for (let i = 0; i < items.length; i++) {
if (items[i] != null) count++;
}
return count;
}
function getOrCreateFilterCache(filterKey, filterState = automat?.state || initialState) {
let entry = filterCaches.get(filterKey);
if (!entry) {
const params = getFilterParams(filterState);
entry = {
key: filterKey,
label: formatFilterLabel(params),
params,
total: 0,
items: null,
loadedChunks: new Set(),
status: 'idle',
error: null,
lastAccessed: Date.now(),
epoch: queryEpoch,
};
filterCaches.set(filterKey, entry);
}
return entry;
}
// Touch an existing chunk in the global LRU cache to mark it as Most Recently Used
function touchChunkLRU(filterKey, chunkIndex) {
const key = makeLruKey(filterKey, chunkIndex);
const existing = lruChunks.get(key);
if (existing) {
lruChunks.delete(key);
lruChunks.set(key, { ...existing, accessedAt: Date.now() });
}
}
// Register a newly loaded chunk into the LRU cache and evict the oldest if limit exceeded
function registerChunkLRU(filterKey, chunkIndex, orderCount = 0) {
const key = makeLruKey(filterKey, chunkIndex);
if (lruChunks.has(key)) {
lruChunks.delete(key);
}
const now = Date.now();
lruChunks.set(key, {
filterKey,
chunkIndex,
loadedAt: now,
accessedAt: now,
orderCount,
});
// Enforce global MAX_LRU_CHUNKS limit across all filter caches
while (lruChunks.size > MAX_LRU_CHUNKS) {
const oldestKey = lruChunks.keys().next().value;
const oldestInfo = lruChunks.get(oldestKey);
lruChunks.delete(oldestKey);
if (oldestInfo) {
evictChunkFromMemory(oldestInfo.filterKey, oldestInfo.chunkIndex, 'lru');
}
}
}
// Evicts a chunk from memory: sets items back to null in the filter cache and removes from loadedChunks
function evictChunkFromMemory(filterKey, chunkIndex, reason = 'manual') {
const entry = filterCaches.get(filterKey);
if (!entry) return;
if (entry.loadedChunks.has(chunkIndex)) {
entry.loadedChunks.delete(chunkIndex);
if (Array.isArray(entry.items)) {
const offset = chunkIndex * CHUNK_SIZE;
for (let i = offset; i < offset + CHUNK_SIZE && i < entry.items.length; i++) {
entry.items[i] = null;
}
}
const currentKey = getFilterKey(automat.state);
if (filterKey === currentKey) {
automat.setState({ items: [...entry.items] });
}
const eventType = reason === 'lru' ? 'lru_evict' : 'evict';
const msg = reason === 'lru'
? `LRU-Eviction: Chunk #${chunkIndex} von Filter "${entry.label}" verworfen (${lruChunks.size}/${MAX_LRU_CHUNKS} im Cache)`
: `Chunk #${chunkIndex} von Filter "${entry.label}" verworfen`;
recordChunkEvent({
type: eventType,
chunkIndex,
filterKey,
message: msg,
});
notifyChunkStats();
}
}
function recordChunkEvent(entry) { function recordChunkEvent(entry) {
const event = { const event = {
id: ++nextEventId, id: ++nextEventId,
time: Date.now(), time: Date.now(),
epoch: queryEpoch, epoch: queryEpoch,
filterKey: entry.filterKey ?? getFilterKey(automat?.state),
...entry, ...entry,
}; };
chunkEvents.push(event); chunkEvents.push(event);
@@ -107,23 +291,61 @@ function notifyChunkStats() {
} }
export function getChunkStats() { export function getChunkStats() {
const total = automat?.state?.total ?? 0; const currentKey = getFilterKey(automat?.state);
const chunkCount = total > 0 ? Math.ceil(total / CHUNK_SIZE) : (loadedChunks.size > 0 ? Math.max(...loadedChunks) + 1 : 0); const activeEntry = filterCaches.get(currentKey);
const items = automat?.state?.items;
let loadedItemsCount = 0; const total = activeEntry?.total ?? automat?.state?.total ?? 0;
if (Array.isArray(items)) { const activeLoaded = activeEntry?.loadedChunks ?? new Set();
for (let i = 0; i < items.length; i++) { const chunkCount = total > 0 ? Math.ceil(total / CHUNK_SIZE) : (activeLoaded.size > 0 ? Math.max(...activeLoaded) + 1 : 0);
if (items[i] != null) loadedItemsCount++; const items = activeEntry?.items ?? automat?.state?.items;
const loadedItemsCount = countNonNullItems(items);
// Summarize all cached filter combinations
const cachedFiltersSummary = Array.from(filterCaches.values()).map((entry) => ({
key: entry.key,
label: entry.label,
params: entry.params,
total: entry.total,
loadedChunksCount: entry.loadedChunks.size,
loadedChunks: Array.from(entry.loadedChunks).sort((a, b) => a - b),
chunkCount: entry.total > 0 ? Math.ceil(entry.total / CHUNK_SIZE) : (entry.loadedChunks.size > 0 ? Math.max(...entry.loadedChunks) + 1 : 0),
loadedItemsCount: countNonNullItems(entry.items),
lastAccessed: entry.lastAccessed,
isActive: entry.key === currentKey,
status: entry.status,
items: entry.items,
}));
// LRU queue list from oldest (1) to newest (50)
const lruEntries = Array.from(lruChunks.entries()).map(([key, info], idx) => ({
lruKey: key,
filterKey: info.filterKey,
filterLabel: filterCaches.get(info.filterKey)?.label || info.filterKey,
chunkIndex: info.chunkIndex,
loadedAt: info.loadedAt,
accessedAt: info.accessedAt,
orderCount: info.orderCount,
lruRank: idx + 1,
}));
// Active filter's inflight chunks
const activeInflight = [];
for (const key of inflightChunks.keys()) {
if (key.startsWith(`${currentKey}:::`)) {
const parsed = parseLruKey(key);
activeInflight.push(parsed.chunkIndex);
} }
} }
return { return {
automatName: 'order', automatName: 'order',
chunkSize: CHUNK_SIZE, chunkSize: CHUNK_SIZE,
maxLruChunks: MAX_LRU_CHUNKS,
lruChunksCount: lruChunks.size,
total, total,
chunkCount, chunkCount,
loadedChunks: Array.from(loadedChunks).sort((a, b) => a - b), loadedChunks: Array.from(activeLoaded).sort((a, b) => a - b),
inflightChunks: Array.from(inflightChunks.keys()).sort((a, b) => a - b), inflightChunks: activeInflight.sort((a, b) => a - b),
pendingChunks: Array.from(pendingTargetChunks).sort((a, b) => a - b), pendingChunks: Array.from(pendingTargetChunks).sort((a, b) => a - b),
loadedItemsCount, loadedItemsCount,
status: automat?.state?.status ?? 'idle', status: automat?.state?.status ?? 'idle',
@@ -133,6 +355,10 @@ export function getChunkStats() {
onlyUndelivered: automat?.state?.onlyUndelivered ?? false, onlyUndelivered: automat?.state?.onlyUndelivered ?? false,
negativeSeekMonths: automat?.state?.negativeSeekMonths ?? 0, negativeSeekMonths: automat?.state?.negativeSeekMonths ?? 0,
items, items,
activeFilterKey: currentKey,
activeFilterLabel: formatFilterLabel(currentKey),
filterCaches: cachedFiltersSummary,
lruEntries,
events: [...chunkEvents], events: [...chunkEvents],
}; };
} }
@@ -165,7 +391,7 @@ function clearChunkDebounce() {
} }
// Executes chunk loading for the standstill target and prefetches lookahead chunks // Executes chunk loading for the standstill target and prefetches lookahead chunks
function _executeRequiredChunks(chunks, targetEpoch, prefetch = true) { function _executeRequiredChunks(chunks, targetEpoch, prefetch = true, targetFilterKey = getFilterKey(automat.state)) {
if (targetEpoch !== queryEpoch) { if (targetEpoch !== queryEpoch) {
return Promise.resolve(automat.state.items); return Promise.resolve(automat.state.items);
} }
@@ -178,12 +404,13 @@ function _executeRequiredChunks(chunks, targetEpoch, prefetch = true) {
recordChunkEvent({ recordChunkEvent({
type: 'execute', type: 'execute',
chunks: chunkList, chunks: chunkList,
message: `Lade Chunks [${chunkList.join(', ')}] (Epoch ${targetEpoch})`, filterKey: targetFilterKey,
message: `Lade Chunks [${chunkList.join(', ')}] für "${formatFilterLabel(targetFilterKey)}" (Epoch ${targetEpoch})`,
}); });
const promises = []; const promises = [];
for (const c of chunkList) { for (const c of chunkList) {
promises.push(actions.loadChunk(c, targetEpoch)); promises.push(actions.loadChunk(c, targetEpoch, targetFilterKey));
} }
// Once active chunks finish loading, prefetch the next lookahead chunk in the background // Once active chunks finish loading, prefetch the next lookahead chunk in the background
@@ -191,7 +418,8 @@ function _executeRequiredChunks(chunks, targetEpoch, prefetch = true) {
if (targetEpoch !== queryEpoch) return automat.state.items; if (targetEpoch !== queryEpoch) return automat.state.items;
if (prefetch) { if (prefetch) {
const maxChunk = chunkList[chunkList.length - 1]; const maxChunk = chunkList[chunkList.length - 1];
const total = automat.state.total || 0; const entry = filterCaches.get(targetFilterKey);
const total = entry?.total || automat.state.total || 0;
for (let c = maxChunk + 1; c <= maxChunk + PREFETCH_CHUNKS; c++) { for (let c = maxChunk + 1; c <= maxChunk + PREFETCH_CHUNKS; c++) {
if (total > 0 && c * CHUNK_SIZE >= total) { if (total > 0 && c * CHUNK_SIZE >= total) {
break; break;
@@ -199,9 +427,10 @@ function _executeRequiredChunks(chunks, targetEpoch, prefetch = true) {
recordChunkEvent({ recordChunkEvent({
type: 'prefetch', type: 'prefetch',
chunkIndex: c, chunkIndex: c,
message: `Prefetch Chunk #${c}`, filterKey: targetFilterKey,
message: `Prefetch Chunk #${c} für "${formatFilterLabel(targetFilterKey)}"`,
}); });
void actions.loadChunk(c, targetEpoch); void actions.loadChunk(c, targetEpoch, targetFilterKey);
} }
} }
return automat.state.items; return automat.state.items;
@@ -260,23 +489,22 @@ export function formatNegativeSeek(months) {
return `-${parts.join(' ')}`; return `-${parts.join(' ')}`;
} }
// Builds server query parameters from current automat filter state // Builds server query parameters from filter params
function buildQueryParams(offset = 0, limit = CHUNK_SIZE) { function buildQueryParamsFor(filterParams, offset = 0, limit = CHUNK_SIZE) {
const { filter, onlyUnpaid, onlyUndelivered, negativeSeekMonths } = automat.state;
const params = { offset, limit }; const params = { offset, limit };
const trimmed = String(filter ?? '').trim(); const trimmed = String(filterParams.filter ?? '').trim();
if (trimmed) params.search = trimmed; if (trimmed) params.search = trimmed;
if (onlyUnpaid) params.onlyUnpaid = true; if (filterParams.onlyUnpaid) params.onlyUnpaid = true;
if (onlyUndelivered) params.onlyUndelivered = true; if (filterParams.onlyUndelivered) params.onlyUndelivered = true;
if (negativeSeekMonths != null && Number(negativeSeekMonths) < 0) { if (filterParams.negativeSeekMonths != null && Number(filterParams.negativeSeekMonths) < 0) {
params.seekMonths = Number(negativeSeekMonths); params.seekMonths = Number(filterParams.negativeSeekMonths);
} }
return params; return params;
} }
// MARK: fetches a single chunk from GET /api/order with server-side filters // Fetches a single chunk from GET /api/order with server-side filters
async function fetchOrdersPage(offset = 0, limit = CHUNK_SIZE) { async function fetchOrdersPageFor(filterParams, offset = 0, limit = CHUNK_SIZE) {
const params = buildQueryParams(offset, limit); const params = buildQueryParamsFor(filterParams, offset, limit);
const res = await orderApi.list(params); const res = await orderApi.list(params);
const orders = Array.isArray(res?.orders) ? res.orders : []; const orders = Array.isArray(res?.orders) ? res.orders : [];
const total = Number(res?.total ?? orders.length); const total = Number(res?.total ?? orders.length);
@@ -298,18 +526,62 @@ function onFilterChange(immediate = false) {
} }
} }
// Invoked when active filters change: switches to the matching filter cache without wiping!
function applyFilterReload() { function applyFilterReload() {
queryEpoch++; queryEpoch++;
clearChunkDebounce(); clearChunkDebounce();
loadedChunks.clear();
inflightChunks.clear(); const currentKey = getFilterKey(automat.state);
const cached = filterCaches.get(currentKey);
if (cached && cached.items !== null) {
// CACHE HIT FOR THIS FILTER COMBINATION: restore instantly from RAM!
cached.lastAccessed = Date.now();
for (const c of cached.loadedChunks) {
touchChunkLRU(currentKey, c);
}
automat.setState({
items: cached.items,
total: cached.total,
status: cached.status || 'ready',
error: cached.error || null,
});
recordChunkEvent({ recordChunkEvent({
type: 'filter_reload', type: 'filter_hit',
epoch: queryEpoch, epoch: queryEpoch,
message: `Filter angewendet (Epoch ${queryEpoch})`, filterKey: currentKey,
message: `Filter gewechselt: "${cached.label}" (Cache-Hit: ${cached.loadedChunks.size} Chunks / ${countNonNullItems(cached.items)} Aufträge im RAM)`,
}); });
notifyChunkStats(); notifyChunkStats();
void actions.loadChunk(0, queryEpoch);
// If chunk 0 was evicted or not yet loaded in this filter, fetch chunk 0
if (!cached.loadedChunks.has(0)) {
void actions.loadChunk(0, queryEpoch, currentKey);
}
} else {
// CACHE MISS: initialize fresh filter entry and load chunk 0
const entry = getOrCreateFilterCache(currentKey, automat.state);
entry.lastAccessed = Date.now();
automat.setState({
items: null,
total: 0,
status: 'loading',
error: null,
});
recordChunkEvent({
type: 'filter_miss',
epoch: queryEpoch,
filterKey: currentKey,
message: `Filter gewechselt: "${entry.label}" (Cache-Miss: Lade Chunk #0)`,
});
notifyChunkStats();
void actions.loadChunk(0, queryEpoch, currentKey);
}
} }
const actions = { const actions = {
@@ -350,6 +622,7 @@ const actions = {
start = Math.max(0, Math.floor(start)); start = Math.max(0, Math.floor(start));
end = Math.max(start, Math.floor(end)); end = Math.max(start, Math.floor(end));
const prefetch = options.prefetch !== false; const prefetch = options.prefetch !== false;
const currentKey = getFilterKey(automat.state);
// If initial items are null or immediate requested, bypass debounce and load immediately // If initial items are null or immediate requested, bypass debounce and load immediately
if (options.immediate || automat.state.items === null) { if (options.immediate || automat.state.items === null) {
@@ -359,9 +632,10 @@ const actions = {
recordChunkEvent({ recordChunkEvent({
type: 'require_immediate', type: 'require_immediate',
chunks: Array.from(chunks), chunks: Array.from(chunks),
message: `Sofortige Anforderung: Chunks ${start}..${end}`, filterKey: currentKey,
message: `Sofortige Anforderung: Chunks ${start}..${end} (${formatFilterLabel(currentKey)})`,
}); });
return _executeRequiredChunks(chunks, queryEpoch, prefetch); return _executeRequiredChunks(chunks, queryEpoch, prefetch, currentKey);
} }
// New event tick (drag mousemove / pagination click) replaces previous target position // New event tick (drag mousemove / pagination click) replaces previous target position
@@ -385,6 +659,7 @@ const actions = {
recordChunkEvent({ recordChunkEvent({
type: 'pending', type: 'pending',
chunks: Array.from(pendingTargetChunks), chunks: Array.from(pendingTargetChunks),
filterKey: currentKey,
message: `Debounce vorgemerkt (${CHUNK_DEBOUNCE_MS}ms): Chunks [${Array.from(pendingTargetChunks).join(', ')}]`, message: `Debounce vorgemerkt (${CHUNK_DEBOUNCE_MS}ms): Chunks [${Array.from(pendingTargetChunks).join(', ')}]`,
}); });
notifyChunkStats(); notifyChunkStats();
@@ -417,10 +692,11 @@ const actions = {
recordChunkEvent({ recordChunkEvent({
type: 'debounce_fire', type: 'debounce_fire',
chunks: Array.from(chunksToLoad), chunks: Array.from(chunksToLoad),
filterKey: currentKey,
message: `Debounce abgelaufen: Starte Chunks [${Array.from(chunksToLoad).join(', ')}]`, message: `Debounce abgelaufen: Starte Chunks [${Array.from(chunksToLoad).join(', ')}]`,
}); });
_executeRequiredChunks(chunksToLoad, captureEpoch, true) _executeRequiredChunks(chunksToLoad, captureEpoch, true, currentKey)
.then((res) => resolve?.(res)) .then((res) => resolve?.(res))
.catch((err) => reject?.(err)); .catch((err) => reject?.(err));
}, CHUNK_DEBOUNCE_MS); }, CHUNK_DEBOUNCE_MS);
@@ -428,110 +704,134 @@ const actions = {
return pendingChunkPromise; return pendingChunkPromise;
}, },
// MARK: fetches a single chunk and populates prefilled array // MARK: fetches a single chunk and populates the filter cache and prefilled array
loadChunk(chunkIndex, targetEpoch = queryEpoch) { loadChunk(chunkIndex, targetEpoch = queryEpoch, targetFilterKey = getFilterKey(automat.state)) {
const index = Math.max(0, Number(chunkIndex) || 0); const index = Math.max(0, Number(chunkIndex) || 0);
if (targetEpoch !== queryEpoch) { const entry = getOrCreateFilterCache(targetFilterKey, automat.state);
return Promise.resolve(automat.state.items);
if (targetEpoch !== queryEpoch && targetFilterKey !== getFilterKey(automat.state)) {
return Promise.resolve(entry.items);
} }
if (loadedChunks.has(index)) {
if (entry.loadedChunks.has(index)) {
touchChunkLRU(targetFilterKey, index);
recordChunkEvent({ recordChunkEvent({
type: 'hit', type: 'hit',
chunkIndex: index, chunkIndex: index,
message: `Cache-Hit: Chunk #${index} bereits im Speicher`, filterKey: targetFilterKey,
message: `Cache-Hit: Chunk #${index} für Filter "${entry.label}" bereits im Speicher`,
}); });
return Promise.resolve(automat.state.items); return Promise.resolve(targetFilterKey === getFilterKey(automat.state) ? automat.state.items : entry.items);
} }
if (inflightChunks.has(index)) {
const inflightKey = makeLruKey(targetFilterKey, index);
if (inflightChunks.has(inflightKey)) {
recordChunkEvent({ recordChunkEvent({
type: 'inflight_hit', type: 'inflight_hit',
chunkIndex: index, chunkIndex: index,
message: `Inflight-Hit: Chunk #${index} lädt bereits`, filterKey: targetFilterKey,
message: `Inflight-Hit: Chunk #${index} für Filter "${entry.label}" lädt bereits`,
}); });
return inflightChunks.get(index); return inflightChunks.get(inflightKey);
} }
const offset = index * CHUNK_SIZE; const offset = index * CHUNK_SIZE;
const limit = CHUNK_SIZE; const limit = CHUNK_SIZE;
if (index === 0 && automat.state.items === null) { const isActiveFilter = targetFilterKey === getFilterKey(automat.state);
if (index === 0 && (entry.items === null || (isActiveFilter && automat.state.items === null))) {
entry.status = 'loading';
entry.error = null;
if (isActiveFilter) {
automat.setState({ status: 'loading', error: null }); automat.setState({ status: 'loading', error: null });
} }
}
const startTime = Date.now(); const startTime = Date.now();
recordChunkEvent({ recordChunkEvent({
type: 'start', type: 'start',
chunkIndex: index, chunkIndex: index,
message: `Netzwerk-Request: Lade Chunk #${index} (Offset ${offset}..${offset + limit - 1})`, filterKey: targetFilterKey,
message: `Netzwerk-Request: Lade Chunk #${index} (Offset ${offset}..${offset + limit - 1}) für "${entry.label}"`,
}); });
const promise = fetchOrdersPage(offset, limit) const filterParams = entry.params || getFilterParams(automat.state);
const promise = fetchOrdersPageFor(filterParams, offset, limit)
.then(({ orders, total }) => { .then(({ orders, total }) => {
// Discard if active filter query changed while request was in flight
if (targetEpoch !== queryEpoch) {
return automat.state.items;
}
let items = automat.state.items;
const currentTotal = total > 0 ? total : 0; const currentTotal = total > 0 ? total : 0;
entry.total = currentTotal;
if (items === null || items.length !== currentTotal) { if (entry.items === null || entry.items.length !== currentTotal) {
// Pre-fill items array with empty (null) items based on server filtered total entry.items = new Array(currentTotal).fill(null);
items = new Array(currentTotal).fill(null);
} else { } else {
items = [...items]; entry.items = [...entry.items];
} }
// Fill in real received items for this chunk // Fill in real received items for this chunk
for (let i = 0; i < orders.length; i++) { for (let i = 0; i < orders.length; i++) {
const idx = offset + i; const idx = offset + i;
if (idx < items.length) { if (idx < entry.items.length) {
items[idx] = orders[i]; entry.items[idx] = orders[i];
} }
} }
const duration = Date.now() - startTime; entry.loadedChunks.add(index);
loadedChunks.add(index); entry.status = 'ready';
entry.error = null;
entry.lastAccessed = Date.now();
// Register chunk in global LRU (evicts oldest chunk if > MAX_LRU_CHUNKS)
registerChunkLRU(targetFilterKey, index, orders.length);
const currentActive = targetFilterKey === getFilterKey(automat.state);
if (currentActive) {
automat.setState({ automat.setState({
items, items: entry.items,
total: currentTotal, total: currentTotal,
status: 'ready', status: 'ready',
error: null, error: null,
}); });
}
const duration = Date.now() - startTime;
recordChunkEvent({ recordChunkEvent({
type: 'loaded', type: 'loaded',
chunkIndex: index, chunkIndex: index,
filterKey: targetFilterKey,
count: orders.length, count: orders.length,
duration, duration,
message: `Chunk #${index} geladen (${orders.length} Aufträge in ${duration}ms)`, message: `Chunk #${index} geladen (${orders.length} Aufträge in ${duration}ms) für "${entry.label}"`,
}); });
return items; return currentActive ? automat.state.items : entry.items;
}) })
.catch((err) => { .catch((err) => {
if (targetEpoch === queryEpoch) { entry.status = 'failed';
const duration = Date.now() - startTime; entry.error = err;
console.error(`[orderAutomat] loadChunk(${index}) error:`, err); const currentActive = targetFilterKey === getFilterKey(automat.state);
recordChunkEvent({ if (currentActive) {
type: 'error',
chunkIndex: index,
duration,
error: err?.message || String(err),
message: `Fehler bei Chunk #${index}: ${err?.message || err}`,
});
if (index === 0 && automat.state.items === null) { if (index === 0 && automat.state.items === null) {
automat.setState({ status: 'failed', error: err }); automat.setState({ status: 'failed', error: err });
} }
} }
const duration = Date.now() - startTime;
console.error(`[orderAutomat] loadChunk(${index}, ${targetFilterKey}) error:`, err);
recordChunkEvent({
type: 'error',
chunkIndex: index,
filterKey: targetFilterKey,
duration,
error: err?.message || String(err),
message: `Fehler bei Chunk #${index} ("${entry.label}"): ${err?.message || err}`,
});
throw err; throw err;
}) })
.finally(() => { .finally(() => {
inflightChunks.delete(index); inflightChunks.delete(inflightKey);
notifyChunkStats(); notifyChunkStats();
}); });
inflightChunks.set(index, promise); inflightChunks.set(inflightKey, promise);
notifyChunkStats(); notifyChunkStats();
return promise; return promise;
}, },
@@ -600,7 +900,7 @@ const actions = {
// MARK: initial load // MARK: initial load
load() { load() {
return actions.loadChunk(0, queryEpoch); return actions.loadChunk(0, queryEpoch, getFilterKey(automat.state));
}, },
// MARK: ensure loaded // MARK: ensure loaded
@@ -608,27 +908,43 @@ const actions = {
if (automat.state.items !== null) { if (automat.state.items !== null) {
return Promise.resolve(automat.state.items); return Promise.resolve(automat.state.items);
} }
return actions.loadChunk(0, queryEpoch); return actions.loadChunk(0, queryEpoch, getFilterKey(automat.state));
}, },
// MARK: reload with current active server filters // MARK: reload active filter or invalidate all
async reload() { async reload(onlyCurrent = false) {
queryEpoch++; queryEpoch++;
clearChunkDebounce(); clearChunkDebounce();
loadedChunks.clear();
inflightChunks.clear(); if (onlyCurrent) {
await actions.loadChunk(0, queryEpoch); // Invalidate only current filter's cached chunks
const currentKey = getFilterKey(automat.state);
actions.clearFilterCache(currentKey);
} else {
// Full reload (e.g. after SSE mutation or document deletion): clear all cached data
actions.clearCache();
}
await actions.loadChunk(0, queryEpoch, getFilterKey(automat.state));
return automat.state.items; return automat.state.items;
}, },
// MARK: replace items directly // MARK: replace items directly
replace(items) { replace(items) {
clearChunkDebounce(); clearChunkDebounce();
loadedChunks.clear(); const currentKey = getFilterKey(automat.state);
inflightChunks.clear(); actions.clearFilterCache(currentKey);
const count = Array.isArray(items) ? items.length : 0; const count = Array.isArray(items) ? items.length : 0;
const entry = getOrCreateFilterCache(currentKey, automat.state);
entry.items = items;
entry.total = count;
entry.status = 'ready';
entry.error = null;
recordChunkEvent({ recordChunkEvent({
type: 'replace', type: 'replace',
filterKey: currentKey,
message: `Items ersetzt (${count} Einträge)`, message: `Items ersetzt (${count} Einträge)`,
}); });
notifyChunkStats(); notifyChunkStats();
@@ -641,67 +957,119 @@ const actions = {
return items; return items;
}, },
// MARK: evicts a specific chunk from cache for testing // MARK: evicts a specific chunk from cache (optional filterKey, defaults to active)
evictChunk(chunkIndex) { evictChunk(chunkIndex, filterKey = getFilterKey(automat.state)) {
const index = Math.max(0, Number(chunkIndex) || 0); const index = Math.max(0, Number(chunkIndex) || 0);
if (!loadedChunks.has(index)) return automat.state.items; const key = makeLruKey(filterKey, index);
loadedChunks.delete(index); if (lruChunks.has(key)) {
let items = automat.state.items; lruChunks.delete(key);
if (Array.isArray(items)) {
items = [...items];
const offset = index * CHUNK_SIZE;
for (let i = offset; i < offset + CHUNK_SIZE && i < items.length; i++) {
items[i] = null;
} }
automat.setState({ items }); evictChunkFromMemory(filterKey, index, 'manual');
return automat.state.items;
},
// MARK: clears a specific filter cache and removes its chunks from LRU
clearFilterCache(filterKey = getFilterKey(automat.state)) {
// Remove all chunks of this filter from LRU
for (const [lruKey, info] of Array.from(lruChunks.entries())) {
if (info.filterKey === filterKey) {
lruChunks.delete(lruKey);
} }
}
const entry = filterCaches.get(filterKey);
if (entry) {
entry.loadedChunks.clear();
entry.items = null;
entry.total = 0;
entry.status = 'idle';
entry.error = null;
}
if (filterKey === getFilterKey(automat.state)) {
automat.setState({
items: null,
total: 0,
status: 'idle',
error: null,
});
}
recordChunkEvent({ recordChunkEvent({
type: 'evict', type: 'clear_filter',
chunkIndex: index, filterKey,
message: `Chunk #${index} aus Cache entfernt (evicted)`, message: `Filter-Cache für "${formatFilterLabel(filterKey)}" geleert`,
}); });
notifyChunkStats(); notifyChunkStats();
return automat.state.items; return automat.state.items;
}, },
// MARK: clears all loaded chunks from cache // MARK: clears all loaded chunks and filter caches from RAM
clearCache() { clearCache() {
clearChunkDebounce(); clearChunkDebounce();
loadedChunks.clear(); lruChunks.clear();
inflightChunks.clear(); inflightChunks.clear();
let items = automat.state.items;
if (Array.isArray(items)) { for (const entry of filterCaches.values()) {
items = new Array(automat.state.total || 0).fill(null); entry.loadedChunks.clear();
automat.setState({ items }); entry.items = null;
entry.total = 0;
entry.status = 'idle';
entry.error = null;
} }
automat.setState({
items: null,
total: 0,
status: 'idle',
error: null,
});
recordChunkEvent({ recordChunkEvent({
type: 'clear', type: 'clear',
message: 'Alle Chunks aus dem Cache entfernt', message: 'Gesamter LRU-Cache und alle Filter-Caches geleert',
}); });
notifyChunkStats(); notifyChunkStats();
return automat.state.items; return automat.state.items;
}, },
// MARK: prefetches all remaining chunks // MARK: prefetches all remaining chunks for a filter (bounded by MAX_LRU_CHUNKS)
prefetchAllChunks() { prefetchAllChunks(filterKey = getFilterKey(automat.state)) {
const total = automat.state.total || 0; const entry = getOrCreateFilterCache(filterKey, automat.state);
const total = entry.total || automat.state.total || 0;
const chunkCount = Math.ceil(total / CHUNK_SIZE); const chunkCount = Math.ceil(total / CHUNK_SIZE);
recordChunkEvent({ recordChunkEvent({
type: 'prefetch_all', type: 'prefetch_all',
message: `Starte Prefetch aller ${chunkCount} Chunks`, filterKey,
message: `Starte Prefetch aller ${chunkCount} Chunks für "${entry.label}"`,
}); });
for (let c = 0; c < chunkCount; c++) { for (let c = 0; c < chunkCount; c++) {
if (!loadedChunks.has(c) && !inflightChunks.has(c)) { const inflightKey = makeLruKey(filterKey, c);
void actions.loadChunk(c, queryEpoch); if (!entry.loadedChunks.has(c) && !inflightChunks.has(inflightKey)) {
void actions.loadChunk(c, queryEpoch, filterKey);
} }
} }
notifyChunkStats(); notifyChunkStats();
}, },
// MARK: patches an order locally in the automat items cache // MARK: patches an order locally across all filter caches
patchOrder(id, patch) { patchOrder(id, patch) {
if (!Array.isArray(automat.state.items)) return automat.state.items;
let changed = false; let changed = false;
for (const entry of filterCaches.values()) {
if (Array.isArray(entry.items)) {
entry.items = entry.items.map((o) => {
if (o && o.id === id) {
changed = true;
return { ...o, ...patch };
}
return o;
});
}
}
if (Array.isArray(automat.state.items)) {
const items = automat.state.items.map((o) => { const items = automat.state.items.map((o) => {
if (o && o.id === id) { if (o && o.id === id) {
changed = true; changed = true;
@@ -712,10 +1080,11 @@ const actions = {
if (changed) { if (changed) {
automat.setState({ items }); automat.setState({ items });
} }
return items; }
return automat.state.items;
}, },
// MARK: resets state // MARK: resets state and all caches completely (e.g. on logout / company switch)
reset() { reset() {
queryEpoch++; queryEpoch++;
if (filterDebounceTimer) { if (filterDebounceTimer) {
@@ -723,11 +1092,13 @@ const actions = {
filterDebounceTimer = null; filterDebounceTimer = null;
} }
clearChunkDebounce(); clearChunkDebounce();
loadedChunks.clear(); filterCaches.clear();
lruChunks.clear();
inflightChunks.clear(); inflightChunks.clear();
recordChunkEvent({ recordChunkEvent({
type: 'reset', type: 'reset',
message: 'Order-Automat zurückgesetzt', message: 'Order-Automat und sämtliche Caches zurückgesetzt',
}); });
notifyChunkStats(); notifyChunkStats();
automat.setState(initialState); automat.setState(initialState);
@@ -749,11 +1120,15 @@ export function requireChunk(chunkIndex, endOrOptions, maybeOptions) {
orderAutomat.getItems = getItems; orderAutomat.getItems = getItems;
orderAutomat.requireChunk = requireChunk; orderAutomat.requireChunk = requireChunk;
orderAutomat.CHUNK_SIZE = CHUNK_SIZE; orderAutomat.CHUNK_SIZE = CHUNK_SIZE;
orderAutomat.MAX_LRU_CHUNKS = MAX_LRU_CHUNKS;
orderAutomat.getChunkStats = getChunkStats; orderAutomat.getChunkStats = getChunkStats;
orderAutomat.subscribeChunkStats = subscribeChunkStats; orderAutomat.subscribeChunkStats = subscribeChunkStats;
orderAutomat.evictChunk = actions.evictChunk; orderAutomat.evictChunk = actions.evictChunk;
orderAutomat.clearFilterCache = actions.clearFilterCache;
orderAutomat.clearCache = actions.clearCache; orderAutomat.clearCache = actions.clearCache;
orderAutomat.prefetchAllChunks = actions.prefetchAllChunks; orderAutomat.prefetchAllChunks = actions.prefetchAllChunks;
orderAutomat.getFilterKey = getFilterKey;
orderAutomat.formatFilterLabel = formatFilterLabel;
// Reset on logout or company change // Reset on logout or company change
let lastCompanyId = null; let lastCompanyId = null;

View File

@@ -222,6 +222,7 @@ class OrderSearchField extends PureComponent {
constructor(props) { constructor(props) {
super(props); super(props);
const s = orderAutomat.state; const s = orderAutomat.state;
const stats = orderAutomat.getChunkStats?.();
this.state = { this.state = {
input: s.filter ?? '', input: s.filter ?? '',
onlyUnpaid: s.onlyUnpaid ?? false, onlyUnpaid: s.onlyUnpaid ?? false,
@@ -229,6 +230,9 @@ class OrderSearchField extends PureComponent {
seekMonths: s.seekMonths ?? 0, seekMonths: s.seekMonths ?? 0,
seekYears: s.seekYears ?? 0, seekYears: s.seekYears ?? 0,
negativeSeekMonths: s.negativeSeekMonths ?? 0, negativeSeekMonths: s.negativeSeekMonths ?? 0,
lruChunksCount: stats?.lruChunksCount || 0,
maxLruChunks: stats?.maxLruChunks || 50,
filterCachesCount: stats?.filterCaches?.length || 1,
}; };
} }
@@ -241,10 +245,20 @@ class OrderSearchField extends PureComponent {
seekYears: state.seekYears ?? 0, seekYears: state.seekYears ?? 0,
negativeSeekMonths: state.negativeSeekMonths ?? 0, negativeSeekMonths: state.negativeSeekMonths ?? 0,
})); }));
if (import.meta.env.DEV) {
this.unsubStats = orderAutomat.subscribeChunkStats?.((stats) => {
this.setState({
lruChunksCount: stats.lruChunksCount,
maxLruChunks: stats.maxLruChunks,
filterCachesCount: stats.filterCaches?.length || 1,
});
});
}
} }
componentWillUnmount() { componentWillUnmount() {
this.unsub?.(); this.unsub?.();
this.unsubStats?.();
} }
render() { render() {
@@ -427,11 +441,11 @@ class OrderSearchField extends PureComponent {
</Box> </Box>
{import.meta.env.DEV && ( {import.meta.env.DEV && (
<Tooltip title="Chunk-Cache-Monitor öffnen (Alt+Shift+C)"> <Tooltip title={`Chunk-Cache-Monitor öffnen (Alt+Shift+C) — ${this.state.lruChunksCount || 0}/${this.state.maxLruChunks || 50} Chunks im RAM über ${this.state.filterCachesCount || 1} Filter`}>
<Chip <Chip
size="small" size="small"
icon={<ViewModuleIcon sx={{ fontSize: 16 }} />} icon={<ViewModuleIcon sx={{ fontSize: 16 }} />}
label="Chunk-Cache" label={this.state.lruChunksCount > 0 ? `Chunk-Cache (${this.state.lruChunksCount}/${this.state.maxLruChunks || 50})` : 'Chunk-Cache'}
onClick={() => window.dispatchEvent(new CustomEvent('dash:toggle-chunk-monitor'))} onClick={() => window.dispatchEvent(new CustomEvent('dash:toggle-chunk-monitor'))}
sx={{ sx={{
cursor: 'pointer', cursor: 'pointer',

View File

@@ -19,7 +19,6 @@ import ViewModuleIcon from '@mui/icons-material/ViewModule';
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from '@mui/icons-material/Close';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator'; import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import RefreshIcon from '@mui/icons-material/Refresh'; import RefreshIcon from '@mui/icons-material/Refresh';
import DeleteSweepIcon from '@mui/icons-material/DeleteSweep';
import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined'; import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined';
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty'; import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty';
import CloudDownloadIcon from '@mui/icons-material/CloudDownload'; import CloudDownloadIcon from '@mui/icons-material/CloudDownload';
@@ -29,17 +28,21 @@ import HistoryIcon from '@mui/icons-material/History';
import GridViewIcon from '@mui/icons-material/GridView'; import GridViewIcon from '@mui/icons-material/GridView';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined'; import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import ArrowBackIcon from '@mui/icons-material/ArrowBack'; import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import LayersIcon from '@mui/icons-material/Layers';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import WarningAmberIcon from '@mui/icons-material/WarningAmber';
import orderAutomat, { import orderAutomat, {
CHUNK_SIZE, CHUNK_SIZE,
MAX_LRU_CHUNKS,
isOrderPaid, isOrderPaid,
isOrderDelivered, isOrderDelivered,
subscribeChunkStats, subscribeChunkStats,
} from '../automats/orderAutomat'; } from '../automats/orderAutomat';
import { formatPrice } from '../utils/price'; import { formatPrice } from '../utils/price';
const PANEL_WIDTH = 620; const PANEL_WIDTH = 680;
const PANEL_HEIGHT = 480; const PANEL_HEIGHT = 520;
const pulseAnimationA = keyframes` const pulseAnimationA = keyframes`
0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(25, 118, 210, 0); } 0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(25, 118, 210, 0); }
@@ -69,14 +72,10 @@ function orderGrossTotal(lines) {
class ChunkCacheMonitor extends PureComponent { class ChunkCacheMonitor extends PureComponent {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { const initialStats = orderAutomat.getChunkStats?.() || {
open: false,
position: null,
tab: 'grid', // 'grid' | 'log'
selectedChunk: null,
pulseCounter: 0,
stats: orderAutomat.getChunkStats?.() || {
chunkSize: CHUNK_SIZE, chunkSize: CHUNK_SIZE,
maxLruChunks: MAX_LRU_CHUNKS,
lruChunksCount: 0,
total: 0, total: 0,
chunkCount: 0, chunkCount: 0,
loadedChunks: [], loadedChunks: [],
@@ -90,8 +89,21 @@ class ChunkCacheMonitor extends PureComponent {
onlyUndelivered: false, onlyUndelivered: false,
negativeSeekMonths: 0, negativeSeekMonths: 0,
items: null, items: null,
activeFilterKey: '',
activeFilterLabel: 'Standard',
filterCaches: [],
lruEntries: [],
events: [], events: [],
}, };
this.state = {
open: false,
position: null,
tab: 'grid', // 'grid' | 'lru' | 'log'
inspectFilterKey: null, // null means follow activeFilterKey
selectedChunk: null,
pulseCounter: 0,
stats: initialStats,
}; };
this.panelRef = createRef(); this.panelRef = createRef();
@@ -105,6 +117,8 @@ class ChunkCacheMonitor extends PureComponent {
this.handleLoadChunk = this.handleLoadChunk.bind(this); this.handleLoadChunk = this.handleLoadChunk.bind(this);
this.handleEvictChunk = this.handleEvictChunk.bind(this); this.handleEvictChunk = this.handleEvictChunk.bind(this);
this.handleClearCache = this.handleClearCache.bind(this); this.handleClearCache = this.handleClearCache.bind(this);
this.handleClearFilter = this.handleClearFilter.bind(this);
this.handleApplyFilter = this.handleApplyFilter.bind(this);
this.handlePrefetchAll = this.handlePrefetchAll.bind(this); this.handlePrefetchAll = this.handlePrefetchAll.bind(this);
this.handleReload = this.handleReload.bind(this); this.handleReload = this.handleReload.bind(this);
} }
@@ -152,7 +166,7 @@ class ChunkCacheMonitor extends PureComponent {
} }
handlePointerDown(event) { handlePointerDown(event) {
if (event.target.closest('button') || event.target.closest('.MuiTab-root')) return; if (event.target.closest('button') || event.target.closest('.MuiTab-root') || event.target.closest('.MuiChip-root')) return;
const rect = this.panelRef.current?.getBoundingClientRect(); const rect = this.panelRef.current?.getBoundingClientRect();
if (!rect) return; if (!rect) return;
event.preventDefault(); event.preventDefault();
@@ -188,14 +202,16 @@ class ChunkCacheMonitor extends PureComponent {
})); }));
} }
handleLoadChunk(chunkIndex, e) { handleLoadChunk(chunkIndex, filterKey, e) {
e?.stopPropagation(); e?.stopPropagation();
void orderAutomat.actions.requireChunk(chunkIndex, chunkIndex, { immediate: true }); const targetFilter = filterKey || this.getInspectedFilterKey();
void orderAutomat.actions.loadChunk(chunkIndex, orderAutomat.state.queryEpoch, targetFilter);
} }
handleEvictChunk(chunkIndex, e) { handleEvictChunk(chunkIndex, filterKey, e) {
e?.stopPropagation(); e?.stopPropagation();
orderAutomat.evictChunk?.(chunkIndex); const targetFilter = filterKey || this.getInspectedFilterKey();
orderAutomat.evictChunk?.(chunkIndex, targetFilter);
if (this.state.selectedChunk === chunkIndex) { if (this.state.selectedChunk === chunkIndex) {
this.setState({ selectedChunk: null }); this.setState({ selectedChunk: null });
} }
@@ -206,34 +222,145 @@ class ChunkCacheMonitor extends PureComponent {
this.setState({ selectedChunk: null }); this.setState({ selectedChunk: null });
} }
handlePrefetchAll() { handleClearFilter(filterKey, e) {
orderAutomat.prefetchAllChunks?.(); e?.stopPropagation();
orderAutomat.clearFilterCache?.(filterKey);
if (this.state.inspectFilterKey === filterKey) {
this.setState({ inspectFilterKey: null, selectedChunk: null });
}
}
handleApplyFilter(filterKey) {
const entry = this.state.stats.filterCaches?.find((f) => f.key === filterKey);
if (!entry) return;
const p = entry.params || {};
orderAutomat.actions.resetFilters();
if (p.filter) orderAutomat.actions.filter(p.filter);
if (p.onlyUnpaid) orderAutomat.actions.setOnlyUnpaid(true);
if (p.onlyUndelivered) orderAutomat.actions.setOnlyUndelivered(true);
if (p.negativeSeekMonths) orderAutomat.actions.addNegativeSeek(p.negativeSeekMonths);
this.setState({ inspectFilterKey: null, selectedChunk: null });
}
handlePrefetchAll(filterKey) {
const targetFilter = filterKey || this.getInspectedFilterKey();
orderAutomat.prefetchAllChunks?.(targetFilter);
} }
handleReload() { handleReload() {
void orderAutomat.actions.reload(); void orderAutomat.actions.reload(false);
this.setState({ selectedChunk: null }); this.setState({ selectedChunk: null });
} }
getInspectedFilterKey() {
return this.state.inspectFilterKey || this.state.stats.activeFilterKey;
}
getInspectedFilterEntry() {
const key = this.getInspectedFilterKey();
const entry = this.state.stats.filterCaches?.find((f) => f.key === key);
if (entry) return entry;
return {
key,
label: this.state.stats.activeFilterLabel || 'Aktiver Filter',
total: this.state.stats.total,
loadedChunksCount: this.state.stats.loadedChunks.length,
loadedChunks: this.state.stats.loadedChunks,
chunkCount: this.state.stats.chunkCount,
loadedItemsCount: this.state.stats.loadedItemsCount,
isActive: true,
items: this.state.stats.items,
status: this.state.stats.status,
};
}
renderFilterSelector() {
const { stats, inspectFilterKey } = this.state;
const filterCaches = stats.filterCaches || [];
const activeKey = stats.activeFilterKey;
const currentInspected = this.getInspectedFilterKey();
return (
<Box
sx={{
px: 1.5,
py: 0.75,
bgcolor: 'background.paper',
borderBottom: '1px solid',
borderColor: 'divider',
display: 'flex',
alignItems: 'center',
gap: 1,
overflowX: 'auto',
'&::-webkit-scrollbar': { height: 4 },
'&::-webkit-scrollbar-thumb': { bgcolor: 'divider', borderRadius: 2 },
}}
>
<Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary', whiteSpace: 'nowrap' }}>
Filter-Caches ({filterCaches.length}):
</Typography>
{filterCaches.map((entry) => {
const isInspected = entry.key === currentInspected;
const isActive = entry.key === activeKey;
return (
<Chip
key={entry.key}
size="small"
variant={isInspected ? 'filled' : 'outlined'}
color={isActive ? 'primary' : isInspected ? 'secondary' : 'default'}
label={`${entry.label} (${entry.loadedChunksCount} Chunks)`}
onClick={() => this.setState({ inspectFilterKey: entry.key, selectedChunk: null })}
onDelete={!isActive ? (e) => this.handleClearFilter(entry.key, e) : undefined}
sx={{
fontWeight: isInspected ? 700 : 500,
fontSize: '0.72rem',
height: 26,
cursor: 'pointer',
whiteSpace: 'nowrap',
flexShrink: 0,
borderWidth: isInspected ? 2 : 1,
}}
/>
);
})}
</Box>
);
}
renderChunkGrid() { renderChunkGrid() {
const { stats, selectedChunk } = this.state; const { stats, selectedChunk } = this.state;
const { total, chunkCount, loadedChunks, inflightChunks, pendingChunks, items } = stats; const currentFilter = this.getInspectedFilterEntry();
const loadedSet = new Set(loadedChunks); const isActiveFilter = currentFilter.key === stats.activeFilterKey;
const inflightSet = new Set(inflightChunks);
const pendingSet = new Set(pendingChunks); const { total, chunkCount, loadedChunks, items } = currentFilter;
const loadedSet = new Set(loadedChunks || []);
const inflightSet = new Set(isActiveFilter ? stats.inflightChunks : []);
const pendingSet = new Set(isActiveFilter ? stats.pendingChunks : []);
// LRU rank lookup Map: lruKey -> rank (1..50)
const lruRankMap = new Map();
if (Array.isArray(stats.lruEntries)) {
for (const entry of stats.lruEntries) {
if (entry.filterKey === currentFilter.key) {
lruRankMap.set(entry.chunkIndex, entry.lruRank);
}
}
}
// If total is 0 and no chunks loaded, show uninitialized state
if (chunkCount === 0 && (!items || items.length === 0)) { if (chunkCount === 0 && (!items || items.length === 0)) {
return ( return (
<Box sx={{ p: 3, textAlign: 'center' }}> <Box sx={{ p: 3, textAlign: 'center' }}>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}> <Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
Automat ist noch nicht initialisiert (keine Daten geladen). Keine Daten für diesen Filter geladen ({currentFilter.label}).
</Typography> </Typography>
<Button <Button
size="small" size="small"
variant="contained" variant="contained"
startIcon={<CloudDownloadIcon />} startIcon={<CloudDownloadIcon />}
onClick={() => this.handleLoadChunk(0)} onClick={() => this.handleLoadChunk(0, currentFilter.key)}
> >
Ersten Chunk (#0) laden Ersten Chunk (#0) laden
</Button> </Button>
@@ -249,11 +376,11 @@ class ChunkCacheMonitor extends PureComponent {
const isInflight = inflightSet.has(c); const isInflight = inflightSet.has(c);
const isPending = pendingSet.has(c); const isPending = pendingSet.has(c);
const isSelected = selectedChunk === c; const isSelected = selectedChunk === c;
const lruRank = lruRankMap.get(c);
const offsetStart = c * CHUNK_SIZE; const offsetStart = c * CHUNK_SIZE;
const offsetEnd = Math.min((c + 1) * CHUNK_SIZE - 1, Math.max(0, total - 1)); const offsetEnd = Math.min((c + 1) * CHUNK_SIZE - 1, Math.max(0, total - 1));
// Calculate loaded items inside this chunk
let itemsInChunk = 0; let itemsInChunk = 0;
if (Array.isArray(items)) { if (Array.isArray(items)) {
for (let i = offsetStart; i <= offsetEnd; i++) { for (let i = offsetStart; i <= offsetEnd; i++) {
@@ -266,20 +393,16 @@ class ChunkCacheMonitor extends PureComponent {
let borderStyle = '1px solid'; let borderStyle = '1px solid';
let borderColor = 'divider'; let borderColor = 'divider';
let bgColor = 'background.paper'; let bgColor = 'background.paper';
let statusLabel = 'Nicht geladen';
if (isLoaded) { if (isLoaded) {
statusLabel = `Geladen (${itemsInChunk}/${expectedInChunk})`;
statusColor = 'success.main'; statusColor = 'success.main';
borderColor = 'success.main'; borderColor = 'success.main';
bgColor = 'rgba(46, 125, 50, 0.08)'; bgColor = 'rgba(46, 125, 50, 0.08)';
} else if (isInflight) { } else if (isInflight) {
statusLabel = 'Lädt über Netzwerk...';
statusColor = 'info.main'; statusColor = 'info.main';
borderColor = 'info.main'; borderColor = 'info.main';
bgColor = 'rgba(2, 136, 209, 0.08)'; bgColor = 'rgba(2, 136, 209, 0.08)';
} else if (isPending) { } else if (isPending) {
statusLabel = 'Vorgemerkt (Debounce)';
statusColor = 'warning.main'; statusColor = 'warning.main';
borderStyle = '1px dashed'; borderStyle = '1px dashed';
borderColor = 'warning.main'; borderColor = 'warning.main';
@@ -289,7 +412,7 @@ class ChunkCacheMonitor extends PureComponent {
blocks.push( blocks.push(
<Box <Box
key={c} key={c}
onClick={() => (isLoaded ? this.handleSelectChunk(c) : this.handleLoadChunk(c))} onClick={() => (isLoaded ? this.handleSelectChunk(c) : this.handleLoadChunk(c, currentFilter.key))}
sx={{ sx={{
position: 'relative', position: 'relative',
p: 1, p: 1,
@@ -309,7 +432,7 @@ class ChunkCacheMonitor extends PureComponent {
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
justifyContent: 'space-between', justifyContent: 'space-between',
minHeight: 74, minHeight: 82,
}} }}
> >
{/* Top Row: Chunk Number & Status Indicator */} {/* Top Row: Chunk Number & Status Indicator */}
@@ -318,9 +441,27 @@ class ChunkCacheMonitor extends PureComponent {
#{c} #{c}
</Typography> </Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
{isLoaded && lruRank != null && (
<Tooltip title={lruRank === 1 ? 'Ältester Chunk im RAM: Wird bei Überschreiten von 50 Chunks als nächstes verworfen!' : `LRU-Position #${lruRank} von ${stats.lruChunksCount}`}>
<Chip
size="small"
label={`LRU #${lruRank}`}
color={lruRank === 1 ? 'warning' : 'default'}
sx={{
height: 18,
fontSize: '0.62rem',
fontWeight: 700,
px: 0.25,
'& .MuiChip-label': { px: 0.5 },
}}
/>
</Tooltip>
)}
{isLoaded ? ( {isLoaded ? (
<Tooltip title="Im Cache"> <Tooltip title="Im RAM">
<CheckCircleOutlinedIcon fontSize="small" color="success" sx={{ fontSize: 18 }} /> <CheckCircleOutlinedIcon fontSize="small" color="success" sx={{ fontSize: 16 }} />
</Tooltip> </Tooltip>
) : isInflight ? ( ) : isInflight ? (
<Tooltip title="Netzwerk-Request läuft"> <Tooltip title="Netzwerk-Request läuft">
@@ -336,9 +477,10 @@ class ChunkCacheMonitor extends PureComponent {
</Tooltip> </Tooltip>
)} )}
</Box> </Box>
</Box>
{/* Middle: Item range index */} {/* Middle: Item range index */}
<Typography variant="caption" color="text.secondary" sx={{ fontVariantNumeric: 'tabular-nums' }}> <Typography variant="caption" color="text.secondary" sx={{ fontVariantNumeric: 'tabular-nums', fontSize: '0.72rem' }}>
{offsetStart}–{offsetEnd} {offsetStart}–{offsetEnd}
</Typography> </Typography>
@@ -350,18 +492,18 @@ class ChunkCacheMonitor extends PureComponent {
fontWeight: 600, fontWeight: 600,
color: statusColor, color: statusColor,
fontVariantNumeric: 'tabular-nums', fontVariantNumeric: 'tabular-nums',
fontSize: '0.7rem', fontSize: '0.68rem',
}} }}
> >
{isLoaded ? `${itemsInChunk} Aufträge` : isInflight ? 'Laden…' : isPending ? 'Wartet…' : 'Klick: Laden'} {isLoaded ? `${itemsInChunk}/${expectedInChunk}` : isInflight ? 'Laden…' : isPending ? 'Wartet…' : 'Klick: Laden'}
</Typography> </Typography>
{isLoaded && ( {isLoaded && (
<Tooltip title="Diesen Chunk aus Cache verwerfen (Evict)"> <Tooltip title="Chunk aus RAM verwerfen (Evict)">
<IconButton <IconButton
size="small" size="small"
aria-label={`Chunk ${c} verwerfen`} aria-label={`Chunk ${c} verwerfen`}
onClick={(e) => this.handleEvictChunk(c, e)} onClick={(e) => this.handleEvictChunk(c, currentFilter.key, e)}
sx={{ p: 0.25, ml: 0.5 }} sx={{ p: 0.25, ml: 0.5 }}
> >
<DeleteOutlinedIcon sx={{ fontSize: 14 }} color="action" /> <DeleteOutlinedIcon sx={{ fontSize: 14 }} color="action" />
@@ -374,11 +516,53 @@ class ChunkCacheMonitor extends PureComponent {
} }
return ( return (
<Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
{/* Inactive filter inspector banner */}
{!isActiveFilter && (
<Box
sx={{
px: 1.5,
py: 0.6,
bgcolor: 'action.selected',
borderBottom: '1px solid',
borderColor: 'divider',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Typography variant="caption" sx={{ fontWeight: 600, color: 'text.secondary' }}>
Inspektion: {currentFilter.label}
</Typography>
<Stack direction="row" spacing={1}>
<Button
size="small"
variant="outlined"
color="primary"
startIcon={<PlayArrowIcon sx={{ fontSize: 14 }} />}
onClick={() => this.handleApplyFilter(currentFilter.key)}
sx={{ py: 0.1, px: 1, fontSize: '0.72rem', textTransform: 'none', height: 24 }}
>
In UI anwenden
</Button>
<Button
size="small"
variant="text"
color="inherit"
onClick={() => this.setState({ inspectFilterKey: null, selectedChunk: null })}
sx={{ py: 0.1, px: 1, fontSize: '0.72rem', textTransform: 'none', height: 24 }}
>
Zum aktiven Filter
</Button>
</Stack>
</Box>
)}
<Box <Box
sx={{ sx={{
p: 1.5, p: 1.5,
display: 'grid', display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(105px, 1fr))', gridTemplateColumns: 'repeat(auto-fill, minmax(115px, 1fr))',
gap: 1.25, gap: 1.25,
overflowY: 'auto', overflowY: 'auto',
flex: 1, flex: 1,
@@ -386,14 +570,16 @@ class ChunkCacheMonitor extends PureComponent {
> >
{blocks} {blocks}
</Box> </Box>
</Box>
); );
} }
renderChunkDetail() { renderChunkDetail() {
const { stats, selectedChunk } = this.state; const { selectedChunk } = this.state;
if (selectedChunk === null) return null; if (selectedChunk === null) return null;
const { items, total } = stats; const currentFilter = this.getInspectedFilterEntry();
const { items, total } = currentFilter;
const offsetStart = selectedChunk * CHUNK_SIZE; const offsetStart = selectedChunk * CHUNK_SIZE;
const offsetEnd = Math.min((selectedChunk + 1) * CHUNK_SIZE - 1, Math.max(0, total - 1)); const offsetEnd = Math.min((selectedChunk + 1) * CHUNK_SIZE - 1, Math.max(0, total - 1));
@@ -432,11 +618,11 @@ class ChunkCacheMonitor extends PureComponent {
<ArrowBackIcon fontSize="small" /> <ArrowBackIcon fontSize="small" />
</IconButton> </IconButton>
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}> <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
Chunk #{selectedChunk} Inspection Chunk #{selectedChunk} Detail
</Typography> </Typography>
<Chip <Chip
size="small" size="small"
label={`${chunkOrders.length} Einträge (Index ${offsetStart}–${offsetEnd})`} label={`${chunkOrders.length} geladene Aufträge (Index ${offsetStart}–${offsetEnd})`}
color="primary" color="primary"
variant="outlined" variant="outlined"
/> />
@@ -447,16 +633,16 @@ class ChunkCacheMonitor extends PureComponent {
size="small" size="small"
color="warning" color="warning"
variant="outlined" variant="outlined"
onClick={() => this.handleEvictChunk(selectedChunk)} onClick={() => this.handleEvictChunk(selectedChunk, currentFilter.key)}
sx={{ textTransform: 'none', py: 0.25, fontSize: '0.75rem' }} sx={{ textTransform: 'none', py: 0.25, fontSize: '0.75rem' }}
> >
Evict (Aus Cache) Aus Cache verwerfen
</Button> </Button>
<Button <Button
size="small" size="small"
color="primary" color="primary"
variant="contained" variant="contained"
onClick={() => this.handleLoadChunk(selectedChunk)} onClick={() => this.handleLoadChunk(selectedChunk, currentFilter.key)}
sx={{ textTransform: 'none', py: 0.25, fontSize: '0.75rem' }} sx={{ textTransform: 'none', py: 0.25, fontSize: '0.75rem' }}
> >
Neu laden Neu laden
@@ -534,6 +720,97 @@ class ChunkCacheMonitor extends PureComponent {
); );
} }
renderLruQueue() {
const { stats } = this.state;
const lruEntries = stats.lruEntries || [];
if (lruEntries.length === 0) {
return (
<Box sx={{ p: 3, textAlign: 'center' }}>
<Typography variant="body2" color="text.secondary">
Der globale LRU-Cache ist aktuell leer (keine Chunks im RAM).
</Typography>
</Box>
);
}
return (
<Box sx={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
<Box sx={{ px: 2, py: 1, bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' }}>
<Typography variant="caption" color="text.secondary">
Geordnet nach Alter (LRU). Position #1 ist der älteste Chunk und wird als nächstes automatisch verworfen, sobald das Gesamtlimit von {stats.maxLruChunks || 50} Chunks überschritten wird.
</Typography>
</Box>
<Box sx={{ flex: 1, overflowY: 'auto', p: 1.5 }}>
<Stack spacing={1}>
{lruEntries.map((entry) => {
const isOldest = entry.lruRank === 1;
const isNewest = entry.lruRank === lruEntries.length;
const offsetStart = entry.chunkIndex * CHUNK_SIZE;
const offsetEnd = (entry.chunkIndex + 1) * CHUNK_SIZE - 1;
return (
<Paper
key={entry.lruKey}
variant="outlined"
sx={{
p: 1.25,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 1.5,
borderColor: isOldest ? 'warning.main' : isNewest ? 'primary.main' : 'divider',
bgcolor: isOldest ? 'rgba(237, 108, 2, 0.04)' : 'background.paper',
}}
>
<Stack direction="row" spacing={1.5} alignItems="center" sx={{ minWidth: 0, flex: 1 }}>
<Chip
size="small"
label={`#${entry.lruRank}`}
color={isOldest ? 'warning' : isNewest ? 'primary' : 'default'}
sx={{ fontWeight: 700, width: 44 }}
/>
{isOldest && (
<Tooltip title="Wird bei neuem Chunk als nächstes verworfen">
<WarningAmberIcon fontSize="small" color="warning" />
</Tooltip>
)}
<Box sx={{ minWidth: 0, flex: 1 }}>
<Typography variant="body2" sx={{ fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{entry.filterLabel}
</Typography>
<Typography variant="caption" color="text.secondary">
Chunk #{entry.chunkIndex} (Index {offsetStart}..{offsetEnd}) · {entry.orderCount} Aufträge geladen
</Typography>
</Box>
</Stack>
<Stack direction="row" spacing={1} alignItems="center">
<Typography variant="caption" color="text.secondary" sx={{ fontVariantNumeric: 'tabular-nums' }}>
{new Date(entry.accessedAt).toLocaleTimeString()}
</Typography>
<Tooltip title="Diesen Chunk manuell aus dem Cache entfernen">
<IconButton
size="small"
color="warning"
onClick={(e) => this.handleEvictChunk(entry.chunkIndex, entry.filterKey, e)}
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
</Paper>
);
})}
</Stack>
</Box>
</Box>
);
}
renderEventLog() { renderEventLog() {
const { stats } = this.state; const { stats } = this.state;
const events = stats.events || []; const events = stats.events || [];
@@ -555,9 +832,10 @@ class ChunkCacheMonitor extends PureComponent {
const timeStr = new Date(entry.time).toLocaleTimeString(); const timeStr = new Date(entry.time).toLocaleTimeString();
let chipColor = 'default'; let chipColor = 'default';
if (entry.type === 'loaded' || entry.type === 'hit') chipColor = 'success'; if (entry.type === 'loaded' || entry.type === 'hit') chipColor = 'success';
if (entry.type === 'start' || entry.type === 'prefetch') chipColor = 'info'; if (entry.type === 'filter_hit') chipColor = 'secondary';
if (entry.type === 'filter_miss' || entry.type === 'start') chipColor = 'info';
if (entry.type === 'pending' || entry.type === 'debounce_fire') chipColor = 'warning'; if (entry.type === 'pending' || entry.type === 'debounce_fire') chipColor = 'warning';
if (entry.type === 'error') chipColor = 'error'; if (entry.type === 'lru_evict' || entry.type === 'evict' || entry.type === 'error') chipColor = 'error';
return ( return (
<Box <Box
@@ -596,22 +874,23 @@ class ChunkCacheMonitor extends PureComponent {
render() { render() {
const { open, position, tab, stats, pulseCounter } = this.state; const { open, position, tab, stats, pulseCounter } = this.state;
const { total, chunkCount, loadedChunks, inflightChunks, pendingChunks, loadedItemsCount, status } = stats; const { lruChunksCount, maxLruChunks, inflightChunks } = stats;
const loadedCount = loadedChunks.length; const maxLru = maxLruChunks || MAX_LRU_CHUNKS;
const expectedChunks = Math.max(chunkCount, 1); const lruCount = lruChunksCount || 0;
const progressPercent = expectedChunks > 0 ? Math.min(100, Math.round((loadedCount / expectedChunks) * 100)) : 0; const lruPercent = Math.min(100, Math.round((lruCount / maxLru) * 100));
const hasInflight = inflightChunks.length > 0; const hasInflight = inflightChunks.length > 0;
const filterCachesCount = stats.filterCaches?.length || 1;
return ( return (
<> <>
{!open ? ( {!open ? (
<Tooltip title="Chunk-Cache-Monitor (Alt+Shift+C)" placement="right"> <Tooltip title={`Chunk-Cache-Monitor (Alt+Shift+C) — ${lruCount}/${maxLru} Chunks im RAM`} placement="right">
<Badge <Badge
badgeContent={loadedCount} badgeContent={`${lruCount}/${maxLru}`}
color="success" color={lruCount >= maxLru ? 'warning' : 'success'}
overlap="circular" overlap="circular"
max={99} max={999}
sx={{ sx={{
position: 'fixed', position: 'fixed',
left: { xs: 27, sm: 171 }, left: { xs: 27, sm: 171 },
@@ -681,20 +960,26 @@ class ChunkCacheMonitor extends PureComponent {
<Typography variant="subtitle2" sx={{ fontWeight: 700, flexGrow: 1 }}> <Typography variant="subtitle2" sx={{ fontWeight: 700, flexGrow: 1 }}>
Chunk-Cache-Monitor Chunk-Cache-Monitor
</Typography> </Typography>
<Chip size="small" color="primary" variant="outlined" label="orderAutomat" /> <Chip size="small" color="primary" variant="outlined" label="orderAutomat" />
<Chip <Chip
size="small" size="small"
color={hasInflight ? 'info' : 'default'} color={lruCount >= maxLru ? 'warning' : 'success'}
label={`${loadedCount} / ${expectedChunks} Chunks`} label={`LRU: ${lruCount}/${maxLru} Chunks`}
/>
<Chip
size="small"
variant="outlined"
label={`${filterCachesCount} Filter`}
/> />
<Tooltip title="Prefetch All"> <Tooltip title="Prefetch All Chunks">
<IconButton size="small" aria-label="Alle Chunks vorladen" onClick={this.handlePrefetchAll}> <IconButton size="small" aria-label="Alle Chunks vorladen" onClick={() => this.handlePrefetchAll()}>
<PlaylistAddCheckIcon fontSize="small" /> <PlaylistAddCheckIcon fontSize="small" />
</IconButton> </IconButton>
</Tooltip> </Tooltip>
<Tooltip title="Cache leeren"> <Tooltip title="Gesamten Cache leeren">
<IconButton size="small" aria-label="Cache leeren" onClick={this.handleClearCache}> <IconButton size="small" aria-label="Cache leeren" onClick={this.handleClearCache}>
<LayersClearIcon fontSize="small" /> <LayersClearIcon fontSize="small" />
</IconButton> </IconButton>
@@ -717,15 +1002,16 @@ class ChunkCacheMonitor extends PureComponent {
<Box sx={{ px: 2, py: 1, bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' }}> <Box sx={{ px: 2, py: 1, bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.75 }}> <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.75 }}>
<Typography variant="caption" sx={{ fontWeight: 600 }}> <Typography variant="caption" sx={{ fontWeight: 600 }}>
Cache-Füllstand: {progressPercent}% ({loadedCount} von {expectedChunks} Chunks) LRU-Speicher: {lruPercent}% ({lruCount} von {maxLru} Chunks belegt)
</Typography> </Typography>
<Typography variant="caption" color="text.secondary"> <Typography variant="caption" color="text.secondary">
{loadedItemsCount} von {total} Aufträgen im RAM · Chunk-Größe {CHUNK_SIZE} Aktiver Filter: {stats.activeFilterLabel}
</Typography> </Typography>
</Box> </Box>
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
value={progressPercent} value={lruPercent}
color={lruCount >= maxLru ? 'warning' : 'primary'}
sx={{ sx={{
height: 6, height: 6,
borderRadius: 3, borderRadius: 3,
@@ -733,63 +1019,11 @@ class ChunkCacheMonitor extends PureComponent {
'& .MuiLinearProgress-bar': { borderRadius: 3 }, '& .MuiLinearProgress-bar': { borderRadius: 3 },
}} }}
/> />
<Stack direction="row" spacing={1} alignItems="center" sx={{ mt: 1, flexWrap: 'wrap', gap: 0.5 }}>
<Chip size="small" label={`Status: ${status}`} sx={{ height: 20, fontSize: '0.7rem' }} />
{hasInflight && (
<Chip
size="small"
color="info"
icon={<CircularProgress size={12} color="inherit" />}
label={`${inflightChunks.length} lädt`}
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
{pendingChunks.length > 0 && (
<Chip
size="small"
color="warning"
label={`${pendingChunks.length} vorgemerkt`}
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
{stats.filter && (
<Chip
size="small"
variant="outlined"
label={`Filter: "${stats.filter}"`}
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
{stats.onlyUnpaid && (
<Chip
size="small"
color="warning"
variant="outlined"
label="Nur unbezahlt"
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
{stats.onlyUndelivered && (
<Chip
size="small"
color="primary"
variant="outlined"
label="Nur ungeliefert"
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
{stats.negativeSeekMonths !== 0 && (
<Chip
size="small"
variant="outlined"
label={`Seek: ${stats.negativeSeekMonths}M`}
sx={{ height: 20, fontSize: '0.7rem' }}
/>
)}
</Stack>
</Box> </Box>
{/* Filter Caches Switcher Bar */}
{this.renderFilterSelector()}
{/* View Tabs */} {/* View Tabs */}
<Box sx={{ borderBottom: '1px solid', borderColor: 'divider', px: 1 }}> <Box sx={{ borderBottom: '1px solid', borderColor: 'divider', px: 1 }}>
<Tabs <Tabs
@@ -798,6 +1032,12 @@ class ChunkCacheMonitor extends PureComponent {
sx={{ minHeight: 36, '& .MuiTab-root': { minHeight: 36, py: 0.5, fontSize: '0.75rem' } }} sx={{ minHeight: 36, '& .MuiTab-root': { minHeight: 36, py: 0.5, fontSize: '0.75rem' } }}
> >
<Tab icon={<GridViewIcon fontSize="small" />} iconPosition="start" label="Chunk-Map" value="grid" /> <Tab icon={<GridViewIcon fontSize="small" />} iconPosition="start" label="Chunk-Map" value="grid" />
<Tab
icon={<LayersIcon fontSize="small" />}
iconPosition="start"
label={`LRU-Queue (${lruCount}/${maxLru})`}
value="lru"
/>
<Tab <Tab
icon={<HistoryIcon fontSize="small" />} icon={<HistoryIcon fontSize="small" />}
iconPosition="start" iconPosition="start"
@@ -809,8 +1049,10 @@ class ChunkCacheMonitor extends PureComponent {
{/* Body */} {/* Body */}
<Box sx={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}> <Box sx={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{tab === 'grid' ? this.renderChunkGrid() : this.renderEventLog()} {tab === 'grid' && this.renderChunkGrid()}
{tab === 'grid' && this.renderChunkDetail()} {tab === 'grid' && this.renderChunkDetail()}
{tab === 'lru' && this.renderLruQueue()}
{tab === 'log' && this.renderEventLog()}
</Box> </Box>
</Paper> </Paper>
)} )}