refactor: pass context as object to event handlers

This commit is contained in:
James Murdza 2024-10-24 17:15:58 -06:00
parent 98eda3b080
commit af83b33f51
2 changed files with 80 additions and 61 deletions

View File

@ -6,6 +6,16 @@ import { SecureGitClient } from "./SecureGitClient"
import { TerminalManager } from "./TerminalManager" import { TerminalManager } from "./TerminalManager"
import { LockManager } from "./utils" import { LockManager } from "./utils"
export interface HandlerContext {
fileManager: FileManager;
terminalManager: TerminalManager;
sandboxManager: any;
aiWorker: AIWorker;
dokkuClient: DokkuClient | null;
gitClient: SecureGitClient | null;
lockManager: LockManager
}
// Extract port number from a string // Extract port number from a string
function extractPortNumber(inputString: string): number | null { function extractPortNumber(inputString: string): number | null {
const cleanedString = inputString.replace(/\x1B\[[0-9;]*m/g, "") const cleanedString = inputString.replace(/\x1B\[[0-9;]*m/g, "")
@ -15,82 +25,82 @@ function extractPortNumber(inputString: string): number | null {
} }
// Handle heartbeat from a socket connection // Handle heartbeat from a socket connection
export function handleHeartbeat(socket: any, data: any, containers: any) { export function handleHeartbeat(data: any, context: HandlerContext) {
containers[data.sandboxId].setTimeout(CONTAINER_TIMEOUT) context.sandboxManager.setTimeout(CONTAINER_TIMEOUT)
} }
// Handle getting a file // Handle getting a file
export function handleGetFile(fileManager: FileManager, fileId: string) { export function handleGetFile(fileId: string, context: HandlerContext) {
return fileManager.getFile(fileId) return context.fileManager.getFile(fileId)
} }
// Handle getting a folder // Handle getting a folder
export function handleGetFolder(fileManager: FileManager, folderId: string) { export function handleGetFolder(folderId: string, context: HandlerContext) {
return fileManager.getFolder(folderId) return context.fileManager.getFolder(folderId)
} }
// Handle saving a file // Handle saving a file
export function handleSaveFile(fileManager: FileManager, fileId: string, body: string) { export function handleSaveFile(fileId: string, body: string, context: HandlerContext) {
return fileManager.saveFile(fileId, body) return context.fileManager.saveFile(fileId, body)
} }
// Handle moving a file // Handle moving a file
export function handleMoveFile(fileManager: FileManager, fileId: string, folderId: string) { export function handleMoveFile(fileId: string, folderId: string, context: HandlerContext) {
return fileManager.moveFile(fileId, folderId) return context.fileManager.moveFile(fileId, folderId)
} }
// Handle listing apps // Handle listing apps
export async function handleListApps(client: DokkuClient | null) { export async function handleListApps(context: HandlerContext) {
if (!client) throw Error("Failed to retrieve apps list: No Dokku client") if (!context.dokkuClient) throw Error("Failed to retrieve apps list: No Dokku client")
return { success: true, apps: await client.listApps() } return { success: true, apps: await context.dokkuClient.listApps() }
} }
// Handle deploying code // Handle deploying code
export async function handleDeploy(git: SecureGitClient | null, fileManager: FileManager, sandboxId: string) { export async function handleDeploy(sandboxId: string, context: HandlerContext) {
if (!git) throw Error("Failed to retrieve apps list: No git client") if (!context.gitClient) throw Error("Failed to retrieve apps list: No git client")
const fixedFilePaths = fileManager.sandboxFiles.fileData.map((file) => ({ const fixedFilePaths = context.fileManager.sandboxFiles.fileData.map((file) => ({
...file, ...file,
id: file.id.split("/").slice(2).join("/"), id: file.id.split("/").slice(2).join("/"),
})) }))
await git.pushFiles(fixedFilePaths, sandboxId) await context.gitClient.pushFiles(fixedFilePaths, sandboxId)
return { success: true } return { success: true }
} }
// Handle creating a file // Handle creating a file
export function handleCreateFile(fileManager: FileManager, name: string) { export function handleCreateFile(name: string, context: HandlerContext) {
return fileManager.createFile(name) return context.fileManager.createFile(name)
} }
// Handle creating a folder // Handle creating a folder
export function handleCreateFolder(fileManager: FileManager, name: string) { export function handleCreateFolder(name: string, context: HandlerContext) {
return fileManager.createFolder(name) return context.fileManager.createFolder(name)
} }
// Handle renaming a file // Handle renaming a file
export function handleRenameFile(fileManager: FileManager, fileId: string, newName: string) { export function handleRenameFile(fileId: string, newName: string, context: HandlerContext) {
return fileManager.renameFile(fileId, newName) return context.fileManager.renameFile(fileId, newName)
} }
// Handle deleting a file // Handle deleting a file
export function handleDeleteFile(fileManager: FileManager, fileId: string) { export function handleDeleteFile(fileId: string, context: HandlerContext) {
return fileManager.deleteFile(fileId) return context.fileManager.deleteFile(fileId)
} }
// Handle deleting a folder // Handle deleting a folder
export function handleDeleteFolder(fileManager: FileManager, folderId: string) { export function handleDeleteFolder(folderId: string, context: HandlerContext) {
return fileManager.deleteFolder(folderId) return context.fileManager.deleteFolder(folderId)
} }
// Handle creating a terminal session // Handle creating a terminal session
export async function handleCreateTerminal(lockManager: LockManager, terminalManager: TerminalManager, id: string, socket: any, containers: any, data: any) { export async function handleCreateTerminal(id: string, socket: any, data: any, context: HandlerContext) {
await lockManager.acquireLock(data.sandboxId, async () => { await context.lockManager.acquireLock(data.sandboxId, async () => {
await terminalManager.createTerminal(id, (responseString: string) => { await context.terminalManager.createTerminal(id, (responseString: string) => {
socket.emit("terminalResponse", { id, data: responseString }) socket.emit("terminalResponse", { id, data: responseString })
const port = extractPortNumber(responseString) const port = extractPortNumber(responseString)
if (port) { if (port) {
socket.emit( socket.emit(
"previewURL", "previewURL",
"https://" + containers[data.sandboxId].getHost(port) "https://" + context.sandboxManager.getHost(port)
) )
} }
}) })
@ -98,22 +108,21 @@ export async function handleCreateTerminal(lockManager: LockManager, terminalMan
} }
// Handle resizing a terminal // Handle resizing a terminal
export function handleResizeTerminal(terminalManager: TerminalManager, dimensions: { cols: number; rows: number }) { export function handleResizeTerminal(dimensions: { cols: number; rows: number }, context: HandlerContext) {
terminalManager.resizeTerminal(dimensions) context.terminalManager.resizeTerminal(dimensions)
} }
// Handle sending data to a terminal // Handle sending data to a terminal
export function handleTerminalData(terminalManager: TerminalManager, id: string, data: string) { export function handleTerminalData(id: string, data: string, context: HandlerContext) {
return terminalManager.sendTerminalData(id, data) return context.terminalManager.sendTerminalData(id, data)
} }
// Handle closing a terminal // Handle closing a terminal
export function handleCloseTerminal(terminalManager: TerminalManager, id: string) { export function handleCloseTerminal(id: string, context: HandlerContext) {
return terminalManager.closeTerminal(id) return context.terminalManager.closeTerminal(id)
} }
// Handle generating code // Handle generating code
export function handleGenerateCode(aiWorker: AIWorker, userId: string, fileName: string, code: string, line: number, instructions: string) { export function handleGenerateCode(userId: string, fileName: string, code: string, line: number, instructions: string, context: HandlerContext) {
return aiWorker.generateCode(userId, fileName, code, line, instructions) return context.aiWorker.generateCode(userId, fileName, code, line, instructions)
}
} }

View File

@ -18,7 +18,7 @@ import {
saveFileRL, saveFileRL,
} from "./ratelimit" } from "./ratelimit"
import { SecureGitClient } from "./SecureGitClient" import { SecureGitClient } from "./SecureGitClient"
import { handleCloseTerminal, handleCreateFile, handleCreateFolder, handleCreateTerminal, handleDeleteFile, handleDeleteFolder, handleDeploy, handleDisconnect, handleGenerateCode, handleGetFile, handleGetFolder, handleHeartbeat, handleListApps, handleMoveFile, handleRenameFile, handleResizeTerminal, handleSaveFile, handleTerminalData } from "./SocketHandlers" import { handleCloseTerminal, handleCreateFile, handleCreateFolder, handleCreateTerminal, handleDeleteFile, handleDeleteFolder, handleDeploy, handleGenerateCode, handleGetFile, handleGetFolder, handleHeartbeat, handleListApps, handleMoveFile, HandlerContext, handleRenameFile, handleResizeTerminal, handleSaveFile, handleTerminalData } from "./SocketHandlers"
import { TerminalManager } from "./TerminalManager" import { TerminalManager } from "./TerminalManager"
import { DokkuResponse, User } from "./types" import { DokkuResponse, User } from "./types"
import { LockManager } from "./utils" import { LockManager } from "./utils"
@ -134,7 +134,7 @@ if (!process.env.DOKKU_KEY)
console.error("Environment variable DOKKU_KEY is not defined") console.error("Environment variable DOKKU_KEY is not defined")
// Initialize Dokku client // Initialize Dokku client
const client = const dokkuClient =
process.env.DOKKU_HOST && process.env.DOKKU_KEY && process.env.DOKKU_USERNAME process.env.DOKKU_HOST && process.env.DOKKU_KEY && process.env.DOKKU_USERNAME
? new DokkuClient({ ? new DokkuClient({
host: process.env.DOKKU_HOST, host: process.env.DOKKU_HOST,
@ -142,10 +142,10 @@ const client =
privateKey: fs.readFileSync(process.env.DOKKU_KEY), privateKey: fs.readFileSync(process.env.DOKKU_KEY),
}) })
: null : null
client?.connect() dokkuClient?.connect()
// Initialize Git client used to deploy Dokku apps // Initialize Git client used to deploy Dokku apps
const git = const gitClient =
process.env.DOKKU_HOST && process.env.DOKKU_KEY process.env.DOKKU_HOST && process.env.DOKKU_KEY
? new SecureGitClient( ? new SecureGitClient(
`dokku@${process.env.DOKKU_HOST}`, `dokku@${process.env.DOKKU_HOST}`,
@ -228,10 +228,20 @@ io.on("connection", async (socket) => {
// Load file list from the file manager into the editor // Load file list from the file manager into the editor
sendLoadedEvent(fileManager.sandboxFiles) sendLoadedEvent(fileManager.sandboxFiles)
const handlerContext: HandlerContext = {
fileManager,
terminalManager,
aiWorker,
dokkuClient,
gitClient,
lockManager,
sandboxManager: containers[data.sandboxId],
}
// Handle various socket events (heartbeat, file operations, terminal operations, etc.) // Handle various socket events (heartbeat, file operations, terminal operations, etc.)
socket.on("heartbeat", async () => { socket.on("heartbeat", async () => {
try { try {
handleHeartbeat(socket, data, containers) handleHeartbeat(data, handlerContext)
} catch (e: any) { } catch (e: any) {
console.error("Error setting timeout:", e) console.error("Error setting timeout:", e)
socket.emit("error", `Error: set timeout. ${e.message ?? e}`) socket.emit("error", `Error: set timeout. ${e.message ?? e}`)
@ -240,7 +250,7 @@ io.on("connection", async (socket) => {
socket.on("getFile", async (fileId: string, callback) => { socket.on("getFile", async (fileId: string, callback) => {
try { try {
callback(await handleGetFile(fileManager, fileId)) callback(await handleGetFile(fileId, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error getting file:", e) console.error("Error getting file:", e)
socket.emit("error", `Error: get file. ${e.message ?? e}`) socket.emit("error", `Error: get file. ${e.message ?? e}`)
@ -249,7 +259,7 @@ io.on("connection", async (socket) => {
socket.on("getFolder", async (folderId: string, callback) => { socket.on("getFolder", async (folderId: string, callback) => {
try { try {
callback(await handleGetFolder(fileManager, folderId)) callback(await handleGetFolder(folderId, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error getting folder:", e) console.error("Error getting folder:", e)
socket.emit("error", `Error: get folder. ${e.message ?? e}`) socket.emit("error", `Error: get folder. ${e.message ?? e}`)
@ -259,7 +269,7 @@ io.on("connection", async (socket) => {
socket.on("saveFile", async (fileId: string, body: string) => { socket.on("saveFile", async (fileId: string, body: string) => {
try { try {
await saveFileRL.consume(data.userId, 1) await saveFileRL.consume(data.userId, 1)
await handleSaveFile(fileManager, fileId, body) await handleSaveFile(fileId, body, handlerContext)
} catch (e: any) { } catch (e: any) {
console.error("Error saving file:", e) console.error("Error saving file:", e)
socket.emit("error", `Error: file saving. ${e.message ?? e}`) socket.emit("error", `Error: file saving. ${e.message ?? e}`)
@ -268,7 +278,7 @@ io.on("connection", async (socket) => {
socket.on("moveFile", async (fileId: string, folderId: string, callback) => { socket.on("moveFile", async (fileId: string, folderId: string, callback) => {
try { try {
callback(await handleMoveFile(fileManager, fileId, folderId)) callback(await handleMoveFile(fileId, folderId, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error moving file:", e) console.error("Error moving file:", e)
socket.emit("error", `Error: file moving. ${e.message ?? e}`) socket.emit("error", `Error: file moving. ${e.message ?? e}`)
@ -278,7 +288,7 @@ io.on("connection", async (socket) => {
socket.on("list", async (callback: (response: DokkuResponse) => void) => { socket.on("list", async (callback: (response: DokkuResponse) => void) => {
console.log("Retrieving apps list...") console.log("Retrieving apps list...")
try { try {
callback(await handleListApps(client)) callback(await handleListApps(handlerContext))
} catch (error) { } catch (error) {
callback({ callback({
success: false, success: false,
@ -290,7 +300,7 @@ io.on("connection", async (socket) => {
socket.on("deploy", async (callback: (response: DokkuResponse) => void) => { socket.on("deploy", async (callback: (response: DokkuResponse) => void) => {
try { try {
console.log("Deploying project ${data.sandboxId}...") console.log("Deploying project ${data.sandboxId}...")
callback(await handleDeploy(git, fileManager, data.sandboxId)) callback(await handleDeploy(data.sandboxId, handlerContext))
} catch (error) { } catch (error) {
callback({ callback({
success: false, success: false,
@ -302,7 +312,7 @@ io.on("connection", async (socket) => {
socket.on("createFile", async (name: string, callback) => { socket.on("createFile", async (name: string, callback) => {
try { try {
await createFileRL.consume(data.userId, 1) await createFileRL.consume(data.userId, 1)
callback({ success: await handleCreateFile(fileManager, name) }) callback({ success: await handleCreateFile(name, handlerContext) })
} catch (e: any) { } catch (e: any) {
console.error("Error creating file:", e) console.error("Error creating file:", e)
socket.emit("error", `Error: file creation. ${e.message ?? e}`) socket.emit("error", `Error: file creation. ${e.message ?? e}`)
@ -312,7 +322,7 @@ io.on("connection", async (socket) => {
socket.on("createFolder", async (name: string, callback) => { socket.on("createFolder", async (name: string, callback) => {
try { try {
await createFolderRL.consume(data.userId, 1) await createFolderRL.consume(data.userId, 1)
await handleCreateFolder(fileManager, name) await handleCreateFolder(name, handlerContext)
callback() callback()
} catch (e: any) { } catch (e: any) {
console.error("Error creating folder:", e) console.error("Error creating folder:", e)
@ -323,7 +333,7 @@ io.on("connection", async (socket) => {
socket.on("renameFile", async (fileId: string, newName: string) => { socket.on("renameFile", async (fileId: string, newName: string) => {
try { try {
await renameFileRL.consume(data.userId, 1) await renameFileRL.consume(data.userId, 1)
await handleRenameFile(fileManager, fileId, newName) await handleRenameFile(fileId, newName, handlerContext)
} catch (e: any) { } catch (e: any) {
console.error("Error renaming file:", e) console.error("Error renaming file:", e)
socket.emit("error", `Error: file renaming. ${e.message ?? e}`) socket.emit("error", `Error: file renaming. ${e.message ?? e}`)
@ -333,7 +343,7 @@ io.on("connection", async (socket) => {
socket.on("deleteFile", async (fileId: string, callback) => { socket.on("deleteFile", async (fileId: string, callback) => {
try { try {
await deleteFileRL.consume(data.userId, 1) await deleteFileRL.consume(data.userId, 1)
callback(await handleDeleteFile(fileManager, fileId)) callback(await handleDeleteFile(fileId, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error deleting file:", e) console.error("Error deleting file:", e)
socket.emit("error", `Error: file deletion. ${e.message ?? e}`) socket.emit("error", `Error: file deletion. ${e.message ?? e}`)
@ -342,7 +352,7 @@ io.on("connection", async (socket) => {
socket.on("deleteFolder", async (folderId: string, callback) => { socket.on("deleteFolder", async (folderId: string, callback) => {
try { try {
callback(await handleDeleteFolder(fileManager, folderId)) callback(await handleDeleteFolder(folderId, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error deleting folder:", e) console.error("Error deleting folder:", e)
socket.emit("error", `Error: folder deletion. ${e.message ?? e}`) socket.emit("error", `Error: folder deletion. ${e.message ?? e}`)
@ -351,7 +361,7 @@ io.on("connection", async (socket) => {
socket.on("createTerminal", async (id: string, callback) => { socket.on("createTerminal", async (id: string, callback) => {
try { try {
await handleCreateTerminal(lockManager, terminalManager, id, socket, containers, data) await handleCreateTerminal(id, socket, data, handlerContext)
callback() callback()
} catch (e: any) { } catch (e: any) {
console.error(`Error creating terminal ${id}:`, e) console.error(`Error creating terminal ${id}:`, e)
@ -361,7 +371,7 @@ io.on("connection", async (socket) => {
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => { socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
try { try {
handleResizeTerminal(terminalManager, dimensions) handleResizeTerminal(dimensions, handlerContext)
} catch (e: any) { } catch (e: any) {
console.error("Error resizing terminal:", e) console.error("Error resizing terminal:", e)
socket.emit("error", `Error: terminal resizing. ${e.message ?? e}`) socket.emit("error", `Error: terminal resizing. ${e.message ?? e}`)
@ -370,7 +380,7 @@ io.on("connection", async (socket) => {
socket.on("terminalData", async (id: string, data: string) => { socket.on("terminalData", async (id: string, data: string) => {
try { try {
await handleTerminalData(terminalManager, id, data) await handleTerminalData(id, data, handlerContext)
} catch (e: any) { } catch (e: any) {
console.error("Error writing to terminal:", e) console.error("Error writing to terminal:", e)
socket.emit("error", `Error: writing to terminal. ${e.message ?? e}`) socket.emit("error", `Error: writing to terminal. ${e.message ?? e}`)
@ -379,7 +389,7 @@ io.on("connection", async (socket) => {
socket.on("closeTerminal", async (id: string, callback) => { socket.on("closeTerminal", async (id: string, callback) => {
try { try {
await handleCloseTerminal(terminalManager, id) await handleCloseTerminal(id, handlerContext)
callback() callback()
} catch (e: any) { } catch (e: any) {
console.error("Error closing terminal:", e) console.error("Error closing terminal:", e)
@ -389,7 +399,7 @@ io.on("connection", async (socket) => {
socket.on("generateCode", async (fileName: string, code: string, line: number, instructions: string, callback) => { socket.on("generateCode", async (fileName: string, code: string, line: number, instructions: string, callback) => {
try { try {
callback(await handleGenerateCode(aiWorker, data.userId, fileName, code, line, instructions)) callback(await handleGenerateCode(data.userId, fileName, code, line, instructions, handlerContext))
} catch (e: any) { } catch (e: any) {
console.error("Error generating code:", e) console.error("Error generating code:", e)
socket.emit("error", `Error: code generation. ${e.message ?? e}`) socket.emit("error", `Error: code generation. ${e.message ?? e}`)