Skip to content

fix : added proper error handling to failure logs #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import sharp from "sharp";

export function sanitizeUrlParam(param: string): string {
// Remove any characters that could be used for command injection
return param.replace(/[;&|`$(){}[\]<>]/g, "");
export interface LogResponse {
logs?: any[];
message?: string;
}

export interface HarFile {
Expand All @@ -27,6 +27,29 @@ export interface HarEntry {
time?: number;
}

export function validateResponse(
response: Response,
logType: string,
): LogResponse | null {
if (!response.ok) {
if (response.status === 404) {
return { message: `No ${logType} available for this session` };
}
if (response.status === 401 || response.status === 403) {
return {
message: `Unable to access ${logType} - please check your credentials`,
};
}
return { message: `Unable to fetch ${logType} at this time` };
}
return null;
}

export function sanitizeUrlParam(param: string): string {
// Remove any characters that could be used for command injection
return param.replace(/[;&|`$(){}[\]<>]/g, "");
}

const ONE_MB = 1048576;

//Compresses a base64 image intelligently to keep it under 1 MB if needed.
Expand Down
28 changes: 17 additions & 11 deletions src/tools/failurelogs-utils/app-automate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import config from "../../config.js";
import { assertOkResponse, filterLinesByKeywords } from "../../lib/utils.js";
import {
filterLinesByKeywords,
validateResponse,
LogResponse,
} from "../../lib/utils.js";

const auth = Buffer.from(
`${config.browserstackUsername}:${config.browserstackAccessKey}`,
Expand All @@ -9,7 +13,7 @@ const auth = Buffer.from(
export async function retrieveDeviceLogs(
sessionId: string,
buildId: string,
): Promise<string[]> {
): Promise<LogResponse> {
const url = `https://api.browserstack.com/app-automate/builds/${buildId}/sessions/${sessionId}/deviceLogs`;

const response = await fetch(url, {
Expand All @@ -19,17 +23,18 @@ export async function retrieveDeviceLogs(
},
});

await assertOkResponse(response, "device logs");
const validationResult = validateResponse(response, "device logs");
if (validationResult) return validationResult;

const logText = await response.text();
return filterDeviceFailures(logText);
return { logs: filterDeviceFailures(logText) };
}

// APPIUM LOGS
export async function retrieveAppiumLogs(
sessionId: string,
buildId: string,
): Promise<string[]> {
): Promise<LogResponse> {
const url = `https://api.browserstack.com/app-automate/builds/${buildId}/sessions/${sessionId}/appiumlogs`;

const response = await fetch(url, {
Expand All @@ -39,17 +44,18 @@ export async function retrieveAppiumLogs(
},
});

await assertOkResponse(response, "Appium logs");
const validationResult = validateResponse(response, "Appium logs");
if (validationResult) return validationResult;

const logText = await response.text();
return filterAppiumFailures(logText);
return { logs: filterAppiumFailures(logText) };
}

// CRASH LOGS
export async function retrieveCrashLogs(
sessionId: string,
buildId: string,
): Promise<string[]> {
): Promise<LogResponse> {
const url = `https://api.browserstack.com/app-automate/builds/${buildId}/sessions/${sessionId}/crashlogs`;

const response = await fetch(url, {
Expand All @@ -59,14 +65,14 @@ export async function retrieveCrashLogs(
},
});

await assertOkResponse(response, "crash logs");
const validationResult = validateResponse(response, "crash logs");
if (validationResult) return validationResult;

const logText = await response.text();
return filterCrashFailures(logText);
return { logs: filterCrashFailures(logText) };
}

// FILTER HELPERS

export function filterDeviceFailures(logText: string): string[] {
const keywords = [
"error",
Expand Down
63 changes: 37 additions & 26 deletions src/tools/failurelogs-utils/automate.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import config from "../../config.js";
import { HarEntry, HarFile } from "../../lib/utils.js";
import { assertOkResponse, filterLinesByKeywords } from "../../lib/utils.js";
import {
HarEntry,
HarFile,
filterLinesByKeywords,
validateResponse,
LogResponse,
} from "../../lib/utils.js";

const auth = Buffer.from(
`${config.browserstackUsername}:${config.browserstackAccessKey}`,
).toString("base64");

// NETWORK LOGS
export async function retrieveNetworkFailures(sessionId: string): Promise<any> {
export async function retrieveNetworkFailures(
sessionId: string,
): Promise<LogResponse> {
const url = `https://api.browserstack.com/automate/sessions/${sessionId}/networklogs`;

const response = await fetch(url, {
Expand All @@ -18,7 +25,8 @@ export async function retrieveNetworkFailures(sessionId: string): Promise<any> {
},
});

await assertOkResponse(response, "network logs");
const validationResult = validateResponse(response, "network logs");
if (validationResult) return validationResult;

const networklogs: HarFile = await response.json();

Expand All @@ -33,28 +41,29 @@ export async function retrieveNetworkFailures(sessionId: string): Promise<any> {
},
);

// Return only the failure entries with some context
return failureEntries.map((entry: any) => ({
startedDateTime: entry.startedDateTime,
request: {
method: entry.request?.method,
url: entry.request?.url,
queryString: entry.request?.queryString,
},
response: {
status: entry.response?.status,
statusText: entry.response?.statusText,
_error: entry.response?._error,
},
serverIPAddress: entry.serverIPAddress,
time: entry.time,
}));
return {
logs: failureEntries.map((entry: any) => ({
startedDateTime: entry.startedDateTime,
request: {
method: entry.request?.method,
url: entry.request?.url,
queryString: entry.request?.queryString,
},
response: {
status: entry.response?.status,
statusText: entry.response?.statusText,
_error: entry.response?._error,
},
serverIPAddress: entry.serverIPAddress,
time: entry.time,
})),
};
}

// SESSION LOGS
export async function retrieveSessionFailures(
sessionId: string,
): Promise<string[]> {
): Promise<LogResponse> {
const url = `https://api.browserstack.com/automate/sessions/${sessionId}/logs`;

const response = await fetch(url, {
Expand All @@ -64,16 +73,17 @@ export async function retrieveSessionFailures(
},
});

await assertOkResponse(response, "session logs");
const validationResult = validateResponse(response, "session logs");
if (validationResult) return validationResult;

const logText = await response.text();
return filterSessionFailures(logText);
return { logs: filterSessionFailures(logText) };
}

// CONSOLE LOGS
export async function retrieveConsoleFailures(
sessionId: string,
): Promise<string[]> {
): Promise<LogResponse> {
const url = `https://api.browserstack.com/automate/sessions/${sessionId}/consolelogs`;

const response = await fetch(url, {
Expand All @@ -83,10 +93,11 @@ export async function retrieveConsoleFailures(
},
});

await assertOkResponse(response, "console logs");
const validationResult = validateResponse(response, "console logs");
if (validationResult) return validationResult;

const logText = await response.text();
return filterConsoleFailures(logText);
return { logs: filterConsoleFailures(logText) };
}

// FILTER: session logs
Expand Down
62 changes: 36 additions & 26 deletions src/tools/getFailureLogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import {
retrieveCrashLogs,
} from "./failurelogs-utils/app-automate.js";
import { trackMCP } from "../lib/instrumentation.js";
import { AppAutomateLogType, AutomateLogType, SessionType } from "../lib/constants.js";
import {
AppAutomateLogType,
AutomateLogType,
SessionType,
} from "../lib/constants.js";

type LogType = AutomateLogType | AppAutomateLogType;
type SessionTypeValues = SessionType;
Expand Down Expand Up @@ -86,79 +90,85 @@ export async function getFailureLogs(args: {
],
};
}

let response;
// eslint-disable-next-line no-useless-catch
try {
for (const logType of validLogTypes) {
switch (logType) {
case AutomateLogType.NetworkLogs: {
const logs = await retrieveNetworkFailures(args.sessionId);
response = await retrieveNetworkFailures(args.sessionId);
results.push({
type: "text",
text:
logs.length > 0
? `Network Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No network failures found",
response.message ||
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

directly return the result of these conditionals in the response (for other methods as well)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain this change a bit ?

(response.logs && response.logs.length > 0
? `Network Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No network failures found"),
});
break;
}

case AutomateLogType.SessionLogs: {
const logs = await retrieveSessionFailures(args.sessionId);
response = await retrieveSessionFailures(args.sessionId);
results.push({
type: "text",
text:
logs.length > 0
? `Session Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No session failures found",
response.message ||
(response.logs && response.logs.length > 0
? `Session Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No session failures found"),
});
break;
}

case AutomateLogType.ConsoleLogs: {
const logs = await retrieveConsoleFailures(args.sessionId);
response = await retrieveConsoleFailures(args.sessionId);
results.push({
type: "text",
text:
logs.length > 0
? `Console Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No console failures found",
response.message ||
(response.logs && response.logs.length > 0
? `Console Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No console failures found"),
});
break;
}

case AppAutomateLogType.DeviceLogs: {
const logs = await retrieveDeviceLogs(args.sessionId, args.buildId!);
response = await retrieveDeviceLogs(args.sessionId, args.buildId!);
results.push({
type: "text",
text:
logs.length > 0
? `Device Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No device failures found",
response.message ||
(response.logs && response.logs.length > 0
? `Device Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No device failures found"),
});
break;
}

case AppAutomateLogType.AppiumLogs: {
const logs = await retrieveAppiumLogs(args.sessionId, args.buildId!);
response = await retrieveAppiumLogs(args.sessionId, args.buildId!);
results.push({
type: "text",
text:
logs.length > 0
? `Appium Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No Appium failures found",
response.message ||
(response.logs && response.logs.length > 0
? `Appium Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No Appium failures found"),
});
break;
}

case AppAutomateLogType.CrashLogs: {
const logs = await retrieveCrashLogs(args.sessionId, args.buildId!);
response = await retrieveCrashLogs(args.sessionId, args.buildId!);
results.push({
type: "text",
text:
logs.length > 0
? `Crash Failures (${logs.length} found):\n${JSON.stringify(logs, null, 2)}`
: "No crash failures found",
response.message ||
(response.logs && response.logs.length > 0
? `Crash Failures (${response.logs.length} found):\n${JSON.stringify(response.logs, null, 2)}`
: "No crash failures found"),
});
break;
}
Expand Down
Loading