Skip to content

Commit 81b8d00

Browse files
committed
Refactor backend caching and logging mechanisms; implement browser caching
- Removed redundant server state tracking and response caching logic in favor of a simpler in-flight request handling. - Enhanced logging to provide clearer user context without trace IDs. - Introduced a new browser cache utility for improved performance and reduced backend calls. - Cleaned up unused code and consolidated logging for user actions across various routes. - Removed the backend wakeup hook from the frontend as it was deemed unnecessary.
1 parent 817d98f commit 81b8d00

File tree

13 files changed

+250
-397
lines changed

13 files changed

+250
-397
lines changed

backend/src/hevyApi.ts

Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import type {
55
} from './types';
66
import { clearTokenCache, getRecaptchaToken } from './hevyRecaptcha';
77

8+
const formatDuration = (ms: number): string => `${(ms / 1000).toFixed(1)}s`;
9+
810
const requireEnv = (key: string): string => {
911
const v = process.env[key];
1012
if (!v) throw new Error(`Missing required env var: ${key}`);
@@ -59,33 +61,25 @@ const timeoutSignal = (timeoutMs: number): AbortSignal | undefined => {
5961
return AbortSignal.timeout(timeoutMs);
6062
};
6163

62-
const getTraceLabel = (traceId?: string): string => (traceId ? `[${traceId}]` : '[no-trace]');
6364
const buildEndpointUrl = (path: string): string => (
6465
path.startsWith('/') ? `${HEVY_BASE_URL}${path}` : `${HEVY_BASE_URL}/${path}`
6566
);
66-
const formatDuration = (ms: number): string => `${(ms / 1000).toFixed(2)}s (${ms}ms)`;
6767

6868
export const hevyLogin = async (
6969
emailOrUsername: string,
7070
password: string,
7171
context: HevyRequestContext = {}
7272
): Promise<HevyLoginResponse> => {
73-
const trace = getTraceLabel(context.traceId);
74-
const startedAt = Date.now();
75-
76-
const recaptchaStartedAt = Date.now();
77-
const { token: recaptchaToken, usedCache } = await getRecaptchaToken({
78-
traceId: context.traceId,
79-
});
80-
const recaptchaDurationMs = Date.now() - recaptchaStartedAt;
81-
console.log(`${trace} ✅ Got reCAPTCHA token in ${formatDuration(recaptchaDurationMs)}`);
73+
const { token: recaptchaToken, usedCache } = await getRecaptchaToken();
74+
75+
if (usedCache) {
76+
clearTokenCache();
77+
}
8278

8379
const attemptLogin = async (token: string): Promise<{ res: Response; token: string }> => {
8480
const headers = buildHeaders();
8581
const body = { emailOrUsername, password, recaptchaToken: token, useAuth2_0: true };
8682

87-
console.log(`${trace} 📡 Calling Hevy /login API...`);
88-
const requestStartedAt = Date.now();
8983
let res: Response;
9084
try {
9185
res = await fetch(buildEndpointUrl('/login'), {
@@ -95,25 +89,16 @@ export const hevyLogin = async (
9589
signal: timeoutSignal(HEVY_LOGIN_TIMEOUT_MS),
9690
});
9791
} catch (err) {
98-
console.error(`${trace} ❌ Network error calling Hevy API: ${(err as Error).message}`);
9992
throw err;
10093
}
101-
const requestDurationMs = Date.now() - requestStartedAt;
102-
console.log(`${trace} 📡 Hevy API responded in ${formatDuration(requestDurationMs)} - Status: ${res.status}`);
10394

10495
return { res, token };
10596
};
10697

10798
let { res } = await attemptLogin(recaptchaToken);
10899

109-
if (usedCache) {
110-
clearTokenCache();
111-
}
112-
113100
if (res.status === 400) {
114-
console.log(`${trace} ⚠️ Got 400 error, retrying with fresh token...`);
115-
116-
const freshResult = await getRecaptchaToken({ traceId: context.traceId });
101+
const freshResult = await getRecaptchaToken();
117102
const retryResult = await attemptLogin(freshResult.token);
118103
res = retryResult.res;
119104

@@ -124,14 +109,12 @@ export const hevyLogin = async (
124109

125110
if (!res.ok) {
126111
const msg = await parseErrorBody(res);
127-
console.error(`${trace} ❌ Hevy API error: ${msg}`);
128112
const err = new Error(msg);
129113
(err as any).statusCode = res.status;
130114
throw err;
131115
}
132116

133117
const payload = mapOAuthResponse(await res.json() as HevyLoginResponse);
134-
console.log(`${trace} ✅ Login response parsed successfully`);
135118
return payload;
136119
};
137120

@@ -140,11 +123,9 @@ export const hevyRefreshToken = async (
140123
accessToken?: string,
141124
context: HevyRequestContext = {}
142125
): Promise<HevyLoginResponse> => {
143-
const trace = getTraceLabel(context.traceId);
144126
const startedAt = Date.now();
145127
const trimmedRefreshToken = String(refreshToken ?? '').trim();
146128
if (!trimmedRefreshToken) {
147-
console.error(`${trace} ❌ Missing refresh_token`);
148129
const err = new Error('Missing refresh_token');
149130
(err as any).statusCode = 400;
150131
throw err;
@@ -154,8 +135,6 @@ export const hevyRefreshToken = async (
154135
const body = { refresh_token: trimmedRefreshToken };
155136
const refreshUrl = buildEndpointUrl(HEVY_REFRESH_PATH);
156137

157-
console.log(`${trace} 📡 Calling Hevy /auth/refresh_token API...`);
158-
const requestStartedAt = Date.now();
159138
let res: Response;
160139
try {
161140
res = await fetch(refreshUrl, {
@@ -165,29 +144,23 @@ export const hevyRefreshToken = async (
165144
signal: timeoutSignal(HEVY_REFRESH_TIMEOUT_MS),
166145
});
167146
} catch (err) {
168-
console.error(`${trace} ❌ Network error calling Hevy refresh API: ${(err as Error).message}`);
169147
throw err;
170148
}
171-
const requestDurationMs = Date.now() - requestStartedAt;
172-
console.log(`${trace} 📡 Hevy refresh API responded in ${formatDuration(requestDurationMs)} - Status: ${res.status}`);
173149

174150
if (!res.ok) {
175151
const msg = await parseErrorBody(res);
176-
console.error(`${trace} ❌ Hevy refresh API error: ${msg}`);
177152
const err = new Error(msg);
178153
(err as any).statusCode = res.status;
179154
throw err;
180155
}
181156

182157
const payload = mapOAuthResponse(await res.json() as HevyLoginResponse);
183-
console.log(`${trace} ✅ Refresh response parsed successfully`);
184158
return payload;
185159
};
186160

187161
// Validate token by checking expiry or making a test request
188162
export const hevyValidateAuthToken = async (accessToken: string): Promise<boolean> => {
189163
try {
190-
// Try to get account info - if it works, token is valid
191164
await hevyGetAccount(accessToken);
192165
return true;
193166
} catch (err) {

0 commit comments

Comments
 (0)