fix: add error handling to the backend
This commit is contained in:
parent
ed709210e3
commit
c262fb2a31
@ -49,11 +49,15 @@ const terminals: Record<string, Terminal> = {};
|
||||
|
||||
const dirName = "/home/user";
|
||||
|
||||
const moveFile = async (filesystem: FilesystemManager, filePath: string, newFilePath: string) => {
|
||||
const fileContents = await filesystem.readBytes(filePath)
|
||||
const moveFile = async (
|
||||
filesystem: FilesystemManager,
|
||||
filePath: string,
|
||||
newFilePath: string
|
||||
) => {
|
||||
const fileContents = await filesystem.readBytes(filePath);
|
||||
await filesystem.writeBytes(newFilePath, fileContents);
|
||||
await filesystem.remove(filePath);
|
||||
}
|
||||
};
|
||||
|
||||
io.use(async (socket, next) => {
|
||||
const handshakeSchema = z.object({
|
||||
@ -109,6 +113,7 @@ io.use(async (socket, next) => {
|
||||
const lockManager = new LockManager();
|
||||
|
||||
io.on("connection", async (socket) => {
|
||||
try {
|
||||
if (inactivityTimeout) clearTimeout(inactivityTimeout);
|
||||
|
||||
const data = socket.data as {
|
||||
@ -132,10 +137,14 @@ io.on("connection", async (socket) => {
|
||||
if (!containers[data.sandboxId]) {
|
||||
containers[data.sandboxId] = await Sandbox.create();
|
||||
console.log("Created container ", data.sandboxId);
|
||||
io.emit("previewURL", "https://" + containers[data.sandboxId].getHostname(5173));
|
||||
io.emit(
|
||||
"previewURL",
|
||||
"https://" + containers[data.sandboxId].getHostname(5173)
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating container ", data.sandboxId, error);
|
||||
} catch (e: any) {
|
||||
console.error(`Error creating container ${data.sandboxId}:`, e);
|
||||
io.emit("error", `Error: container creation. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
@ -144,12 +153,14 @@ io.on("connection", async (socket) => {
|
||||
await containers[data.sandboxId].process.startAndWait(
|
||||
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
||||
sandboxFiles.fileData.forEach(async (file) => {
|
||||
const filePath = path.join(dirName, file.id);
|
||||
await containers[data.sandboxId].filesystem.makeDir(path.dirname(filePath));
|
||||
await containers[data.sandboxId].filesystem.makeDir(
|
||||
path.dirname(filePath)
|
||||
);
|
||||
await containers[data.sandboxId].filesystem.write(filePath, file.data);
|
||||
});
|
||||
fixPermissions();
|
||||
@ -157,43 +168,65 @@ io.on("connection", async (socket) => {
|
||||
socket.emit("loaded", sandboxFiles.files);
|
||||
|
||||
socket.on("getFile", (fileId: string, callback) => {
|
||||
console.log(fileId);
|
||||
try {
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
|
||||
callback(file.data);
|
||||
} catch (e: any) {
|
||||
console.error("Error getting file:", e);
|
||||
io.emit("error", `Error: get file. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("getFolder", async (folderId: string, callback) => {
|
||||
try {
|
||||
const files = await getFolder(folderId);
|
||||
callback(files);
|
||||
} catch (e: any) {
|
||||
console.error("Error getting folder:", e);
|
||||
io.emit("error", `Error: get folder. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
// todo: send diffs + debounce for efficiency
|
||||
socket.on("saveFile", async (fileId: string, body: string) => {
|
||||
try {
|
||||
await saveFileRL.consume(data.userId, 1);
|
||||
|
||||
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
||||
socket.emit(
|
||||
"rateLimit",
|
||||
"Rate limited: file size too large. Please reduce the file size."
|
||||
"error",
|
||||
"Error: file size too large. Please reduce the file size."
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await saveFileRL.consume(data.userId, 1);
|
||||
await saveFile(fileId, body);
|
||||
} catch (e) {
|
||||
io.emit("error", "Rate limited: file saving. Please slow down.");
|
||||
return;
|
||||
}
|
||||
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
file.data = body;
|
||||
|
||||
await containers[data.sandboxId].filesystem.write(path.join(dirName, file.id), body);
|
||||
await containers[data.sandboxId].filesystem.write(
|
||||
path.join(dirName, file.id),
|
||||
body
|
||||
);
|
||||
fixPermissions();
|
||||
await saveFile(fileId, body);
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
|
||||
} catch (e: any) {
|
||||
console.error("Error saving file:", e);
|
||||
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("moveFile", async (fileId: string, folderId: string, callback) => {
|
||||
socket.on(
|
||||
"moveFile",
|
||||
async (fileId: string, folderId: string, callback) => {
|
||||
try {
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
|
||||
@ -204,16 +237,20 @@ io.on("connection", async (socket) => {
|
||||
containers[data.sandboxId].filesystem,
|
||||
path.join(dirName, fileId),
|
||||
path.join(dirName, newFileId)
|
||||
)
|
||||
);
|
||||
fixPermissions();
|
||||
|
||||
file.id = newFileId;
|
||||
|
||||
await renameFile(fileId, newFileId, file.data);
|
||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||
|
||||
callback(newFiles.files);
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error("Error moving file:", e);
|
||||
io.emit("error", `Error: file moving. ${e.message ?? e}`);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
socket.on("createFile", async (name: string, callback) => {
|
||||
try {
|
||||
@ -221,17 +258,26 @@ io.on("connection", async (socket) => {
|
||||
// limit is 200mb
|
||||
if (size > 200 * 1024 * 1024) {
|
||||
io.emit(
|
||||
"rateLimit",
|
||||
"error",
|
||||
"Rate limited: project size exceeded. Please delete some files."
|
||||
);
|
||||
callback({ success: false });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await createFileRL.consume(data.userId, 1);
|
||||
} catch (e) {
|
||||
io.emit("error", "Rate limited: file creation. Please slow down.");
|
||||
return;
|
||||
}
|
||||
|
||||
const id = `projects/${data.sandboxId}/${name}`;
|
||||
|
||||
await containers[data.sandboxId].filesystem.write(path.join(dirName, id), "");
|
||||
await containers[data.sandboxId].filesystem.write(
|
||||
path.join(dirName, id),
|
||||
""
|
||||
);
|
||||
fixPermissions();
|
||||
|
||||
sandboxFiles.files.push({
|
||||
@ -248,28 +294,42 @@ io.on("connection", async (socket) => {
|
||||
await createFile(id);
|
||||
|
||||
callback({ success: true });
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file creation. Please slow down.");
|
||||
} catch (e: any) {
|
||||
console.error("Error creating file:", e);
|
||||
io.emit("error", `Error: file creation. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("createFolder", async (name: string, callback) => {
|
||||
try {
|
||||
try {
|
||||
await createFolderRL.consume(data.userId, 1);
|
||||
} catch (e) {
|
||||
io.emit("error", "Rate limited: folder creation. Please slow down.");
|
||||
return;
|
||||
}
|
||||
|
||||
const id = `projects/${data.sandboxId}/${name}`;
|
||||
|
||||
await containers[data.sandboxId].filesystem.makeDir(path.join(dirName, id));
|
||||
await containers[data.sandboxId].filesystem.makeDir(
|
||||
path.join(dirName, id)
|
||||
);
|
||||
|
||||
callback();
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: folder creation. Please slow down.");
|
||||
} catch (e: any) {
|
||||
console.error("Error creating folder:", e);
|
||||
io.emit("error", `Error: folder creation. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("renameFile", async (fileId: string, newName: string) => {
|
||||
try {
|
||||
try {
|
||||
await renameFileRL.consume(data.userId, 1);
|
||||
} catch (e) {
|
||||
io.emit("error", "Rate limited: file renaming. Please slow down.");
|
||||
return;
|
||||
}
|
||||
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
@ -279,27 +339,33 @@ io.on("connection", async (socket) => {
|
||||
const newFileId =
|
||||
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
||||
|
||||
|
||||
await moveFile(
|
||||
containers[data.sandboxId].filesystem,
|
||||
path.join(dirName, fileId),
|
||||
path.join(dirName, newFileId)
|
||||
)
|
||||
);
|
||||
fixPermissions();
|
||||
await renameFile(fileId, newFileId, file.data);
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
|
||||
return;
|
||||
} catch (e: any) {
|
||||
console.error("Error renaming folder:", e);
|
||||
io.emit("error", `Error: folder renaming. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("deleteFile", async (fileId: string, callback) => {
|
||||
try {
|
||||
try {
|
||||
await deleteFileRL.consume(data.userId, 1);
|
||||
} catch (e) {
|
||||
io.emit("error", "Rate limited: file deletion. Please slow down.");
|
||||
}
|
||||
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
|
||||
await containers[data.sandboxId].filesystem.remove(path.join(dirName, fileId));
|
||||
await containers[data.sandboxId].filesystem.remove(
|
||||
path.join(dirName, fileId)
|
||||
);
|
||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||
(f) => f.id !== fileId
|
||||
);
|
||||
@ -308,8 +374,9 @@ io.on("connection", async (socket) => {
|
||||
|
||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||
callback(newFiles.files);
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file deletion. Please slow down.");
|
||||
} catch (e: any) {
|
||||
console.error("Error deleting file:", e);
|
||||
io.emit("error", `Error: file deletion. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
@ -318,11 +385,14 @@ io.on("connection", async (socket) => {
|
||||
// });
|
||||
|
||||
socket.on("deleteFolder", async (folderId: string, callback) => {
|
||||
try {
|
||||
const files = await getFolder(folderId);
|
||||
|
||||
await Promise.all(
|
||||
files.map(async (file) => {
|
||||
await containers[data.sandboxId].filesystem.remove(path.join(dirName, file));
|
||||
await containers[data.sandboxId].filesystem.remove(
|
||||
path.join(dirName, file)
|
||||
);
|
||||
|
||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||
(f) => f.id !== file
|
||||
@ -335,9 +405,14 @@ io.on("connection", async (socket) => {
|
||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||
|
||||
callback(newFiles.files);
|
||||
} catch (e: any) {
|
||||
console.error("Error deleting folder:", e);
|
||||
io.emit("error", `Error: folder deletion. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("createTerminal", async (id: string, callback) => {
|
||||
try {
|
||||
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
||||
return;
|
||||
}
|
||||
@ -351,36 +426,53 @@ io.on("connection", async (socket) => {
|
||||
size: { cols: 80, rows: 20 },
|
||||
onExit: () => console.log("Terminal exited", id),
|
||||
});
|
||||
await terminals[id].sendData(`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`)
|
||||
await terminals[id].sendData(
|
||||
`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`
|
||||
);
|
||||
await terminals[id].sendData("export PS1='user> '\rclear\r");
|
||||
console.log("Created terminal", id);
|
||||
} catch (error) {
|
||||
console.error("Error creating terminal ", id, error);
|
||||
} catch (e: any) {
|
||||
console.error(`Error creating terminal ${id}:`, e);
|
||||
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
callback();
|
||||
} catch (e: any) {
|
||||
console.error(`Error creating terminal ${id}:`, e);
|
||||
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
|
||||
socket.on(
|
||||
"resizeTerminal",
|
||||
(dimensions: { cols: number; rows: number }) => {
|
||||
try {
|
||||
Object.values(terminals).forEach((t) => {
|
||||
t.resize(dimensions);
|
||||
});
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error("Error resizing terminal:", e);
|
||||
io.emit("error", `Error: terminal resizing. ${e.message ?? e}`);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
socket.on("terminalData", (id: string, data: string) => {
|
||||
try {
|
||||
if (!terminals[id]) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
terminals[id].sendData(data);
|
||||
} catch (e) {
|
||||
console.log("Error writing to terminal", e);
|
||||
} catch (e: any) {
|
||||
console.error("Error writing to terminal:", e);
|
||||
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("closeTerminal", async (id: string, callback) => {
|
||||
try {
|
||||
if (!terminals[id]) {
|
||||
return;
|
||||
}
|
||||
@ -389,6 +481,10 @@ io.on("connection", async (socket) => {
|
||||
delete terminals[id];
|
||||
|
||||
callback();
|
||||
} catch (e: any) {
|
||||
console.error("Error closing terminal:", e);
|
||||
io.emit("error", `Error: closing terminal. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on(
|
||||
@ -400,6 +496,7 @@ io.on("connection", async (socket) => {
|
||||
instructions: string,
|
||||
callback
|
||||
) => {
|
||||
try {
|
||||
const fetchPromise = fetch(
|
||||
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
|
||||
{
|
||||
@ -433,10 +530,15 @@ io.on("connection", async (socket) => {
|
||||
const json = await generateCodeResponse.json();
|
||||
|
||||
callback({ response: json.response, success: true });
|
||||
} catch (e: any) {
|
||||
console.error("Error generating code:", e);
|
||||
io.emit("error", `Error: code generation. ${e.message ?? e}`);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
socket.on("disconnect", async () => {
|
||||
try {
|
||||
if (data.isOwner) {
|
||||
connections[data.sandboxId]--;
|
||||
}
|
||||
@ -483,7 +585,15 @@ io.on("connection", async (socket) => {
|
||||
// } else {
|
||||
// console.log("number of sockets", sockets.length);
|
||||
// }
|
||||
} catch (e: any) {
|
||||
console.log("Error disconnecting:", e);
|
||||
io.emit("error", `Error: disconnecting. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error("Error connecting:", e);
|
||||
io.emit("error", `Error: connection. ${e.message ?? e}`);
|
||||
}
|
||||
});
|
||||
|
||||
httpServer.listen(port, () => {
|
||||
|
@ -391,7 +391,7 @@ export default function CodeEditor({
|
||||
setFiles(files)
|
||||
}
|
||||
|
||||
const onRateLimit = (message: string) => {
|
||||
const onError = (message: string) => {
|
||||
toast.error(message)
|
||||
}
|
||||
|
||||
@ -413,7 +413,7 @@ export default function CodeEditor({
|
||||
socketRef.current?.on("connect", onConnect)
|
||||
socketRef.current?.on("disconnect", onDisconnect)
|
||||
socketRef.current?.on("loaded", onLoadedEvent)
|
||||
socketRef.current?.on("rateLimit", onRateLimit)
|
||||
socketRef.current?.on("error", onError)
|
||||
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
||||
socketRef.current?.on("disableAccess", onDisableAccess)
|
||||
socketRef.current?.on("previewURL", setPreviewURL)
|
||||
@ -422,7 +422,7 @@ export default function CodeEditor({
|
||||
socketRef.current?.off("connect", onConnect)
|
||||
socketRef.current?.off("disconnect", onDisconnect)
|
||||
socketRef.current?.off("loaded", onLoadedEvent)
|
||||
socketRef.current?.off("rateLimit", onRateLimit)
|
||||
socketRef.current?.off("error", onError)
|
||||
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
||||
socketRef.current?.off("disableAccess", onDisableAccess)
|
||||
socketRef.current?.off("previewURL", setPreviewURL)
|
||||
|
Loading…
x
Reference in New Issue
Block a user