feat: add sandbox

This commit is contained in:
2024-02-26 10:48:17 +00:00
parent 5b68230734
commit 85e71c2983
19 changed files with 588 additions and 19 deletions
+66
View File
@@ -0,0 +1,66 @@
import fetch, { RequestInit } from "node-fetch";
const createRequest = async (
url: string,
options?: RequestInit & { ignoreError?: boolean }
) => {
const reqUrl = "http://127.0.0.1:8000" + url;
const response = await fetch(reqUrl, options);
if (!response.ok && !options?.ignoreError) {
const err: any = Error(response.statusText);
err.code = response.status;
throw err;
}
return response;
};
const start = async (id: string, path: string) => {
return createRequest("/start", {
body: JSON.stringify({ path, id }),
method: "POST",
ignoreError: true,
});
};
const stop = async (id: string) => {
const res = await createRequest(`/stop/${id}`, { method: "POST" });
return res.json();
};
const restart = async (id: string) => {
return createRequest(`/restart/${id}`, { method: "POST", ignoreError: true });
};
const getStats = async (id: string) => {
const res = await createRequest(`/stats/${id}`);
return res.json();
};
const getLogs = async (id: string) => {
return createRequest(`/logs/${id}`);
};
type ProxyOptions = {
pathname: string;
headers: Headers;
};
const proxy = async (id: string, opt: ProxyOptions) => {
return createRequest(`/proxy/${id}` + opt.pathname, {
headers: opt.headers,
ignoreError: true,
});
};
const sandbox = {
start,
stop,
restart,
getStats,
getLogs,
proxy,
};
export default sandbox;
+3 -1
View File
@@ -5,12 +5,14 @@ import db from "../db";
import { file } from "../db/schema/file";
import { fileExists, getProjectDir } from "./utils";
import { getFileExt } from "~/lib/utils";
import { ProjectSchema } from "../db/schema/project";
type UnpackProjectOptions = {
ext: string;
};
export const unpackProject = async (
projectData: ProjectSchema,
opt: Partial<UnpackProjectOptions> = {}
) => {
const files = await db.query.file.findMany({
@@ -21,7 +23,7 @@ export const unpackProject = async (
),
});
const projectDir = getProjectDir();
const projectDir = getProjectDir(projectData);
if (!fileExists(projectDir)) {
await fs.mkdir(projectDir, { recursive: true });
}
+3 -2
View File
@@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import cuid2 from "@paralleldrive/cuid2";
import { ProjectSchema } from "../db/schema/project";
export const fileExists = (path: string) => {
try {
@@ -11,8 +12,8 @@ export const fileExists = (path: string) => {
}
};
export const getProjectDir = () => {
return path.resolve(process.cwd(), "storage/tmp/project1");
export const getProjectDir = (project: ProjectSchema) => {
return path.resolve(process.cwd(), "storage/tmp", project.slug);
};
export const uid = cuid2.init({