183 lines
5.7 KiB
TypeScript
Raw Normal View History

2024-10-19 05:25:26 -06:00
import cors from "cors"
import dotenv from "dotenv"
import express, { Express } from "express"
import fs from "fs"
import { createServer } from "http"
import { Server, Socket } from "socket.io"
2024-10-19 15:43:18 -06:00
import { AIWorker } from "./AIWorker"
import { ConnectionManager } from "./ConnectionManager"
import { DokkuClient } from "./DokkuClient"
2024-10-25 07:36:43 -06:00
import { Sandbox } from "./SandboxManager"
import { SecureGitClient } from "./SecureGitClient"
import { socketAuth } from "./socketAuth"; // Import the new socketAuth middleware
import { TFile, TFolder } from "./types"
2024-04-18 16:40:08 -04:00
2024-10-25 07:06:07 -06:00
// Log errors and send a notification to the client
export const handleErrors = (message: string, error: any, socket: Socket) => {
2024-10-25 07:06:07 -06:00
console.error(message, error);
socket.emit("error", `${message} ${error.message ?? error}`);
};
2024-10-19 15:16:24 -06:00
// Handle uncaught exceptions
2024-10-19 05:25:26 -06:00
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error)
// Do not exit the process
2024-10-19 05:25:26 -06:00
})
2024-10-19 15:16:24 -06:00
// Handle unhandled promise rejections
2024-10-19 05:25:26 -06:00
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection at:", promise, "reason:", reason)
// Do not exit the process
2024-10-19 05:25:26 -06:00
})
// Initialize containers and managers
2024-10-25 07:36:43 -06:00
const connections = new ConnectionManager()
const sandboxes: Record<string, Sandbox> = {}
2024-10-19 15:16:24 -06:00
// Load environment variables
2024-10-19 05:25:26 -06:00
dotenv.config()
2024-04-18 16:40:08 -04:00
2024-10-19 15:16:24 -06:00
// Initialize Express app and create HTTP server
2024-10-19 05:25:26 -06:00
const app: Express = express()
const port = process.env.PORT || 4000
app.use(cors())
const httpServer = createServer(app)
2024-04-18 16:40:08 -04:00
const io = new Server(httpServer, {
cors: {
2024-10-25 07:30:35 -06:00
origin: "*", // Allow connections from any origin
2024-04-18 16:40:08 -04:00
},
2024-10-19 05:25:26 -06:00
})
2024-04-18 16:40:08 -04:00
2024-10-19 15:16:24 -06:00
// Middleware for socket authentication
io.use(socketAuth) // Use the new socketAuth middleware
2024-04-18 16:40:08 -04:00
2024-10-19 15:16:24 -06:00
// Check for required environment variables
2024-10-19 05:25:26 -06:00
if (!process.env.DOKKU_HOST)
2024-10-24 17:38:43 -06:00
console.warn("Environment variable DOKKU_HOST is not defined")
2024-10-19 05:25:26 -06:00
if (!process.env.DOKKU_USERNAME)
2024-10-24 17:38:43 -06:00
console.warn("Environment variable DOKKU_USERNAME is not defined")
2024-10-19 05:25:26 -06:00
if (!process.env.DOKKU_KEY)
2024-10-24 17:38:43 -06:00
console.warn("Environment variable DOKKU_KEY is not defined")
2024-10-19 15:16:24 -06:00
// Initialize Dokku client
const dokkuClient =
process.env.DOKKU_HOST && process.env.DOKKU_KEY && process.env.DOKKU_USERNAME
? new DokkuClient({
host: process.env.DOKKU_HOST,
username: process.env.DOKKU_USERNAME,
privateKey: fs.readFileSync(process.env.DOKKU_KEY),
})
2024-10-19 05:25:26 -06:00
: null
dokkuClient?.connect()
2024-10-19 15:16:24 -06:00
// Initialize Git client used to deploy Dokku apps
const gitClient =
2024-10-19 05:25:26 -06:00
process.env.DOKKU_HOST && process.env.DOKKU_KEY
? new SecureGitClient(
`dokku@${process.env.DOKKU_HOST}`,
process.env.DOKKU_KEY
)
2024-10-19 05:25:26 -06:00
: null
2024-10-19 15:43:18 -06:00
// Add this near the top of the file, after other initializations
const aiWorker = new AIWorker(
process.env.AI_WORKER_URL!,
process.env.CF_AI_KEY!,
process.env.DATABASE_WORKER_URL!,
process.env.WORKERS_KEY!
)
// Handle a client connecting to the server
2024-04-18 16:40:08 -04:00
io.on("connection", async (socket) => {
try {
// This data comes is added by our authentication middleware
const data = socket.data as {
2024-10-19 05:25:26 -06:00
userId: string
sandboxId: string
isOwner: boolean
}
2024-04-21 22:55:49 -04:00
2024-10-25 07:30:35 -06:00
// Disable access unless the sandbox owner is connected
if (data.isOwner) {
2024-10-25 07:36:43 -06:00
connections.ownerConnected(data.sandboxId)
} else {
2024-10-25 07:36:43 -06:00
if (!connections.ownerIsConnected(data.sandboxId)) {
2024-10-19 05:25:26 -06:00
socket.emit("disableAccess", "The sandbox owner is not connected.")
return
}
}
connections.addConnectionForSandbox(socket, data.sandboxId)
try {
2024-10-25 07:30:35 -06:00
// Create or retrieve the sandbox manager for the given sandbox ID
2024-10-25 07:36:43 -06:00
const sandboxManager = sandboxes[data.sandboxId] ?? new Sandbox(
2024-10-25 06:40:47 -06:00
data.sandboxId,
{
aiWorker, dokkuClient, gitClient,
}
2024-10-25 06:40:47 -06:00
)
sandboxes[data.sandboxId] = sandboxManager
const sendFileNotifications = (files: (TFolder | TFile)[]) => {
connections.connectionsForSandbox(data.sandboxId).forEach((socket: Socket) => {
socket.emit("loaded", files);
});
};
2024-10-25 06:40:47 -06:00
2024-10-25 07:30:35 -06:00
// Initialize the sandbox container
// The file manager and terminal managers will be set up if they have been closed
await sandboxManager.initialize(sendFileNotifications)
socket.emit("loaded", sandboxManager.fileManager?.files)
2024-04-27 19:12:25 -04:00
2024-10-25 07:30:35 -06:00
// Register event handlers for the sandbox
Object.entries(sandboxManager.handlers({
userId: data.userId,
isOwner: data.isOwner,
socket
})).forEach(([event, handler]) => {
2024-10-25 06:40:47 -06:00
socket.on(event, async (options: any, callback?: (response: any) => void) => {
try {
2024-10-25 19:02:18 -06:00
const result = await handler(options)
callback?.(result);
2024-10-25 06:40:47 -06:00
} catch (e: any) {
2024-10-25 07:06:07 -06:00
handleErrors(`Error processing event "${event}":`, e, socket);
2024-10-25 06:40:47 -06:00
}
});
});
2024-05-06 23:34:45 -07:00
2024-10-25 07:30:35 -06:00
// Handle disconnection event
2024-10-25 06:40:47 -06:00
socket.on("disconnect", async () => {
try {
connections.removeConnectionForSandbox(socket, data.sandboxId)
2024-10-25 06:40:47 -06:00
if (data.isOwner) {
2024-10-25 07:36:43 -06:00
connections.ownerDisconnected(data.sandboxId)
// If the owner has disconnected from all sockets, close open terminals and file watchers.o
// The sandbox itself will timeout after the heartbeat stops.
if (!connections.ownerIsConnected(data.sandboxId)) {
await sandboxManager.disconnect()
socket.broadcast.emit(
"disableAccess",
"The sandbox owner has disconnected."
)
}
2024-10-25 06:40:47 -06:00
}
} catch (e: any) {
2024-10-25 07:06:07 -06:00
handleErrors("Error disconnecting:", e, socket);
}
2024-10-25 06:40:47 -06:00
})
2024-10-25 06:40:47 -06:00
} catch (e: any) {
2024-10-25 07:06:07 -06:00
handleErrors(`Error initializing sandbox ${data.sandboxId}:`, e, socket);
2024-10-25 06:40:47 -06:00
}
} catch (e: any) {
2024-10-25 07:06:07 -06:00
handleErrors("Error connecting:", e, socket);
}
2024-10-19 05:25:26 -06:00
})
2024-04-18 16:40:08 -04:00
2024-10-19 15:16:24 -06:00
// Start the server
2024-04-18 16:40:08 -04:00
httpServer.listen(port, () => {
2024-10-19 05:25:26 -06:00
console.log(`Server running on port ${port}`)
})