refresh stale data (#156)

This commit is contained in:
Doh
2025-05-30 18:04:03 -04:00
committed by GitHub
parent 1967d154ed
commit 276e8a8a7b
12 changed files with 396 additions and 66 deletions

View File

@@ -29,6 +29,9 @@ import { signInSchema } from '@/lib/zod';
import { auth } from '@/auth';
import _ from 'lodash';
import { getCurrentUser, getCurrentUserId } from '@/lib/server-helpers'
import stableStringify from 'json-stable-stringify';
import { prepareDataForHashing, generateCryptoHash } from '@/lib/utils';
import { PermissionError } from '@/lib/exceptions'
@@ -123,6 +126,33 @@ async function saveData<T>(type: DataType, data: T): Promise<void> {
}
}
/**
* Calculates the server's global freshness token based on all core data files.
* This is an expensive operation as it reads all data files.
*/
async function calculateServerFreshnessToken(): Promise<string> {
try {
const settings = await loadSettings();
const habits = await loadHabitsData();
const coins = await loadCoinsData();
const wishlist = await loadWishlistData();
const users = await loadUsersData();
const dataString = prepareDataForHashing(
settings,
habits,
coins,
wishlist,
users
);
const serverToken = await generateCryptoHash(dataString);
return serverToken;
} catch (error) {
console.error("Error calculating server freshness token:", error);
throw error;
}
}
// Wishlist specific functions
export async function loadWishlistData(): Promise<WishlistData> {
const user = await getCurrentUser()
@@ -595,3 +625,24 @@ export async function loadServerSettings(): Promise<ServerSettings> {
isDemo: !!process.env.DEMO,
}
}
/**
* Checks if the client's data is fresh by comparing its token with the server's token.
* @param clientToken The freshness token calculated by the client.
* @returns A promise that resolves to an object { isFresh: boolean }.
*/
export async function checkDataFreshness(clientToken: string): Promise<{ isFresh: boolean }> {
try {
const serverToken = await calculateServerFreshnessToken();
const isFresh = clientToken === serverToken;
if (!isFresh) {
console.log(`Data freshness check: Stale. Client token: ${clientToken}, Server token: ${serverToken}`);
}
return { isFresh };
} catch (error) {
console.error("Error in checkDataFreshness:", error);
// If server fails to determine its token, assume client might be stale to be safe,
// or handle error reporting differently.
return { isFresh: false };
}
}