|
|
|
|
@@ -1,12 +1,15 @@
|
|
|
|
|
// engage-api/get-activity.ts
|
|
|
|
|
import axios from 'axios';
|
|
|
|
|
import axios, { type AxiosRequestConfig } from 'axios';
|
|
|
|
|
import { logger } from '../utils/logger';
|
|
|
|
|
import {
|
|
|
|
|
ensureSingleLogin,
|
|
|
|
|
loadCachedCookies,
|
|
|
|
|
saveCookiesToCache,
|
|
|
|
|
clearCookieCache,
|
|
|
|
|
getCachedCookieString
|
|
|
|
|
getCachedCookieString,
|
|
|
|
|
backupCookies,
|
|
|
|
|
restoreCookieBackup,
|
|
|
|
|
tryAcquireAuthLock,
|
|
|
|
|
releaseAuthCooldown
|
|
|
|
|
} from '../services/playwright-auth';
|
|
|
|
|
|
|
|
|
|
// Define interfaces for our data structures
|
|
|
|
|
@@ -51,7 +54,8 @@ async function getActivityDetailsRaw(
|
|
|
|
|
activityId: string,
|
|
|
|
|
cookies: string,
|
|
|
|
|
maxRetries: number = 3,
|
|
|
|
|
timeoutMilliseconds: number = 10000
|
|
|
|
|
timeoutMilliseconds: number = 10000,
|
|
|
|
|
signal?: AbortSignal
|
|
|
|
|
): Promise<string | null> {
|
|
|
|
|
const url = 'https://engage.nkcswx.cn/Services/ActivitiesService.asmx/GetActivityDetails';
|
|
|
|
|
const headers = {
|
|
|
|
|
@@ -65,13 +69,17 @@ async function getActivityDetailsRaw(
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
|
|
|
if (signal?.aborted) {
|
|
|
|
|
logger.debug(`Activity ${activityId} aborted before attempt ${attempt + 1}`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
logger.debug(`Attempt ${attempt + 1}/${maxRetries} for activity ${activityId} - Sending POST request to ${url}`);
|
|
|
|
|
const response = await axios.post(url, payload, {
|
|
|
|
|
headers,
|
|
|
|
|
timeout: timeoutMilliseconds,
|
|
|
|
|
responseType: 'text',
|
|
|
|
|
// Add additional timeout safety
|
|
|
|
|
signal,
|
|
|
|
|
maxRedirects: 5
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
@@ -79,14 +87,19 @@ async function getActivityDetailsRaw(
|
|
|
|
|
if (response.status !== 200) {
|
|
|
|
|
logger.error(`Non-200 status ${response.status} for activity ${activityId}. NOT updating cache to preserve local data.`);
|
|
|
|
|
|
|
|
|
|
// On 5xx errors, set flag to validate cookie on next request
|
|
|
|
|
// Backend may be in degraded state and invalidated sessions
|
|
|
|
|
if (response.status >= 500 && response.status < 600) {
|
|
|
|
|
logger.warn(`Server error ${response.status} - will validate cookie on next request.`);
|
|
|
|
|
shouldValidateCookieOnNextRequest = true;
|
|
|
|
|
// IMPORTANT: Only 500 is cookie expiration. Other 5xx (502/503/504) are real server outages.
|
|
|
|
|
// The backend returns 500 when cookie is expired but session not yet invalidated.
|
|
|
|
|
// It takes several hours before it returns 401/403.
|
|
|
|
|
// 502/503/504 are real server errors (bad gateway, service unavailable, gateway timeout)
|
|
|
|
|
if (response.status === 500) {
|
|
|
|
|
logger.warn(`Server error 500 - this is cookie expiration. Throwing AuthenticationError to trigger immediate re-login.`);
|
|
|
|
|
throw new AuthenticationError(`Received 500 for activity ${activityId} - expired cookie`, 500);
|
|
|
|
|
} else if (response.status >= 500 && response.status < 600) {
|
|
|
|
|
// Real server outage (502/503/504), preserve cache and don't re-login
|
|
|
|
|
logger.error(`Real server outage ${response.status} - preserving local cache, not re-login.`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Return null immediately on non-200, don't retry
|
|
|
|
|
// Return null immediately on non-200 errors
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -115,12 +128,15 @@ async function getActivityDetailsRaw(
|
|
|
|
|
|
|
|
|
|
if (error.response) {
|
|
|
|
|
logger.error(`Status: ${error.response.status}, Data (getActivityDetailsRaw): ${ String(error.response.data).slice(0,100)}...`);
|
|
|
|
|
// CRITICAL: 5xx errors should NOT update cache, return null immediately
|
|
|
|
|
if (error.response.status >= 500 && error.response.status < 600) {
|
|
|
|
|
logger.error(`Server error ${error.response.status} - preserving local cache, not updating.`);
|
|
|
|
|
// Set flag to validate cookie on next request
|
|
|
|
|
shouldValidateCookieOnNextRequest = true;
|
|
|
|
|
return null;
|
|
|
|
|
// IMPORTANT: Only 500 is cookie expiration. Other 5xx (502/503/504) are real server outages.
|
|
|
|
|
// The backend returns 500 when cookie is expired but session not yet invalidated.
|
|
|
|
|
// 502/503/504 are real server errors (bad gateway, service unavailable, gateway timeout)
|
|
|
|
|
if (error.response.status === 500) {
|
|
|
|
|
logger.warn(`Server error 500 - this is cookie expiration. Throwing AuthenticationError to trigger immediate re-login.`);
|
|
|
|
|
throw new AuthenticationError(`Received 500 for activity ${activityId} - expired cookie`, 500);
|
|
|
|
|
} else if (error.response.status >= 500 && error.response.status < 600) {
|
|
|
|
|
// Real server outage (502/503/504), preserve cache and don't re-login
|
|
|
|
|
logger.error(`Real server outage ${error.response.status} - preserving local cache, not re-login.`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (attempt === maxRetries - 1) {
|
|
|
|
|
@@ -134,9 +150,6 @@ async function getActivityDetailsRaw(
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Flag to track if we need to validate cookies after server errors
|
|
|
|
|
let shouldValidateCookieOnNextRequest = false;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Main exported function. Handles cookie caching, validation, re-authentication, and fetches activity details.
|
|
|
|
|
* @param activityId - The ID of the activity to fetch.
|
|
|
|
|
@@ -150,6 +163,7 @@ export async function fetchActivityData(
|
|
|
|
|
userName: string,
|
|
|
|
|
userPwd: string,
|
|
|
|
|
forceLogin: boolean = false,
|
|
|
|
|
signal?: AbortSignal
|
|
|
|
|
): Promise<any | null> {
|
|
|
|
|
let currentCookie = forceLogin ? null : await getCachedCookieString();
|
|
|
|
|
|
|
|
|
|
@@ -159,17 +173,10 @@ export async function fetchActivityData(
|
|
|
|
|
currentCookie = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Optimization: Skip pre-validation, directly request data
|
|
|
|
|
// Only validate/re-login when we get 4xx error OR after 5xx (backend may be in degraded state)
|
|
|
|
|
if (!currentCookie) {
|
|
|
|
|
logger.info('No cached cookie found. Attempting login...');
|
|
|
|
|
try {
|
|
|
|
|
currentCookie = await getCompleteCookies(userName, userPwd);
|
|
|
|
|
|
|
|
|
|
const cookies = await loadCachedCookies();
|
|
|
|
|
if (cookies) {
|
|
|
|
|
await saveCookiesToCache(cookies);
|
|
|
|
|
}
|
|
|
|
|
} catch (loginError) {
|
|
|
|
|
logger.error(`Login process failed: ${(loginError as Error).message}`);
|
|
|
|
|
return null;
|
|
|
|
|
@@ -181,101 +188,42 @@ export async function fetchActivityData(
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Validate cookie after previous 5xx error (backend may have invalidated sessions)
|
|
|
|
|
if (shouldValidateCookieOnNextRequest) {
|
|
|
|
|
logger.info('Validating cookie after previous server error...');
|
|
|
|
|
shouldValidateCookieOnNextRequest = false;
|
|
|
|
|
// Simple validation: try to fetch a known activity (ID 3350)
|
|
|
|
|
const testResponse = await getActivityDetailsRaw('3350', currentCookie, 1, 5000);
|
|
|
|
|
if (!testResponse) {
|
|
|
|
|
// Check if this is still a server error (5xx) - if so, it's an outage, don't re-login
|
|
|
|
|
// Just preserve existing cookie and return null
|
|
|
|
|
logger.warn('Cookie validation returned null. Checking if server is still down...');
|
|
|
|
|
|
|
|
|
|
// Try one more time with explicit status check
|
|
|
|
|
try {
|
|
|
|
|
const url = 'https://engage.nkcswx.cn/Services/ActivitiesService.asmx/GetActivityDetails';
|
|
|
|
|
const headers = {
|
|
|
|
|
'Content-Type': 'application/json; charset=UTF-8',
|
|
|
|
|
'Cookie': currentCookie,
|
|
|
|
|
'User-Agent': 'Mozilla/5.0 (Bun DSAS-CCA Cookie Validator)',
|
|
|
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
|
|
|
};
|
|
|
|
|
const payload = { "activityID": "3350" };
|
|
|
|
|
const validationResponse = await axios.post(url, payload, {
|
|
|
|
|
headers,
|
|
|
|
|
timeout: 5000,
|
|
|
|
|
responseType: 'text'
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (validationResponse.status >= 500 && validationResponse.status < 600) {
|
|
|
|
|
// Server still returning 5xx - it's an outage, preserve cookie and don't re-login
|
|
|
|
|
logger.warn('Server still returning 5xx during validation - treating as server outage, preserving cookie.');
|
|
|
|
|
return null;
|
|
|
|
|
} else if (validationResponse.status === 401 || validationResponse.status === 403) {
|
|
|
|
|
// Cookie is invalid, re-login
|
|
|
|
|
logger.warn('Cookie validation failed with 4xx. Re-login required.');
|
|
|
|
|
await clearCookieCache();
|
|
|
|
|
try {
|
|
|
|
|
currentCookie = await getCompleteCookies(userName, userPwd);
|
|
|
|
|
const cookies = await loadCachedCookies();
|
|
|
|
|
if (cookies) {
|
|
|
|
|
await saveCookiesToCache(cookies);
|
|
|
|
|
}
|
|
|
|
|
logger.info('Re-login completed due to cookie validation failure.');
|
|
|
|
|
} catch (loginError) {
|
|
|
|
|
logger.error(`Re-login failed: ${(loginError as Error).message}`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// Some other error, preserve cookie
|
|
|
|
|
logger.warn('Cookie validation failed with unexpected status. Preserving existing cookie.');
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
} catch (validationError: any) {
|
|
|
|
|
// Network error or timeout during validation - treat as server issue, preserve cookie
|
|
|
|
|
if (validationError.response && validationError.response.status >= 500) {
|
|
|
|
|
logger.warn('Server error during cookie validation - treating as outage, preserving cookie.');
|
|
|
|
|
} else {
|
|
|
|
|
logger.warn(`Network error during cookie validation: ${validationError.message}. Preserving existing cookie.`);
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
logger.info('Cookie validation successful after server error.');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.debug('Using cached cookie for API request.');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
logger.debug(`Calling getActivityDetailsRaw for activity ${activityId}...`);
|
|
|
|
|
const rawActivityDetailsString = await getActivityDetailsRaw(activityId, currentCookie);
|
|
|
|
|
const rawActivityDetailsString = await getActivityDetailsRaw(activityId, currentCookie, 3, 10000, signal);
|
|
|
|
|
logger.debug(`getActivityDetailsRaw returned for activity ${activityId}`);
|
|
|
|
|
if (rawActivityDetailsString) {
|
|
|
|
|
const parsedOuter = JSON.parse(rawActivityDetailsString);
|
|
|
|
|
return JSON.parse(parsedOuter.d);
|
|
|
|
|
}
|
|
|
|
|
// Check if this was a 5xx error and set flag for cookie validation
|
|
|
|
|
logger.warn(`No data returned from getActivityDetailsRaw for activity ${activityId}, but no authentication error was thrown.`);
|
|
|
|
|
return null;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (signal?.aborted) {
|
|
|
|
|
logger.debug(`Activity ${activityId} fetch aborted.`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
if (error instanceof AuthenticationError) {
|
|
|
|
|
// Cookie returned 4xx, now validate and re-login
|
|
|
|
|
logger.warn(`API returned 4xx error (Status: ${error.status}). Cookie may be invalid. Attempting re-login and retry.`);
|
|
|
|
|
// Throttle: prevent thundering herd from multiple 500 errors
|
|
|
|
|
if (!tryAcquireAuthLock()) {
|
|
|
|
|
logger.info(`Auth throttled for activity ${activityId}. Reusing current cookies — likely still valid.`);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Backup cookies before clearing so we can restore on re-login failure
|
|
|
|
|
backupCookies();
|
|
|
|
|
await clearCookieCache();
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
logger.info('Attempting re-login due to authentication failure...');
|
|
|
|
|
currentCookie = await getCompleteCookies(userName, userPwd);
|
|
|
|
|
|
|
|
|
|
const cookies = await loadCachedCookies();
|
|
|
|
|
if (cookies) {
|
|
|
|
|
await saveCookiesToCache(cookies);
|
|
|
|
|
}
|
|
|
|
|
releaseAuthCooldown();
|
|
|
|
|
|
|
|
|
|
logger.info('Re-login successful. Retrying request for activity details...');
|
|
|
|
|
const rawActivityDetailsStringRetry = await getActivityDetailsRaw(activityId, currentCookie);
|
|
|
|
|
const rawActivityDetailsStringRetry = await getActivityDetailsRaw(activityId, currentCookie, 1, 10000, signal);
|
|
|
|
|
if (rawActivityDetailsStringRetry) {
|
|
|
|
|
const parsedOuterRetry = JSON.parse(rawActivityDetailsStringRetry);
|
|
|
|
|
return JSON.parse(parsedOuterRetry.d);
|
|
|
|
|
@@ -283,7 +231,9 @@ export async function fetchActivityData(
|
|
|
|
|
logger.warn(`Still no details for activity ${activityId} after re-login and retry.`);
|
|
|
|
|
return null;
|
|
|
|
|
} catch (retryLoginOrFetchError) {
|
|
|
|
|
logger.error(`Error during re-login or retry fetch for activity ${activityId}: ${(retryLoginOrFetchError as Error).message}`);
|
|
|
|
|
logger.error(`Re-login or retry failed for activity ${activityId}: ${(retryLoginOrFetchError as Error).message}`);
|
|
|
|
|
// Restore old cookies instead of leaving cache empty
|
|
|
|
|
await restoreCookieBackup();
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
|