Files
parcer/server/src/workflow-management/scheduler/index.ts

205 lines
5.5 KiB
TypeScript
Raw Normal View History

2024-09-13 14:28:52 +05:30
import fs from "fs";
import { uuid } from "uuidv4";
import { chromium } from "playwright";
import { io, Socket } from "socket.io-client";
2024-09-13 14:27:39 +05:30
import { readFile, saveFile } from "../storage";
import { createRemoteBrowserForRun, destroyRemoteBrowser } from '../../browser-management/controller';
2024-09-11 11:53:12 +05:30
import logger from '../../logger';
2024-09-12 21:01:46 +05:30
import { browserPool } from "../../server";
2024-09-19 19:41:19 +05:30
import { googleSheetUpdateTasks, processGoogleSheetUpdates } from "../integrations/gsheet";
2024-10-08 23:34:53 +05:30
import { getRecordingByFileName } from "../../routes/storage";
import Robot from "../../models/Robot";
import Run from "../../models/Run";
import { getDecryptedProxyConfig } from "../../routes/proxy";
2024-09-12 21:01:46 +05:30
async function runWorkflow(id: string) {
if (!id) {
id = uuid();
2024-09-12 00:57:01 +05:30
}
const recording = await Robot.findOne({
where: {
'recording_meta.id': id
},
raw: true
});
2024-10-08 23:34:53 +05:30
if (!recording || !recording.recording_meta || !recording.recording_meta.id) {
return {
success: false,
error: 'Recording not found'
};
}
// req.user.id will not be available here :)
const proxyConfig = await getDecryptedProxyConfig(req.user.id);
let proxyOptions: any = {};
2024-10-10 02:54:53 +05:30
if (proxyConfig.proxy_url) {
proxyOptions = {
server: proxyConfig.proxy_url,
...(proxyConfig.proxy_username && proxyConfig.proxy_password && {
username: proxyConfig.proxy_username,
password: proxyConfig.proxy_password,
}),
};
}
2024-10-08 23:34:53 +05:30
2024-09-11 11:53:12 +05:30
try {
const browserId = createRemoteBrowserForRun({
browser: chromium,
launchOptions: { headless: true }
});
const run = await Run.create({
2024-10-08 21:19:14 +05:30
status: 'Scheduled',
name: recording.recording_meta.name,
robotId: recording.id,
robotMetaId: recording.recording_meta.id,
startedAt: new Date().toLocaleString(),
finishedAt: '',
browserId: id,
2024-09-11 23:35:59 +05:30
interpreterSettings: { maxConcurrency: 1, maxRepeats: 1, debug: true },
log: '',
runId: id,
serializableOutput: {},
binaryOutput: {},
});
const plainRun = run.toJSON();
2024-09-12 00:57:01 +05:30
2024-09-12 21:01:46 +05:30
return {
browserId,
runId: plainRun.runId,
2024-09-12 21:01:46 +05:30
}
2024-09-11 11:53:12 +05:30
} catch (e) {
const { message } = e as Error;
logger.log('info', `Error while scheduling a run with id: ${id}`);
2024-09-12 00:57:01 +05:30
console.log(message);
return {
success: false,
error: message,
};
2024-09-11 11:53:12 +05:30
}
}
async function executeRun(id: string) {
2024-09-12 00:57:01 +05:30
try {
const run = await Run.findOne({ where: { runId: id } });
if (!run) {
return {
success: false,
error: 'Run not found'
}
}
2024-09-12 00:57:01 +05:30
const plainRun = run.toJSON();
2024-09-12 00:57:01 +05:30
const recording = await Robot.findOne({ where: { 'recording_meta.id': plainRun.robotMetaId }, raw: true });
if (!recording) {
return {
success: false,
error: 'Recording not found'
}
}
2024-09-12 00:57:01 +05:30
plainRun.status = 'running';
const browser = browserPool.getRemoteBrowser(plainRun.browserId);
2024-09-12 00:57:01 +05:30
if (!browser) {
throw new Error('Could not access browser');
}
const currentPage = await browser.getCurrentPage();
if (!currentPage) {
throw new Error('Could not create a new page');
}
const interpretationInfo = await browser.interpreter.InterpretRecording(
recording.recording, currentPage, plainRun.interpreterSettings);
2024-09-12 00:57:19 +05:30
await destroyRemoteBrowser(plainRun.browserId);
2024-09-12 00:57:01 +05:30
await run.update({
...run,
2024-09-19 19:38:31 +05:30
status: 'success',
2024-09-12 00:57:01 +05:30
finishedAt: new Date().toLocaleString(),
browserId: plainRun.browserId,
2024-09-12 00:57:01 +05:30
log: interpretationInfo.log.join('\n'),
serializableOutput: interpretationInfo.serializableOutput,
binaryOutput: interpretationInfo.binaryOutput,
});
2024-09-12 00:57:01 +05:30
googleSheetUpdateTasks[id] = {
name: plainRun.name,
runId: id,
2024-09-19 19:41:19 +05:30
status: 'pending',
retries: 5,
};
processGoogleSheetUpdates();
2024-09-12 19:35:27 +05:30
return true;
2024-09-12 00:57:01 +05:30
} catch (error: any) {
logger.log('info', `Error while running a recording with id: ${id} - ${error.message}`);
2024-09-12 00:57:01 +05:30
console.log(error.message);
2024-09-12 19:35:27 +05:30
return false;
2024-09-12 00:57:01 +05:30
}
}
2024-09-12 21:01:46 +05:30
2024-10-10 03:03:14 +05:30
async function readyForRunHandler(browserId: string, id: string) {
2024-09-12 21:02:07 +05:30
try {
2024-10-10 03:03:14 +05:30
const interpretation = await executeRun(id);
2024-09-12 21:02:07 +05:30
if (interpretation) {
2024-10-10 03:03:14 +05:30
logger.log('info', `Interpretation of ${id} succeeded`);
2024-09-12 21:02:07 +05:30
} else {
2024-10-10 03:03:14 +05:30
logger.log('error', `Interpretation of ${id} failed`);
2024-09-12 21:05:49 +05:30
await destroyRemoteBrowser(browserId);
2024-09-12 21:02:07 +05:30
}
2024-10-10 03:03:14 +05:30
resetRecordingState(browserId, id);
2024-09-12 21:02:07 +05:30
} catch (error: any) {
2024-09-12 21:08:36 +05:30
logger.error(`Error during readyForRunHandler: ${error.message}`);
2024-09-12 21:02:07 +05:30
await destroyRemoteBrowser(browserId);
}
}
2024-10-10 03:03:14 +05:30
function resetRecordingState(browserId: string, id: string) {
2024-09-12 21:02:27 +05:30
browserId = '';
2024-10-10 03:03:14 +05:30
id = '';
2024-09-12 21:02:27 +05:30
}
2024-09-12 21:01:46 +05:30
2024-10-07 01:22:42 +05:30
export async function handleRunRecording(fileName: string, runId: string) {
2024-09-12 21:01:46 +05:30
try {
const result = await runWorkflow(fileName, runId);
const { browserId, runId: newRunId } = result;
if (!browserId || !newRunId) {
throw new Error('browserId or runId is undefined');
}
const socket = io(`http://localhost:8080/${browserId}`, {
transports: ['websocket'],
rejectUnauthorized: false
});
socket.on('ready-for-run', () => readyForRunHandler(browserId, fileName, newRunId));
logger.log('info', `Running recording: ${fileName}`);
socket.on('disconnect', () => {
cleanupSocketListeners(socket, browserId, newRunId);
});
} catch (error: any) {
2024-09-12 21:08:36 +05:30
logger.error('Error running recording:', error);
2024-09-12 21:01:46 +05:30
}
}
function cleanupSocketListeners(socket: Socket, browserId: string, runId: string) {
socket.off('ready-for-run', () => readyForRunHandler(browserId, '', runId));
logger.log('info', `Cleaned up listeners for browserId: ${browserId}, runId: ${runId}`);
}
2024-10-07 01:23:49 +05:30
export { runWorkflow };