feat(statistics): persist ranges and align history columns
Persist per-day download volume, outcomes, active transfer time, and provider results so today, seven-day, and 30-day views use real partial-window data. Preserve existing all-time counters while extending totals with newly recorded result metrics. Rebuild the history table around one resizable persisted grid shared by headers and rows, with synchronized overflow and consistent alignment across window sizes.
This commit is contained in:
@@ -17,8 +17,9 @@ import {
|
||||
PackageEntry,
|
||||
PackagePriority,
|
||||
ParsedPackageInput,
|
||||
SessionState,
|
||||
StartConflictEntry,
|
||||
SessionState,
|
||||
StatisticsLedger,
|
||||
StartConflictEntry,
|
||||
StartConflictResolutionResult,
|
||||
UiSnapshot, DebridAccountStatus } from "../shared/types";
|
||||
import { parseDebridLinkApiKeys } from "../shared/debrid-link-keys";
|
||||
@@ -73,6 +74,16 @@ import { compactErrorText, ensureDirPath, filenameFromUrl, formatEta, humanSize,
|
||||
import { mergeKnownTotalBytes } from "./download-size";
|
||||
import { DiskCapacityError, DiskReservationCoordinator, type DiskReservationLease } from "./disk-space";
|
||||
import { createRendererState } from "./renderer-state";
|
||||
import {
|
||||
addStatisticsActiveIntervalInPlace,
|
||||
addStatisticsBytesInPlace,
|
||||
addStatisticsOutcomeInPlace,
|
||||
createStatisticsLedger,
|
||||
loadStatisticsLedger,
|
||||
normalizeStatisticsLedger,
|
||||
saveStatisticsLedger,
|
||||
seedStatisticsDayProviderBytes
|
||||
} from "./statistics-ledger";
|
||||
|
||||
type ActiveTask = {
|
||||
itemId: string;
|
||||
@@ -1769,7 +1780,19 @@ export class DownloadManager extends EventEmitter {
|
||||
|
||||
private statsCache: DownloadStats | null = null;
|
||||
|
||||
private statsCacheAt = 0;
|
||||
private statsCacheAt = 0;
|
||||
|
||||
private statisticsLedger: StatisticsLedger;
|
||||
|
||||
private statisticsDirty = false;
|
||||
|
||||
private statisticsUrgent = false;
|
||||
|
||||
private lastStatisticsPersistAt = 0;
|
||||
|
||||
private statisticsActivityAt = 0;
|
||||
|
||||
private statisticsActivityWasActive = false;
|
||||
|
||||
private settingsSnapshotCache: ReturnType<typeof createRendererState> | null = null;
|
||||
private settingsSnapshotCacheAt = 0;
|
||||
@@ -1898,7 +1921,12 @@ export class DownloadManager extends EventEmitter {
|
||||
this.runtimePersistedAt = startedAt;
|
||||
this.session = session;
|
||||
this.itemCount = Object.keys(this.session.items).length;
|
||||
this.storagePaths = storagePaths;
|
||||
this.storagePaths = storagePaths;
|
||||
this.statisticsLedger = seedStatisticsDayProviderBytes(
|
||||
loadStatisticsLedger(storagePaths.statisticsFile, startedAt),
|
||||
settings.providerDailyUsageBytes,
|
||||
startedAt
|
||||
);
|
||||
this.protectAgainstEmptyClobber = Boolean(options.protectEmptyClobber);
|
||||
if (this.protectAgainstEmptyClobber) {
|
||||
logger.warn("Session-Schutz aktiv: Start mit unlesbarer Session — leere Speicherungen blockiert, bis echte Daten vorliegen");
|
||||
@@ -2544,8 +2572,9 @@ export class DownloadManager extends EventEmitter {
|
||||
sessionStartedAt: this.session.runStartedAt,
|
||||
appSessionStartedAt: this.appSessionStartedAt,
|
||||
sessionRuntimeMs: this.getAppSessionRuntimeMs(now),
|
||||
totalRuntimeMs: this.getLiveTotalRuntimeMs(now),
|
||||
runtimeMeasuredAt: now
|
||||
totalRuntimeMs: this.getLiveTotalRuntimeMs(now),
|
||||
runtimeMeasuredAt: now,
|
||||
statistics: normalizeStatisticsLedger(this.statisticsLedger, now)
|
||||
};
|
||||
this.statsCache = stats;
|
||||
this.statsCacheAt = now;
|
||||
@@ -2744,11 +2773,15 @@ export class DownloadManager extends EventEmitter {
|
||||
this.emitState(true);
|
||||
}
|
||||
|
||||
public resetDownloadStats(): void {
|
||||
public resetDownloadStats(): void {
|
||||
this.settings.totalDownloadedAllTime = 0;
|
||||
this.settings.totalCompletedFilesAllTime = 0;
|
||||
this.settings.providerTotalUsageBytes = {};
|
||||
this.settings.debridLinkApiKeyTotalUsageBytes = {};
|
||||
this.settings.debridLinkApiKeyTotalUsageBytes = {};
|
||||
this.statisticsLedger = createStatisticsLedger();
|
||||
this.statisticsDirty = false;
|
||||
this.statisticsUrgent = false;
|
||||
saveStatisticsLedger(this.storagePaths.statisticsFile, this.statisticsLedger);
|
||||
this.lastSettingsPersistAt = nowMs();
|
||||
saveSettings(this.storagePaths, this.settings);
|
||||
this.invalidateStatsCache();
|
||||
@@ -5992,8 +6025,9 @@ export class DownloadManager extends EventEmitter {
|
||||
this.emitState(true);
|
||||
}
|
||||
|
||||
public prepareForShutdown(): void {
|
||||
logger.info(`Shutdown-Vorbereitung gestartet: active=${this.activeTasks.size}, running=${this.session.running}, paused=${this.session.paused}`);
|
||||
public prepareForShutdown(): void {
|
||||
logger.info(`Shutdown-Vorbereitung gestartet: active=${this.activeTasks.size}, running=${this.session.running}, paused=${this.session.paused}`);
|
||||
this.updateStatisticsActivity(nowMs());
|
||||
this.rotationListenerActive = false;
|
||||
this.clearPersistTimer();
|
||||
if (this.stateEmitTimer) {
|
||||
@@ -6070,7 +6104,8 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!this.guardBlocksSessionSave()) {
|
||||
saveSession(this.storagePaths, this.session);
|
||||
}
|
||||
saveSettings(this.storagePaths, this.settings);
|
||||
saveSettings(this.storagePaths, this.settings);
|
||||
saveStatisticsLedger(this.storagePaths.statisticsFile, this.statisticsLedger);
|
||||
} else {
|
||||
logger.info(`Shutdown-Save übersprungen: skipShutdownPersist=${this.skipShutdownPersist}, blockAllPersistence=${this.blockAllPersistence}`);
|
||||
}
|
||||
@@ -6398,11 +6433,22 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!this.guardBlocksSessionSave()) {
|
||||
void saveSessionAsync(this.storagePaths, this.session).catch((err) => logger.warn(`saveSessionAsync Fehler: ${compactErrorText(err)}`));
|
||||
}
|
||||
if (now - this.lastSettingsPersistAt >= 30000) {
|
||||
if (now - this.lastSettingsPersistAt >= 30000) {
|
||||
this.foldRuntimeIntoSettings(now);
|
||||
this.lastSettingsPersistAt = now;
|
||||
void saveSettingsAsync(this.storagePaths, this.settings).catch((err) => logger.warn(`saveSettingsAsync Fehler: ${compactErrorText(err as Error)}`));
|
||||
}
|
||||
void saveSettingsAsync(this.storagePaths, this.settings).catch((err) => logger.warn(`saveSettingsAsync Fehler: ${compactErrorText(err as Error)}`));
|
||||
}
|
||||
if (this.statisticsDirty && (this.statisticsUrgent || now - this.lastStatisticsPersistAt >= 10000)) {
|
||||
this.lastStatisticsPersistAt = now;
|
||||
this.statisticsDirty = false;
|
||||
this.statisticsUrgent = false;
|
||||
try {
|
||||
saveStatisticsLedger(this.storagePaths.statisticsFile, this.statisticsLedger);
|
||||
} catch (error) {
|
||||
this.statisticsDirty = true;
|
||||
logger.warn(`Statistik konnte nicht gespeichert werden: ${compactErrorText(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public persistNowSync(): void {
|
||||
@@ -6414,7 +6460,8 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!this.guardBlocksSessionSave()) {
|
||||
saveSession(this.storagePaths, this.session);
|
||||
}
|
||||
saveSettings(this.storagePaths, this.settings);
|
||||
saveSettings(this.storagePaths, this.settings);
|
||||
saveStatisticsLedger(this.storagePaths.statisticsFile, this.statisticsLedger);
|
||||
}
|
||||
|
||||
private emitState(force = false): void {
|
||||
@@ -6507,8 +6554,15 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!this.runItemIds.has(itemId)) {
|
||||
return;
|
||||
}
|
||||
const previous = this.runOutcomes.get(itemId);
|
||||
this.runOutcomes.set(itemId, status);
|
||||
const previous = this.runOutcomes.get(itemId);
|
||||
this.runOutcomes.set(itemId, status);
|
||||
const item = this.session.items[itemId];
|
||||
const provider = item?.provider ? resolveMegaDebridProvider(this.settings, item.provider) : null;
|
||||
if ((status === "completed" || status === "failed") && previous !== status) {
|
||||
addStatisticsOutcomeInPlace(this.statisticsLedger, provider, status);
|
||||
this.statisticsDirty = true;
|
||||
this.statisticsUrgent = true;
|
||||
}
|
||||
if (status === "completed" && previous !== "completed") {
|
||||
this.sessionCompletedFiles += 1;
|
||||
this.settings.totalCompletedFilesAllTime = Math.max(0, Number(this.settings.totalCompletedFilesAllTime || 0)) + 1;
|
||||
@@ -8105,7 +8159,9 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!provider) {
|
||||
return;
|
||||
}
|
||||
const effectiveProvider = resolveMegaDebridProvider(this.settings, provider) || provider;
|
||||
const effectiveProvider = resolveMegaDebridProvider(this.settings, provider) || provider;
|
||||
addStatisticsBytesInPlace(this.statisticsLedger, effectiveProvider, byteDelta);
|
||||
this.statisticsDirty = true;
|
||||
const nextUsage = addProviderDailyUsageBytes(this.settings, effectiveProvider, byteDelta);
|
||||
const nextTotalUsage = addProviderTotalUsageBytes(this.settings, effectiveProvider, byteDelta);
|
||||
this.settings.providerDailyUsageDay = nextUsage.providerDailyUsageDay;
|
||||
@@ -8169,6 +8225,17 @@ export class DownloadManager extends EventEmitter {
|
||||
return false;
|
||||
}
|
||||
|
||||
private updateStatisticsActivity(now: number): void {
|
||||
if (this.statisticsActivityAt > 0 && this.statisticsActivityWasActive && now > this.statisticsActivityAt) {
|
||||
addStatisticsActiveIntervalInPlace(this.statisticsLedger, this.statisticsActivityAt, now);
|
||||
this.statisticsDirty = true;
|
||||
}
|
||||
this.statisticsActivityAt = now;
|
||||
this.statisticsActivityWasActive = this.session.running
|
||||
&& !this.session.paused
|
||||
&& [...this.activeTasks.values()].some((task) => this.session.items[task.itemId]?.status === "downloading");
|
||||
}
|
||||
|
||||
private hasUsableDownloadAccount(): boolean {
|
||||
return DOWNLOAD_ACCOUNT_PROVIDERS.some((provider) => this.isProviderConfigured(provider));
|
||||
}
|
||||
@@ -8590,8 +8657,9 @@ export class DownloadManager extends EventEmitter {
|
||||
const myGeneration = this.schedulerGeneration;
|
||||
logger.info(`Scheduler gestartet (gen=${myGeneration})`);
|
||||
try {
|
||||
while (this.session.running && this.schedulerGeneration === myGeneration) {
|
||||
const now = nowMs();
|
||||
while (this.session.running && this.schedulerGeneration === myGeneration) {
|
||||
const now = nowMs();
|
||||
this.updateStatisticsActivity(now);
|
||||
if (now - this.lastSchedulerHeartbeatAt >= 60000) {
|
||||
this.lastSchedulerHeartbeatAt = now;
|
||||
logger.info(`Scheduler Heartbeat: active=${this.activeTasks.size}, queued=${this.countQueuedItems()}, reconnect=${this.reconnectActive()}, paused=${this.session.paused}, postProcess=${this.packagePostProcessTasks.size}`);
|
||||
@@ -8624,10 +8692,12 @@ export class DownloadManager extends EventEmitter {
|
||||
if (!next) {
|
||||
break;
|
||||
}
|
||||
this.startItem(next.packageId, next.itemId);
|
||||
}
|
||||
|
||||
this.runGlobalStallWatchdog(now);
|
||||
this.startItem(next.packageId, next.itemId);
|
||||
}
|
||||
|
||||
this.updateStatisticsActivity(nowMs());
|
||||
|
||||
this.runGlobalStallWatchdog(now);
|
||||
|
||||
const queuePresence = this.activeTasks.size === 0 ? this.getQueuePresence(now) : { hasImmediate: true, hasDelayed: false };
|
||||
const downloadsComplete = this.activeTasks.size === 0 && !queuePresence.hasImmediate && !queuePresence.hasDelayed;
|
||||
@@ -8640,9 +8710,10 @@ export class DownloadManager extends EventEmitter {
|
||||
const maxParallel = Math.max(1, this.settings.maxParallel);
|
||||
const schedulerSleepMs = this.activeTasks.size >= maxParallel ? 170 : 120;
|
||||
await sleep(schedulerSleepMs);
|
||||
}
|
||||
} finally {
|
||||
this.scheduleRunning = false;
|
||||
}
|
||||
} finally {
|
||||
this.updateStatisticsActivity(nowMs());
|
||||
this.scheduleRunning = false;
|
||||
logger.info(`Scheduler beendet (gen=${myGeneration})`);
|
||||
// Stop->Start race: a new run can begin while this loop sleeps (start()'s
|
||||
// ensureScheduler early-returns on scheduleRunning, then this loop exits on
|
||||
|
||||
Reference in New Issue
Block a user