Skip to content
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

fix: prevent page reload on run trigger to open remote browser #389

Open
wants to merge 17 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
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
20 changes: 18 additions & 2 deletions server/src/browser-management/classes/BrowserPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ interface BrowserPoolInfo {
* @default false
*/
active: boolean,

isRobotRun?: boolean;
}

/**
Expand Down Expand Up @@ -46,17 +48,29 @@ export class BrowserPool {
* @param browser remote browser instance
* @param active states if the browser's instance is being actively used
*/
public addRemoteBrowser = (id: string, browser: RemoteBrowser, active: boolean = false): void => {
public addRemoteBrowser = (id: string, browser: RemoteBrowser, active: boolean = false, isRobotRun: boolean = false): void => {
this.pool = {
...this.pool,
[id]: {
browser,
active,
isRobotRun
},
}
logger.log('debug', `Remote browser with id: ${id} added to the pool`);
};

public hasActiveRobotRun(): boolean {
return Object.values(this.pool).some(info => info.isRobotRun);
}

public clearRobotRunState(id: string): void {
if (this.pool[id]) {
this.pool[id].isRobotRun = false;
logger.log('debug', `Robot run state cleared for browser ${id}`);
}
}

/**
* Removes the remote browser instance from the pool.
* @param id remote browser instance's id
Expand All @@ -67,6 +81,8 @@ export class BrowserPool {
logger.log('warn', `Remote browser with id: ${id} does not exist in the pool`);
return false;
}

this.clearRobotRunState(id);
delete (this.pool[id]);
logger.log('debug', `Remote browser with id: ${id} deleted from the pool`);
return true;
Expand Down Expand Up @@ -97,4 +113,4 @@ export class BrowserPool {
logger.log('warn', `No active browser in the pool`);
return null;
};
}
}
4 changes: 2 additions & 2 deletions server/src/browser-management/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const createRemoteBrowserForRun = (userId: string): string => {
async (socket: Socket) => {
const browserSession = new RemoteBrowser(socket);
await browserSession.initialize(userId);
browserPool.addRemoteBrowser(id, browserSession, true);
browserPool.addRemoteBrowser(id, browserSession, true, true);
socket.emit('ready-for-run');
});
return id;
Expand Down Expand Up @@ -154,4 +154,4 @@ export const stopRunningInterpretation = async () => {
} else {
logger.log('error', 'Cannot stop interpretation: No active browser or generator.');
}
};
};
14 changes: 13 additions & 1 deletion server/src/routes/record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import stealthPlugin from 'puppeteer-extra-plugin-stealth';
import logger from "../logger";
import { getDecryptedProxyConfig } from './proxy';
import { requireSignIn } from '../middlewares/auth';
import { browserPool } from '../server';

export const router = Router();
chromium.use(stealthPlugin());
Expand All @@ -33,6 +34,17 @@ router.all('/', requireSignIn, (req, res, next) => {
next() // pass control to the next handler
})

router.use('/', requireSignIn, (req: AuthenticatedRequest, res: Response, next) => {
if (browserPool.hasActiveRobotRun()) {
logger.log('debug', 'Preventing browser initialization - robot run in progress');
return res.status(403).json({
error: 'Cannot initialize recording browser while a robot run is in progress'
});
}
next();
});
Comment on lines +37 to +45
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Race condition risk confirmed in browser pool management

The current implementation of BrowserPool lacks proper synchronization mechanisms. Multiple concurrent requests could potentially pass the hasActiveRobotRun check before any of them sets the robot run state, as the operations are not atomic. While Node.js's event loop provides some protection, it's not guaranteed to be safe in high-concurrency scenarios.

Suggested improvements:

  • Implement proper locking mechanism or semaphore for robot run state changes
  • Consider using atomic operations for state transitions
  • Add request queuing to serialize the robot run initialization
🔗 Analysis chain

Preventing parallel sessions on robot runs.

Blocking new browser sessions when hasActiveRobotRun is true is a solid approach. For high-traffic scenarios, consider if multiple requests might pass this check simultaneously (race condition) before the run is registered. If needed, use a lock or queue to serialize these events and avoid edge cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Gather usage references to see how `hasActiveRobotRun` is being checked.
rg -A 4 "hasActiveRobotRun"

Length of output: 878


Script:

#!/bin/bash
# Find where robot runs are initiated and how isRobotRun is set
ast-grep --pattern 'isRobotRun = true'
rg -B 2 -A 4 "isRobotRun.*=.*true"

# Look for any synchronization mechanisms
rg -i "lock|mutex|semaphore|atomic"

Length of output: 3944


Script:

#!/bin/bash
# Get the complete BrowserPool implementation
cat server/src/browser-management/classes/BrowserPool.ts

# Find robot run related code
rg -B 2 -A 4 "robotRun|robot.*run"

Length of output: 14625



/**
* GET endpoint for starting the remote browser recording session.
* returns session's id
Expand Down Expand Up @@ -131,4 +143,4 @@ router.get('/interpret', requireSignIn, async (req, res) => {
router.get('/interpret/stop', requireSignIn, async (req, res) => {
await stopRunningInterpretation();
return res.send('interpretation stopped');
});
});
5 changes: 5 additions & 0 deletions server/src/routes/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,11 @@ router.put('/runs/:id', requireSignIn, async (req: AuthenticatedRequest, res) =>
binaryOutput: {},
});

const job = await workflowQueue.add(
'run workflow',
{ id, runId, userId: req.user.id, isScheduled: false },
);

const plainRun = run.toJSON();

return res.send({
Expand Down
44 changes: 25 additions & 19 deletions server/src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Queue, Worker } from 'bullmq';
import IORedis from 'ioredis';
import logger from './logger';
import { handleRunRecording } from "./workflow-management/scheduler";
import { handleRunRecording as handleScheduledRunRecording } from "./workflow-management/scheduler";
import { handleRunRecording } from './workflow-management/record';
import Robot from './models/Robot';
import { computeNextRun } from './utils/schedule';

Expand All @@ -22,9 +23,11 @@ connection.on('error', (err) => {
const workflowQueue = new Queue('workflow', { connection });

const worker = new Worker('workflow', async job => {
const { runId, userId, id } = job.data;
const { runId, userId, id, isScheduled = true } = job.data;
try {
const result = await handleRunRecording(id, userId);
const result = isScheduled ?
await handleScheduledRunRecording(id, userId) :
await handleRunRecording(id, userId, runId);
return result;
} catch (error) {
logger.error('Error running workflow:', error);
Expand All @@ -34,23 +37,26 @@ const worker = new Worker('workflow', async job => {

worker.on('completed', async (job: any) => {
logger.log(`info`, `Job ${job.id} completed for ${job.data.runId}`);
const robot = await Robot.findOne({ where: { 'recording_meta.id': job.data.id } });
if (robot) {
// Update `lastRunAt` to the current time
const lastRunAt = new Date();

if (job.data.isScheduled) {
const robot = await Robot.findOne({ where: { 'recording_meta.id': job.data.id } });
if (robot) {
// Update `lastRunAt` to the current time
const lastRunAt = new Date();

// Compute the next run date
if (robot.schedule && robot.schedule.cronExpression && robot.schedule.timezone) {
const nextRunAt = computeNextRun(robot.schedule.cronExpression, robot.schedule.timezone) || undefined;
await robot.update({
schedule: {
...robot.schedule,
lastRunAt,
nextRunAt,
},
});
} else {
logger.error('Robot schedule, cronExpression, or timezone is missing.');
// Compute the next run date
if (robot.schedule && robot.schedule.cronExpression && robot.schedule.timezone) {
const nextRunAt = computeNextRun(robot.schedule.cronExpression, robot.schedule.timezone) || undefined;
await robot.update({
schedule: {
...robot.schedule,
lastRunAt,
nextRunAt,
},
});
} else {
logger.error('Robot schedule, cronExpression, or timezone is missing.');
}
}
}
});
Expand Down
4 changes: 3 additions & 1 deletion server/src/workflow-management/classes/Interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,8 @@ export class WorkflowInterpreter {
}, {})
}

this.socket.emit('run-completed', "success");

logger.log('debug', `Interpretation finished`);
this.clearState();
return result;
Expand All @@ -354,4 +356,4 @@ export class WorkflowInterpreter {
this.socket = socket;
this.subscribeToPausing();
};
}
}
32 changes: 22 additions & 10 deletions src/pages/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,14 @@ export const MainPage = ({ handleEditRecording, initialContent }: MainPageProps)
const readyForRunHandler = useCallback((browserId: string, runId: string) => {
interpretStoredRecording(runId).then(async (interpretation: boolean) => {
if (!aborted) {
if (interpretation) {
notify('success', t('main_page.notifications.interpretation_success', { name: runningRecordingName }));
} else {
notify('success', t('main_page.notifications.interpretation_failed', { name: runningRecordingName }));
// destroy the created browser
await stopRecording(browserId);
}
// if (interpretation) {
// notify('success', t('main_page.notifications.interpretation_success', { name: runningRecordingName }));
// } else {
// notify('success', t('main_page.notifications.interpretation_failed', { name: runningRecordingName }));
// // destroy the created browser
// await stopRecording(browserId);
// }
if (!interpretation) await stopRecording(browserId);
}
setRunningRecordingName('');
setCurrentInterpretationLog('');
Expand All @@ -96,8 +97,19 @@ export const MainPage = ({ handleEditRecording, initialContent }: MainPageProps)
rejectUnauthorized: false
});
setSockets(sockets => [...sockets, socket]);
socket.on('ready-for-run', () => readyForRunHandler(browserId, runId));
socket.on('debugMessage', debugMessageHandler);

socket.on('run-completed', (status) => {
if (status === 'success') {
notify('success', t('main_page.notifications.interpretation_success', { name: runningRecordingName }));
} else {
notify('error', t('main_page.notifications.interpretation_failed', { name: runningRecordingName }));
}
setRunningRecordingName('');
setCurrentInterpretationLog('');
setRerenderRuns(true);
});

setContent('runs');
if (browserId) {
notify('info', t('main_page.notifications.run_started', { name: runningRecordingName }));
Expand All @@ -106,10 +118,10 @@ export const MainPage = ({ handleEditRecording, initialContent }: MainPageProps)
}
})
return (socket: Socket, browserId: string, runId: string) => {
socket.off('ready-for-run', () => readyForRunHandler(browserId, runId));
socket.off('debugMessage', debugMessageHandler);
socket.off('run-completed');
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use identical function references to remove socket listeners.
Calling socket.off('run-completed', () => ...) with a new inline arrow function won’t remove the original listener. This can lead to memory leaks or multiple event fires. Store the listener in a variable and pass the same reference to both on and off.

- socket.on('run-completed', (status) => { ... });
- socket.off('run-completed', () => { ... });
+ const handleRunCompleted = (status) => { ... };
+ socket.on('run-completed', handleRunCompleted);
+ socket.off('run-completed', handleRunCompleted);

Committable suggestion skipped: line range outside the PR's diff.

}
}, [runningRecordingName, sockets, ids, readyForRunHandler, debugMessageHandler])
}, [runningRecordingName, sockets, ids, debugMessageHandler])

const handleScheduleRecording = (settings: ScheduleSettings) => {
scheduleStoredRecording(runningRecordingId, settings)
Expand Down