| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1 | import { PrismaClient } from "@prisma/client"; |
| 2 | import express from "express"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 3 | import fs from "node:fs"; |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 4 | import { env } from "node:process"; |
| 5 | import axios from "axios"; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 6 | import { GithubClient } from "./github.js"; |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 7 | import { AppManager, DeployResponse } from "./app_manager.js"; |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 8 | import { z } from "zod"; |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 9 | import { ProjectMonitor, WorkerSchema, LogItem } from "./project_monitor.js"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 10 | import tmp from "tmp"; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 11 | import { NodeJSAnalyzer } from "./lib/nodejs.js"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 12 | import shell from "shelljs"; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 13 | import { RealFileSystem } from "./lib/fs.js"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 14 | import path from "node:path"; |
| gio | 9b7421a | 2025-06-18 12:31:13 +0000 | [diff] [blame] | 15 | import { |
| 16 | Env, |
| 17 | generateDodoConfig, |
| 18 | ConfigSchema, |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 19 | Config, |
| gio | 9b7421a | 2025-06-18 12:31:13 +0000 | [diff] [blame] | 20 | ConfigWithInput, |
| 21 | configToGraph, |
| 22 | Network, |
| 23 | GithubRepository, |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 24 | Graph, |
| gio | 9b7421a | 2025-06-18 12:31:13 +0000 | [diff] [blame] | 25 | } from "config"; |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 26 | import { Instant, DateTimeFormatter, ZoneId } from "@js-joda/core"; |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 27 | import LogStore from "./log.js"; |
| gio | 785c988 | 2025-07-07 16:40:25 +0000 | [diff] [blame] | 28 | import { GraphOrConfigSchema, GraphSchema, GraphConfigOrDraft, AgentAccess } from "config/dist/graph.js"; |
| gio | 43e0aad | 2025-08-01 16:17:27 +0400 | [diff] [blame] | 29 | import { MachineManager } from "./machine_manager.js"; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 30 | |
| 31 | async function generateKey(root: string): Promise<[string, string]> { |
| 32 | const privKeyPath = path.join(root, "key"); |
| 33 | const pubKeyPath = path.join(root, "key.pub"); |
| 34 | if (shell.exec(`ssh-keygen -t ed25519 -f ${privKeyPath} -N ""`).code !== 0) { |
| 35 | throw new Error("Failed to generate SSH key pair"); |
| 36 | } |
| 37 | const publicKey = await fs.promises.readFile(pubKeyPath, "utf8"); |
| 38 | const privateKey = await fs.promises.readFile(privKeyPath, "utf8"); |
| 39 | return [publicKey, privateKey]; |
| 40 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 41 | |
| 42 | const db = new PrismaClient(); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 43 | const logStore = new LogStore(db); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 44 | const appManager = new AppManager(); |
| gio | 43e0aad | 2025-08-01 16:17:27 +0400 | [diff] [blame] | 45 | const machineManager = new MachineManager(env.VPN_API_ADDR!); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 46 | |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 47 | const projectMonitors = new Map<number, ProjectMonitor>(); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 48 | |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 49 | function parseGraph(data: string | null | undefined) { |
| 50 | if (data == null) { |
| 51 | return null; |
| 52 | } |
| 53 | return GraphSchema.safeParse(JSON.parse(data)); |
| 54 | } |
| 55 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 56 | const handleProjectCreate: express.Handler = async (req, resp) => { |
| 57 | try { |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 58 | const tmpDir = tmp.dirSync().name; |
| 59 | const [publicKey, privateKey] = await generateKey(tmpDir); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 60 | const { id } = await db.project.create({ |
| 61 | data: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 62 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 63 | name: req.body.name, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 64 | deployKey: privateKey, |
| 65 | deployKeyPublic: publicKey, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 66 | }, |
| 67 | }); |
| 68 | resp.status(200); |
| 69 | resp.header("Content-Type", "application/json"); |
| 70 | resp.write( |
| 71 | JSON.stringify({ |
| gio | 74ab785 | 2025-05-13 13:19:31 +0000 | [diff] [blame] | 72 | id: id.toString(), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 73 | }), |
| 74 | ); |
| 75 | } catch (e) { |
| 76 | console.log(e); |
| 77 | resp.status(500); |
| 78 | } finally { |
| 79 | resp.end(); |
| 80 | } |
| 81 | }; |
| 82 | |
| 83 | const handleProjectAll: express.Handler = async (req, resp) => { |
| 84 | try { |
| 85 | const r = await db.project.findMany({ |
| 86 | where: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 87 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 88 | }, |
| 89 | }); |
| 90 | resp.status(200); |
| 91 | resp.header("Content-Type", "application/json"); |
| 92 | resp.write( |
| 93 | JSON.stringify( |
| 94 | r.map((p) => ({ |
| 95 | id: p.id.toString(), |
| 96 | name: p.name, |
| 97 | })), |
| 98 | ), |
| 99 | ); |
| 100 | } catch (e) { |
| 101 | console.log(e); |
| 102 | resp.status(500); |
| 103 | } finally { |
| 104 | resp.end(); |
| 105 | } |
| 106 | }; |
| 107 | |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 108 | async function getState(projectId: number, userId: string, state: "deploy" | "draft"): Promise<Graph | null> { |
| 109 | const r = await db.project.findUnique({ |
| 110 | where: { |
| 111 | id: projectId, |
| 112 | userId: userId, |
| 113 | }, |
| 114 | select: { |
| 115 | state: true, |
| 116 | draft: true, |
| 117 | }, |
| 118 | }); |
| 119 | if (r == null) { |
| 120 | return null; |
| 121 | } |
| 122 | let currentState: Graph | null = null; |
| 123 | if (state === "deploy") { |
| 124 | if (r.state != null) { |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 125 | currentState = parseGraph(r.state)!.data!; |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 126 | } |
| 127 | } else { |
| 128 | if (r.draft == null) { |
| 129 | if (r.state == null) { |
| 130 | currentState = { |
| 131 | nodes: [], |
| 132 | edges: [], |
| 133 | viewport: { x: 0, y: 0, zoom: 1 }, |
| 134 | }; |
| 135 | } else { |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 136 | currentState = parseGraph(r.state)!.data!; |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 137 | } |
| 138 | } else { |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 139 | currentState = parseGraph(r.draft)!.data!; |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 140 | } |
| 141 | } |
| 142 | return currentState; |
| 143 | } |
| 144 | |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 145 | function handleSavedGet(state: "deploy" | "draft"): express.Handler { |
| 146 | return async (req, resp) => { |
| 147 | try { |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 148 | const projectId = Number(req.params["projectId"]); |
| 149 | const graph = await getState(projectId, resp.locals.userId, state); |
| 150 | if (graph == null) { |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 151 | resp.status(404); |
| 152 | return; |
| 153 | } |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 154 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 155 | const config = generateDodoConfig(projectId.toString(), graph.nodes, env); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 156 | resp.status(200); |
| 157 | resp.header("content-type", "application/json"); |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 158 | resp.write( |
| 159 | JSON.stringify({ |
| 160 | state: graph, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 161 | config, |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 162 | }), |
| 163 | ); |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 164 | } catch (e) { |
| 165 | console.log(e); |
| 166 | resp.status(500); |
| 167 | } finally { |
| 168 | resp.end(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 169 | } |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 170 | }; |
| 171 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 172 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 173 | const handleProjectDelete: express.Handler = async (req, resp) => { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 174 | try { |
| 175 | const projectId = Number(req.params["projectId"]); |
| 176 | const p = await db.project.findUnique({ |
| 177 | where: { |
| 178 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 179 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 180 | }, |
| 181 | select: { |
| 182 | instanceId: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 183 | githubToken: true, |
| 184 | deployKeyPublic: true, |
| 185 | state: true, |
| 186 | draft: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 187 | }, |
| 188 | }); |
| 189 | if (p === null) { |
| 190 | resp.status(404); |
| 191 | return; |
| 192 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 193 | if (p.githubToken && p.deployKeyPublic) { |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 194 | const allRepos = [...new Set([...extractGithubRepos(p.state), ...extractGithubRepos(p.draft)])]; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 195 | if (allRepos.length > 0) { |
| 196 | const diff: RepoDiff = { toDelete: allRepos, toAdd: [] }; |
| 197 | const github = new GithubClient(p.githubToken); |
| 198 | await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR); |
| 199 | console.log( |
| 200 | `Attempted to remove deploy keys for project ${projectId} from associated GitHub repositories.`, |
| 201 | ); |
| 202 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 203 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 204 | if (p.instanceId !== null) { |
| 205 | if (!(await appManager.removeInstance(p.instanceId))) { |
| 206 | resp.status(500); |
| 207 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 208 | return; |
| 209 | } |
| 210 | } |
| 211 | await db.project.delete({ |
| 212 | where: { |
| 213 | id: projectId, |
| 214 | }, |
| 215 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 216 | resp.status(200); |
| 217 | } catch (e) { |
| 218 | console.log(e); |
| 219 | resp.status(500); |
| 220 | } finally { |
| 221 | resp.end(); |
| 222 | } |
| 223 | }; |
| 224 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 225 | function extractGithubRepos(serializedState: string | null | undefined): string[] { |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 226 | if (!serializedState) { |
| 227 | return []; |
| 228 | } |
| 229 | try { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 230 | const stateObj = JSON.parse(serializedState); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 231 | const githubNodes = stateObj.nodes.filter( |
| 232 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 233 | (n: any) => n.type === "github" && n.data?.repository?.id, |
| 234 | ); |
| 235 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 236 | return githubNodes.map((n: any) => n.data.repository.sshURL); |
| 237 | } catch (error) { |
| 238 | console.error("Failed to parse state or extract GitHub repos:", error); |
| 239 | return []; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | type RepoDiff = { |
| 244 | toAdd?: string[]; |
| 245 | toDelete?: string[]; |
| 246 | }; |
| 247 | |
| 248 | function calculateRepoDiff(oldRepos: string[], newRepos: string[]): RepoDiff { |
| 249 | const toAdd = newRepos.filter((repo) => !oldRepos.includes(repo)); |
| 250 | const toDelete = oldRepos.filter((repo) => !newRepos.includes(repo)); |
| 251 | return { toAdd, toDelete }; |
| 252 | } |
| 253 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 254 | async function manageGithubRepos( |
| 255 | github: GithubClient, |
| 256 | diff: RepoDiff, |
| 257 | deployKey: string, |
| 258 | publicAddr?: string, |
| 259 | ): Promise<void> { |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 260 | for (const repoUrl of diff.toDelete ?? []) { |
| 261 | try { |
| 262 | await github.removeDeployKey(repoUrl, deployKey); |
| 263 | console.log(`Removed deploy key from repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 264 | if (publicAddr) { |
| 265 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 266 | await github.removePushWebhook(repoUrl, webhookCallbackUrl); |
| 267 | console.log(`Removed push webhook from repository ${repoUrl}`); |
| 268 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 269 | } catch (error) { |
| 270 | console.error(`Failed to remove deploy key from repository ${repoUrl}:`, error); |
| 271 | } |
| 272 | } |
| 273 | for (const repoUrl of diff.toAdd ?? []) { |
| 274 | try { |
| 275 | await github.addDeployKey(repoUrl, deployKey); |
| 276 | console.log(`Added deploy key to repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 277 | if (publicAddr) { |
| 278 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 279 | await github.addPushWebhook(repoUrl, webhookCallbackUrl); |
| 280 | console.log(`Added push webhook to repository ${repoUrl}`); |
| 281 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 282 | } catch (error) { |
| 283 | console.error(`Failed to add deploy key from repository ${repoUrl}:`, error); |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 288 | const handleDeploy: express.Handler = async (req, resp) => { |
| 289 | try { |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 290 | const reqParsed = GraphConfigOrDraft.safeParse(req.body); |
| 291 | if (!reqParsed.success) { |
| 292 | resp.status(400); |
| 293 | resp.write(JSON.stringify({ error: "Invalid request body", issues: reqParsed.error.format() })); |
| 294 | return; |
| 295 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 296 | const projectId = Number(req.params["projectId"]); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 297 | const p = await db.project.findUnique({ |
| 298 | where: { |
| 299 | id: projectId, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 300 | // userId: resp.locals.userId, TODO(gio): validate |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 301 | }, |
| 302 | select: { |
| 303 | instanceId: true, |
| 304 | githubToken: true, |
| 305 | deployKey: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 306 | deployKeyPublic: true, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 307 | state: true, |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 308 | draft: true, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 309 | geminiApiKey: true, |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 310 | anthropicApiKey: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 311 | }, |
| 312 | }); |
| 313 | if (p === null) { |
| 314 | resp.status(404); |
| 315 | return; |
| 316 | } |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 317 | let graph: Graph | null = null; |
| 318 | let config: Config | null = null; |
| 319 | if (reqParsed.data.type === "config") { |
| 320 | const parsed = ConfigSchema.safeParse(reqParsed.data.config); |
| 321 | if (parsed.success) { |
| 322 | config = parsed.data; |
| 323 | } else { |
| 324 | resp.status(400); |
| 325 | resp.write(JSON.stringify({ error: "Invalid configuration", issues: parsed.error.format() })); |
| 326 | return; |
| 327 | } |
| 328 | let oldGraph: Graph | undefined = undefined; |
| 329 | if (p.state != null) { |
| 330 | oldGraph = parseGraph(p.state)!.data; |
| 331 | } else if (p.draft != null) { |
| 332 | oldGraph = parseGraph(p.draft)!.data; |
| 333 | } |
| 334 | let repos: GithubRepository[] = []; |
| 335 | if (p.githubToken) { |
| 336 | const github = new GithubClient(p.githubToken); |
| 337 | repos = await github.getRepositories(); |
| 338 | } |
| 339 | graph = configToGraph(config, getNetworks(resp.locals.username), repos, oldGraph); |
| 340 | } else if (reqParsed.data.type === "graph") { |
| 341 | graph = reqParsed.data.graph; |
| 342 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 343 | config = generateDodoConfig(projectId.toString(), graph?.nodes || [], env); |
| 344 | } else if (reqParsed.data.type === "draft") { |
| 345 | if (p.draft == null) { |
| 346 | resp.status(400); |
| 347 | resp.write(JSON.stringify({ error: "Invalid request body" })); |
| 348 | return; |
| 349 | } |
| 350 | graph = parseGraph(p.draft)!.data!; |
| 351 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 352 | config = generateDodoConfig(projectId.toString(), graph?.nodes || [], env); |
| 353 | } |
| 354 | if (config == null || graph == null) { |
| 355 | resp.status(500); |
| 356 | resp.write(JSON.stringify({ error: "Failed to generate configuration" })); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 357 | return; |
| 358 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 359 | await db.project.update({ |
| 360 | where: { |
| 361 | id: projectId, |
| 362 | }, |
| 363 | data: { |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 364 | draft: JSON.stringify(graph), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 365 | }, |
| 366 | }); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 367 | let deployKey: string | null = p.deployKey; |
| 368 | let deployKeyPublic: string | null = p.deployKeyPublic; |
| 369 | if (deployKeyPublic == null) { |
| 370 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 371 | await db.project.update({ |
| 372 | where: { id: projectId }, |
| 373 | data: { deployKeyPublic, deployKey }, |
| 374 | }); |
| 375 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 376 | let diff: RepoDiff | null = null; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 377 | const cfg: ConfigWithInput = { |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 378 | ...config, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 379 | input: { |
| 380 | appId: projectId.toString(), |
| 381 | managerAddr: env.INTERNAL_API_ADDR!, |
| 382 | key: { |
| 383 | public: deployKeyPublic!, |
| 384 | private: deployKey!, |
| 385 | }, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 386 | geminiApiKey: p.geminiApiKey ?? undefined, |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 387 | anthropicApiKey: p.anthropicApiKey ?? undefined, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 388 | }, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 389 | }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 390 | try { |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 391 | let deployResponse: DeployResponse | null = null; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 392 | if (p.instanceId == null) { |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 393 | deployResponse = await appManager.deploy(cfg); |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 394 | diff = { toAdd: extractGithubRepos(JSON.stringify(graph)) }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 395 | } else { |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 396 | deployResponse = await appManager.update(p.instanceId, cfg); |
| gio | 56e9f47 | 2025-07-07 03:33:38 +0000 | [diff] [blame] | 397 | diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(JSON.stringify(graph))); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 398 | } |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 399 | if (deployResponse == null) { |
| 400 | resp.status(500); |
| 401 | resp.write(JSON.stringify({ error: "Failed to deploy" })); |
| 402 | return; |
| 403 | } |
| 404 | await db.project.update({ |
| 405 | where: { |
| 406 | id: projectId, |
| 407 | }, |
| 408 | data: { |
| 409 | state: JSON.stringify(graph), |
| 410 | draft: null, |
| 411 | instanceId: deployResponse.id, |
| 412 | access: JSON.stringify(deployResponse.access), |
| 413 | envVars: JSON.stringify(deployResponse.envVars), |
| 414 | }, |
| 415 | }); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 416 | if (diff && p.githubToken && deployKey) { |
| 417 | const github = new GithubClient(p.githubToken); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 418 | await manageGithubRepos(github, diff, deployKeyPublic!, env.PUBLIC_ADDR); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 419 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 420 | resp.status(200); |
| 421 | } catch (error) { |
| 422 | console.error("Deployment error:", error); |
| 423 | resp.status(500); |
| 424 | resp.write(JSON.stringify({ error: "Deployment failed" })); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 425 | } |
| 426 | } catch (e) { |
| 427 | console.log(e); |
| 428 | resp.status(500); |
| 429 | } finally { |
| 430 | resp.end(); |
| 431 | } |
| 432 | }; |
| 433 | |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 434 | const handleSave: express.Handler = async (req, resp) => { |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 435 | try { |
| 436 | const projectId = Number(req.params["projectId"]); |
| 437 | const p = await db.project.findUnique({ |
| 438 | where: { |
| 439 | id: projectId, |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 440 | userId: resp.locals.userId, |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 441 | }, |
| 442 | select: { |
| 443 | instanceId: true, |
| 444 | githubToken: true, |
| 445 | deployKey: true, |
| 446 | deployKeyPublic: true, |
| 447 | state: true, |
| 448 | geminiApiKey: true, |
| 449 | anthropicApiKey: true, |
| 450 | }, |
| 451 | }); |
| 452 | if (p === null) { |
| 453 | resp.status(404); |
| 454 | return; |
| 455 | } |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 456 | const gc = GraphOrConfigSchema.safeParse(req.body); |
| 457 | if (!gc.success) { |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 458 | resp.status(400); |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 459 | resp.write(JSON.stringify({ error: "Invalid configuration", issues: gc.error.format() })); |
| 460 | return; |
| 461 | } |
| 462 | if (gc.data.type === "graph") { |
| 463 | await db.project.update({ |
| 464 | where: { id: projectId }, |
| 465 | data: { draft: JSON.stringify(gc.data.graph) }, |
| 466 | }); |
| 467 | resp.status(200); |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 468 | return; |
| 469 | } |
| 470 | let repos: GithubRepository[] = []; |
| 471 | if (p.githubToken) { |
| 472 | const github = new GithubClient(p.githubToken); |
| 473 | repos = await github.getRepositories(); |
| 474 | } |
| 475 | const state = JSON.stringify( |
| 476 | configToGraph( |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 477 | gc.data.config, |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 478 | getNetworks(resp.locals.username), |
| 479 | repos, |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 480 | p.state ? parseGraph(p.state)!.data! : undefined, |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 481 | ), |
| 482 | ); |
| 483 | await db.project.update({ |
| 484 | where: { id: projectId }, |
| 485 | data: { draft: state }, |
| 486 | }); |
| 487 | resp.status(200); |
| 488 | } catch (e) { |
| 489 | console.log(e); |
| 490 | resp.status(500); |
| 491 | } finally { |
| 492 | resp.end(); |
| 493 | } |
| 494 | }; |
| 495 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 496 | const handleStatus: express.Handler = async (req, resp) => { |
| 497 | try { |
| 498 | const projectId = Number(req.params["projectId"]); |
| 499 | const p = await db.project.findUnique({ |
| 500 | where: { |
| 501 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 502 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 503 | }, |
| 504 | select: { |
| 505 | instanceId: true, |
| 506 | }, |
| 507 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 508 | if (p === null) { |
| 509 | resp.status(404); |
| 510 | return; |
| 511 | } |
| 512 | if (p.instanceId == null) { |
| 513 | resp.status(404); |
| 514 | return; |
| 515 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 516 | try { |
| 517 | const status = await appManager.getStatus(p.instanceId); |
| 518 | resp.status(200); |
| 519 | resp.write(JSON.stringify(status)); |
| 520 | } catch (error) { |
| 521 | console.error("Error getting status:", error); |
| 522 | resp.status(500); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 523 | } |
| 524 | } catch (e) { |
| 525 | console.log(e); |
| 526 | resp.status(500); |
| 527 | } finally { |
| 528 | resp.end(); |
| 529 | } |
| 530 | }; |
| 531 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 532 | const handleConfigGet: express.Handler = async (req, resp) => { |
| 533 | try { |
| 534 | const projectId = Number(req.params["projectId"]); |
| 535 | const project = await db.project.findUnique({ |
| 536 | where: { |
| 537 | id: projectId, |
| 538 | }, |
| 539 | select: { |
| 540 | state: true, |
| 541 | }, |
| 542 | }); |
| 543 | |
| 544 | if (!project || !project.state) { |
| 545 | resp.status(404).send({ error: "No deployed configuration found." }); |
| 546 | return; |
| 547 | } |
| 548 | |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 549 | const state = parseGraph(project.state)!.data!; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 550 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 551 | const config = generateDodoConfig(projectId.toString(), state.nodes, env); |
| 552 | |
| 553 | if (!config) { |
| 554 | resp.status(500).send({ error: "Failed to generate configuration." }); |
| 555 | return; |
| 556 | } |
| 557 | resp.status(200).json(config); |
| 558 | } catch (e) { |
| 559 | console.log(e); |
| 560 | resp.status(500).send({ error: "Internal server error" }); |
| 561 | } finally { |
| 562 | console.log("config get done"); |
| 563 | resp.end(); |
| 564 | } |
| 565 | }; |
| 566 | |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 567 | const handleRemoveDeployment: express.Handler = async (req, resp) => { |
| 568 | try { |
| 569 | const projectId = Number(req.params["projectId"]); |
| 570 | const p = await db.project.findUnique({ |
| 571 | where: { |
| 572 | id: projectId, |
| 573 | userId: resp.locals.userId, |
| 574 | }, |
| 575 | select: { |
| 576 | instanceId: true, |
| 577 | githubToken: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 578 | deployKeyPublic: true, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 579 | state: true, |
| 580 | draft: true, |
| 581 | }, |
| 582 | }); |
| 583 | if (p === null) { |
| 584 | resp.status(404); |
| 585 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 586 | return; |
| 587 | } |
| 588 | if (p.instanceId == null) { |
| 589 | resp.status(400); |
| 590 | resp.write(JSON.stringify({ error: "Project not deployed" })); |
| 591 | return; |
| 592 | } |
| 593 | const removed = await appManager.removeInstance(p.instanceId); |
| 594 | if (!removed) { |
| 595 | resp.status(500); |
| 596 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 597 | return; |
| 598 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 599 | if (p.githubToken && p.deployKeyPublic && p.state) { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 600 | try { |
| 601 | const github = new GithubClient(p.githubToken); |
| 602 | const repos = extractGithubRepos(p.state); |
| 603 | const diff = { toDelete: repos, toAdd: [] }; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 604 | await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 605 | } catch (error) { |
| 606 | console.error("Error removing GitHub deploy keys:", error); |
| 607 | } |
| 608 | } |
| 609 | await db.project.update({ |
| 610 | where: { |
| 611 | id: projectId, |
| 612 | }, |
| 613 | data: { |
| 614 | instanceId: null, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 615 | deployKeyPublic: null, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 616 | access: null, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 617 | state: null, |
| 618 | draft: p.draft ?? p.state, |
| 619 | }, |
| 620 | }); |
| 621 | resp.status(200); |
| 622 | resp.write(JSON.stringify({ success: true })); |
| 623 | } catch (e) { |
| 624 | console.error("Error removing deployment:", e); |
| 625 | resp.status(500); |
| 626 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 627 | } finally { |
| 628 | resp.end(); |
| 629 | } |
| 630 | }; |
| 631 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 632 | const handleGithubRepos: express.Handler = async (req, resp) => { |
| 633 | try { |
| 634 | const projectId = Number(req.params["projectId"]); |
| 635 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 636 | where: { |
| 637 | id: projectId, |
| 638 | userId: resp.locals.userId, |
| 639 | }, |
| 640 | select: { |
| 641 | githubToken: true, |
| 642 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 643 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 644 | if (!project?.githubToken) { |
| 645 | resp.status(400); |
| 646 | resp.write(JSON.stringify({ error: "GitHub token not configured" })); |
| 647 | return; |
| 648 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 649 | const github = new GithubClient(project.githubToken); |
| 650 | const repositories = await github.getRepositories(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 651 | resp.status(200); |
| 652 | resp.header("Content-Type", "application/json"); |
| 653 | resp.write(JSON.stringify(repositories)); |
| 654 | } catch (e) { |
| 655 | console.log(e); |
| 656 | resp.status(500); |
| 657 | resp.write(JSON.stringify({ error: "Failed to fetch repositories" })); |
| 658 | } finally { |
| 659 | resp.end(); |
| 660 | } |
| 661 | }; |
| 662 | |
| 663 | const handleUpdateGithubToken: express.Handler = async (req, resp) => { |
| 664 | try { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 665 | await db.project.update({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 666 | where: { |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 667 | id: Number(req.params["projectId"]), |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 668 | userId: resp.locals.userId, |
| 669 | }, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 670 | data: { |
| 671 | githubToken: req.body.githubToken, |
| 672 | }, |
| 673 | }); |
| 674 | resp.status(200); |
| 675 | } catch (e) { |
| 676 | console.log(e); |
| 677 | resp.status(500); |
| 678 | } finally { |
| 679 | resp.end(); |
| 680 | } |
| 681 | }; |
| 682 | |
| 683 | const handleUpdateGeminiToken: express.Handler = async (req, resp) => { |
| 684 | try { |
| 685 | await db.project.update({ |
| 686 | where: { |
| 687 | id: Number(req.params["projectId"]), |
| 688 | userId: resp.locals.userId, |
| 689 | }, |
| 690 | data: { |
| 691 | geminiApiKey: req.body.geminiApiKey, |
| 692 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 693 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 694 | resp.status(200); |
| 695 | } catch (e) { |
| 696 | console.log(e); |
| 697 | resp.status(500); |
| 698 | } finally { |
| 699 | resp.end(); |
| 700 | } |
| 701 | }; |
| 702 | |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 703 | const handleUpdateAnthropicToken: express.Handler = async (req, resp) => { |
| 704 | try { |
| 705 | await db.project.update({ |
| 706 | where: { |
| 707 | id: Number(req.params["projectId"]), |
| 708 | userId: resp.locals.userId, |
| 709 | }, |
| 710 | data: { |
| 711 | anthropicApiKey: req.body.anthropicApiKey, |
| 712 | }, |
| 713 | }); |
| 714 | resp.status(200); |
| 715 | } catch (e) { |
| 716 | console.log(e); |
| 717 | resp.status(500); |
| 718 | } finally { |
| 719 | resp.end(); |
| 720 | } |
| 721 | }; |
| 722 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 723 | const getNetworks = (username?: string | undefined): Network[] => { |
| 724 | return [ |
| 725 | { |
| 726 | name: "Trial", |
| 727 | domain: "trial.dodoapp.xyz", |
| 728 | hasAuth: false, |
| 729 | }, |
| 730 | // TODO(gio): Remove |
| 731 | ].concat( |
| 732 | username === "gio" || 1 == 1 |
| 733 | ? [ |
| 734 | { |
| 735 | name: "Public", |
| 736 | domain: "v1.dodo.cloud", |
| 737 | hasAuth: true, |
| 738 | }, |
| 739 | { |
| 740 | name: "Private", |
| 741 | domain: "p.v1.dodo.cloud", |
| 742 | hasAuth: true, |
| 743 | }, |
| 744 | ] |
| 745 | : [], |
| 746 | ); |
| 747 | }; |
| 748 | |
| 749 | const getEnv = async (projectId: number, userId: string, username: string): Promise<Env> => { |
| 750 | const project = await db.project.findUnique({ |
| 751 | where: { |
| 752 | id: projectId, |
| 753 | userId, |
| 754 | }, |
| 755 | select: { |
| 756 | deployKeyPublic: true, |
| 757 | githubToken: true, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 758 | geminiApiKey: true, |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 759 | anthropicApiKey: true, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 760 | access: true, |
| 761 | instanceId: true, |
| 762 | }, |
| 763 | }); |
| 764 | if (!project) { |
| 765 | throw new Error("Project not found"); |
| 766 | } |
| 767 | const monitor = projectMonitors.get(projectId); |
| 768 | const serviceNames = monitor ? monitor.getAllServiceNames() : []; |
| 769 | const services = serviceNames.map((name: string) => ({ |
| 770 | name, |
| 771 | workers: [...(monitor ? monitor.getWorkerStatusesForService(name) : new Map()).entries()].map( |
| 772 | ([id, status]) => ({ |
| 773 | ...status, |
| 774 | id, |
| 775 | }), |
| 776 | ), |
| 777 | })); |
| 778 | return { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 779 | deployKeyPublic: project.deployKeyPublic == null ? undefined : project.deployKeyPublic, |
| 780 | instanceId: project.instanceId == null ? undefined : project.instanceId, |
| 781 | access: JSON.parse(project.access ?? "[]"), |
| 782 | integrations: { |
| 783 | github: !!project.githubToken, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 784 | gemini: !!project.geminiApiKey, |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 785 | anthropic: !!project.anthropicApiKey, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 786 | }, |
| 787 | networks: getNetworks(username), |
| 788 | services, |
| 789 | user: { |
| 790 | id: userId, |
| 791 | username: username, |
| 792 | }, |
| 793 | }; |
| 794 | }; |
| 795 | |
| gio | 43e0aad | 2025-08-01 16:17:27 +0400 | [diff] [blame] | 796 | const handleMachines: express.Handler = async (req, resp) => { |
| 797 | try { |
| 798 | const machines = await machineManager.getUserMachines(resp.locals.username); |
| 799 | resp.status(200); |
| 800 | resp.write(JSON.stringify(machines)); |
| 801 | } catch (error) { |
| 802 | console.error("Error getting machines:", error); |
| 803 | resp.status(500); |
| 804 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 805 | } finally { |
| 806 | resp.end(); |
| 807 | } |
| 808 | }; |
| 809 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 810 | const handleEnv: express.Handler = async (req, resp) => { |
| 811 | const projectId = Number(req.params["projectId"]); |
| 812 | try { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 813 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 814 | resp.status(200); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 815 | resp.write(JSON.stringify(env)); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 816 | } catch (error) { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 817 | console.error("Error getting env:", error); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 818 | resp.status(500); |
| 819 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 820 | } finally { |
| 821 | resp.end(); |
| 822 | } |
| 823 | }; |
| 824 | |
| gio | 007c857 | 2025-07-08 04:27:35 +0000 | [diff] [blame] | 825 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 826 | const internalEnvSchema = z.object({ |
| 827 | githubToken: z.string().optional(), |
| 828 | networks: z.array( |
| 829 | z.object({ |
| 830 | name: z.string(), |
| 831 | domain: z.string(), |
| 832 | hasAuth: z.boolean(), |
| 833 | }), |
| 834 | ), |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 835 | envVars: z.array(z.object({ name: z.string(), value: z.string() })), |
| gio | 007c857 | 2025-07-08 04:27:35 +0000 | [diff] [blame] | 836 | }); |
| 837 | |
| 838 | type InternalEnv = z.infer<typeof internalEnvSchema>; |
| 839 | |
| 840 | const handleInternalEnv: express.Handler = async (req, resp) => { |
| 841 | try { |
| 842 | console.log("getting internal env"); |
| 843 | const project = await db.project.findUnique({ |
| 844 | where: { |
| 845 | id: Number(req.params["projectId"]), |
| 846 | userId: resp.locals.userId, |
| 847 | }, |
| 848 | select: { |
| 849 | githubToken: true, |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 850 | envVars: true, |
| gio | 007c857 | 2025-07-08 04:27:35 +0000 | [diff] [blame] | 851 | }, |
| 852 | }); |
| 853 | const networks = getNetworks(resp.locals.username); |
| 854 | const env: InternalEnv = { |
| 855 | networks, |
| 856 | githubToken: project?.githubToken ?? undefined, |
| gio | e085d5b | 2025-07-08 07:51:36 +0000 | [diff] [blame] | 857 | envVars: JSON.parse(project?.envVars ?? "[]"), |
| gio | 007c857 | 2025-07-08 04:27:35 +0000 | [diff] [blame] | 858 | }; |
| 859 | resp.status(200); |
| 860 | resp.write(JSON.stringify(env)); |
| 861 | } catch (error) { |
| 862 | console.error("Error getting env:", error); |
| 863 | resp.status(500); |
| 864 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 865 | } finally { |
| 866 | resp.end(); |
| 867 | } |
| 868 | }; |
| 869 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 870 | const handleServiceLogs: express.Handler = async (req, resp) => { |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 871 | const projectId = Number(req.params["projectId"]); |
| 872 | const service = req.params["service"]; |
| 873 | const workerId = req.params["workerId"]; |
| 874 | |
| 875 | resp.setHeader("Content-Type", "text/event-stream"); |
| 876 | resp.setHeader("Cache-Control", "no-cache"); |
| 877 | resp.setHeader("Connection", "keep-alive"); |
| 878 | resp.flushHeaders(); |
| 879 | |
| 880 | const timestampFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| 881 | const sendLogs = (logs: LogItem[]) => { |
| 882 | if (logs.length == 0) { |
| 883 | return; |
| 884 | } |
| 885 | const logString = logs |
| 886 | .map((l) => { |
| 887 | const t = Instant.ofEpochMilli(l.timestampMilli); |
| 888 | const formattedTimestamp = t.atZone(ZoneId.UTC).format(timestampFormat); |
| 889 | return `\x1b[38;5;240m${formattedTimestamp}\x1b[0m ${l.contents}`; |
| 890 | }) |
| 891 | .join("\n"); |
| 892 | resp.write("event: message\n"); |
| 893 | resp.write(`data: ${JSON.stringify({ logs: logString })}\n\n`); |
| 894 | }; |
| 895 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 896 | try { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 897 | const project = await db.project.findUnique({ |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 898 | where: { id: projectId, userId: resp.locals.userId }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 899 | }); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 900 | |
| 901 | if (!project) { |
| 902 | resp.status(404).end(); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 903 | return; |
| 904 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 905 | |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 906 | const monitor = projectMonitors.get(projectId); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 907 | if (!monitor) { |
| 908 | resp.status(404).end(); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 909 | return; |
| 910 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 911 | |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 912 | let lastLogId: number | undefined = undefined; |
| 913 | const initialLogs = (await logStore.get(projectId, service, workerId)) || []; |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 914 | await sendLogs(initialLogs); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 915 | if (initialLogs.length > 0) { |
| 916 | lastLogId = initialLogs[initialLogs.length - 1].id; |
| 917 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 918 | resp.flushHeaders(); |
| 919 | |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 920 | const intervalId = setInterval(async () => { |
| 921 | const currentLogs = (await logStore.get(projectId, service, workerId, lastLogId)) || []; |
| 922 | if (currentLogs.length > 0) { |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 923 | await sendLogs(currentLogs); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 924 | lastLogId = currentLogs[currentLogs.length - 1].id; |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 925 | } |
| 926 | }, 500); |
| 927 | |
| 928 | req.on("close", () => { |
| 929 | clearInterval(intervalId); |
| 930 | resp.end(); |
| 931 | }); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 932 | } catch (e) { |
| 933 | console.log(e); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 934 | resp.status(500).end(); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 935 | } |
| 936 | }; |
| 937 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 938 | const handleRegisterWorker: express.Handler = async (req, resp) => { |
| 939 | try { |
| 940 | const projectId = Number(req.params["projectId"]); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 941 | const result = WorkerSchema.safeParse(req.body); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 942 | if (!result.success) { |
| gio | a70535a | 2025-07-02 15:50:25 +0000 | [diff] [blame] | 943 | console.log(JSON.stringify(result.error)); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 944 | resp.status(400); |
| 945 | resp.write( |
| 946 | JSON.stringify({ |
| 947 | error: "Invalid request data", |
| 948 | details: result.error.format(), |
| 949 | }), |
| 950 | ); |
| 951 | return; |
| 952 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 953 | let monitor = projectMonitors.get(projectId); |
| 954 | if (!monitor) { |
| 955 | monitor = new ProjectMonitor(); |
| 956 | projectMonitors.set(projectId, monitor); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 957 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 958 | monitor.registerWorker(result.data); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 959 | if (result.data.logs) { |
| 960 | await logStore.store(projectId, result.data.service, result.data.id, result.data.logs); |
| 961 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 962 | resp.status(200); |
| 963 | resp.write( |
| 964 | JSON.stringify({ |
| 965 | success: true, |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 966 | logItemsConsumed: result.data.logs?.length ?? 0, |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 967 | }), |
| 968 | ); |
| 969 | } catch (e) { |
| 970 | console.log(e); |
| 971 | resp.status(500); |
| 972 | resp.write(JSON.stringify({ error: "Failed to register worker" })); |
| 973 | } finally { |
| 974 | resp.end(); |
| 975 | } |
| 976 | }; |
| 977 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 978 | async function reloadProject(projectId: number): Promise<boolean> { |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 979 | const monitor = projectMonitors.get(projectId); |
| 980 | const projectWorkers = monitor ? monitor.getWorkerAddresses() : []; |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 981 | const workerCount = projectWorkers.length; |
| 982 | if (workerCount === 0) { |
| 983 | return true; |
| 984 | } |
| 985 | const results = await Promise.all( |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 986 | projectWorkers.map(async (workerAddress: string) => { |
| 987 | try { |
| gio | 4561679 | 2025-08-03 11:44:02 +0000 | [diff] [blame] | 988 | const resp = await axios.get(`${workerAddress}/update`); |
| 989 | return resp.status === 200; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 990 | } catch (error) { |
| 991 | console.error(`Failed to reload worker ${workerAddress}:`, error); |
| 992 | return false; |
| 993 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 994 | }), |
| 995 | ); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 996 | return results.reduce((acc: boolean, curr: boolean) => acc && curr, true); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 997 | } |
| 998 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 999 | const handleReload: express.Handler = async (req, resp) => { |
| 1000 | try { |
| 1001 | const projectId = Number(req.params["projectId"]); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1002 | const projectAuth = await db.project.findFirst({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1003 | where: { |
| 1004 | id: projectId, |
| 1005 | userId: resp.locals.userId, |
| 1006 | }, |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1007 | select: { id: true }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1008 | }); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1009 | if (!projectAuth) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1010 | resp.status(404); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1011 | return; |
| 1012 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1013 | const success = await reloadProject(projectId); |
| 1014 | if (success) { |
| 1015 | resp.status(200); |
| 1016 | } else { |
| 1017 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 1018 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 1019 | } catch (e) { |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1020 | console.error(e); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 1021 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 1022 | } |
| 1023 | }; |
| 1024 | |
| gio | 577d234 | 2025-07-03 12:50:18 +0000 | [diff] [blame] | 1025 | const handleQuitWorker: express.Handler = async (req, resp) => { |
| 1026 | const projectId = Number(req.params["projectId"]); |
| 1027 | const serviceName = req.params["serviceName"]; |
| 1028 | const workerId = req.params["workerId"]; |
| 1029 | |
| 1030 | const projectMonitor = projectMonitors.get(projectId); |
| 1031 | if (!projectMonitor) { |
| 1032 | resp.status(404).send({ error: "Project monitor not found" }); |
| 1033 | return; |
| 1034 | } |
| 1035 | |
| 1036 | try { |
| 1037 | await projectMonitor.terminateWorker(serviceName, workerId); |
| 1038 | resp.status(200).send({ message: "Worker termination initiated" }); |
| 1039 | } catch (error) { |
| 1040 | console.error( |
| 1041 | `Failed to terminate worker ${workerId} in service ${serviceName} for project ${projectId}:`, |
| 1042 | error, |
| 1043 | ); |
| 1044 | const errorMessage = error instanceof Error ? error.message : "Unknown error"; |
| 1045 | resp.status(500).send({ error: `Failed to terminate worker: ${errorMessage}` }); |
| 1046 | } |
| 1047 | }; |
| 1048 | |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 1049 | const handleReloadWorker: express.Handler = async (req, resp) => { |
| 1050 | const projectId = Number(req.params["projectId"]); |
| 1051 | const serviceName = req.params["serviceName"]; |
| 1052 | const workerId = req.params["workerId"]; |
| 1053 | |
| 1054 | const projectMonitor = projectMonitors.get(projectId); |
| 1055 | if (!projectMonitor) { |
| 1056 | resp.status(404).send({ error: "Project monitor not found" }); |
| 1057 | return; |
| 1058 | } |
| 1059 | |
| 1060 | try { |
| 1061 | await projectMonitor.reloadWorker(serviceName, workerId); |
| 1062 | resp.status(200).send({ message: "Worker reload initiated" }); |
| 1063 | } catch (error) { |
| 1064 | console.error(`Failed to reload worker ${workerId} in service ${serviceName} for project ${projectId}:`, error); |
| 1065 | const errorMessage = error instanceof Error ? error.message : "Unknown error"; |
| 1066 | resp.status(500).send({ error: `Failed to reload worker: ${errorMessage}` }); |
| 1067 | } |
| 1068 | }; |
| 1069 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1070 | const analyzeRepoReqSchema = z.object({ |
| 1071 | address: z.string(), |
| 1072 | }); |
| 1073 | |
| 1074 | const handleAnalyzeRepo: express.Handler = async (req, resp) => { |
| 1075 | const projectId = Number(req.params["projectId"]); |
| 1076 | const project = await db.project.findUnique({ |
| 1077 | where: { |
| 1078 | id: projectId, |
| 1079 | userId: resp.locals.userId, |
| 1080 | }, |
| 1081 | select: { |
| 1082 | githubToken: true, |
| 1083 | deployKey: true, |
| 1084 | deployKeyPublic: true, |
| 1085 | }, |
| 1086 | }); |
| 1087 | if (!project) { |
| 1088 | resp.status(404).send({ error: "Project not found" }); |
| 1089 | return; |
| 1090 | } |
| 1091 | if (!project.githubToken) { |
| 1092 | resp.status(400).send({ error: "GitHub token not configured" }); |
| 1093 | return; |
| 1094 | } |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame] | 1095 | let tmpDir: tmp.DirResult | null = null; |
| 1096 | try { |
| 1097 | let deployKey: string | null = project.deployKey; |
| 1098 | let deployKeyPublic: string | null = project.deployKeyPublic; |
| 1099 | if (!deployKeyPublic) { |
| 1100 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 1101 | await db.project.update({ |
| 1102 | where: { id: projectId }, |
| 1103 | data: { |
| 1104 | deployKeyPublic: deployKeyPublic, |
| 1105 | deployKey: deployKey, |
| 1106 | }, |
| 1107 | }); |
| 1108 | } |
| 1109 | const github = new GithubClient(project.githubToken); |
| 1110 | const result = analyzeRepoReqSchema.safeParse(req.body); |
| 1111 | if (!result.success) { |
| 1112 | resp.status(400).send({ error: "Invalid request data" }); |
| 1113 | return; |
| 1114 | } |
| 1115 | const { address } = result.data; |
| 1116 | tmpDir = tmp.dirSync({ |
| 1117 | unsafeCleanup: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1118 | }); |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame] | 1119 | await github.addDeployKey(address, deployKeyPublic); |
| 1120 | await fs.promises.writeFile(path.join(tmpDir.name, "key"), deployKey!, { |
| 1121 | mode: 0o600, |
| 1122 | }); |
| 1123 | shell.exec( |
| 1124 | `GIT_SSH_COMMAND='ssh -i ${tmpDir.name}/key -o IdentitiesOnly=yes' git clone ${address} ${tmpDir.name}/code`, |
| 1125 | ); |
| 1126 | const fsc = new RealFileSystem(`${tmpDir.name}/code`); |
| 1127 | const analyzer = new NodeJSAnalyzer(); |
| 1128 | const info = await analyzer.analyze(fsc, "/"); |
| 1129 | resp.status(200).send([info]); |
| 1130 | } catch (e) { |
| 1131 | console.error(e); |
| 1132 | resp.status(500).send({ error: "Failed to analyze repository" }); |
| 1133 | } finally { |
| 1134 | if (tmpDir) { |
| 1135 | tmpDir.removeCallback(); |
| 1136 | } |
| 1137 | resp.end(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1138 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1139 | }; |
| 1140 | |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1141 | const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => { |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 1142 | // Hardcoded user for development |
| gio | 8c4ea24 | 2025-08-04 13:11:29 +0000 | [diff] [blame^] | 1143 | resp.locals.userId = req.headers["x-forwarded-userid"]; |
| 1144 | resp.locals.username = req.headers["x-forwarded-user"]; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1145 | next(); |
| 1146 | }; |
| 1147 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1148 | const handleGithubPushWebhook: express.Handler = async (req, resp) => { |
| 1149 | try { |
| 1150 | // TODO(gio): Implement GitHub signature verification for security |
| 1151 | const webhookSchema = z.object({ |
| 1152 | repository: z.object({ |
| 1153 | ssh_url: z.string(), |
| 1154 | }), |
| 1155 | }); |
| 1156 | |
| 1157 | const result = webhookSchema.safeParse(req.body); |
| 1158 | if (!result.success) { |
| 1159 | console.warn("GitHub webhook: Invalid payload:", result.error.issues); |
| 1160 | resp.status(400).json({ error: "Invalid webhook payload" }); |
| 1161 | return; |
| 1162 | } |
| 1163 | const { ssh_url: addr } = result.data.repository; |
| 1164 | const allProjects = await db.project.findMany({ |
| 1165 | select: { |
| 1166 | id: true, |
| 1167 | state: true, |
| 1168 | }, |
| 1169 | where: { |
| 1170 | instanceId: { |
| 1171 | not: null, |
| 1172 | }, |
| 1173 | }, |
| 1174 | }); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1175 | new Promise<boolean>((resolve, reject) => { |
| 1176 | setTimeout(() => { |
| 1177 | const projectsToReloadIds: number[] = []; |
| 1178 | for (const project of allProjects) { |
| 1179 | if (project.state && project.state.length > 0) { |
| 1180 | const projectRepos = extractGithubRepos(project.state); |
| 1181 | if (projectRepos.includes(addr)) { |
| 1182 | projectsToReloadIds.push(project.id); |
| 1183 | } |
| 1184 | } |
| 1185 | } |
| 1186 | Promise.all(projectsToReloadIds.map((id) => reloadProject(id))) |
| 1187 | .then((results) => { |
| 1188 | resolve(results.reduce((acc, curr) => acc && curr, true)); |
| 1189 | }) |
| 1190 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 1191 | .catch((reason: any) => reject(reason)); |
| 1192 | }, 10); |
| 1193 | }); |
| gio | 4561679 | 2025-08-03 11:44:02 +0000 | [diff] [blame] | 1194 | resp.status(200); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1195 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 1196 | } catch (error: any) { |
| 1197 | console.error(error); |
| 1198 | resp.status(500); |
| gio | 4561679 | 2025-08-03 11:44:02 +0000 | [diff] [blame] | 1199 | } finally { |
| 1200 | resp.end(); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1201 | } |
| 1202 | }; |
| 1203 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1204 | const handleValidateConfig: express.Handler = async (req, resp) => { |
| 1205 | try { |
| 1206 | const validationResult = ConfigSchema.safeParse(req.body); |
| 1207 | if (!validationResult.success) { |
| 1208 | resp.status(400); |
| 1209 | resp.header("Content-Type", "application/json"); |
| 1210 | resp.write(JSON.stringify({ success: false, errors: validationResult.error.flatten() })); |
| 1211 | } else { |
| 1212 | resp.status(200); |
| 1213 | resp.header("Content-Type", "application/json"); |
| 1214 | resp.write(JSON.stringify({ success: true })); |
| 1215 | } |
| 1216 | } catch (e) { |
| 1217 | console.log(e); |
| 1218 | resp.status(500); |
| 1219 | } finally { |
| 1220 | resp.end(); |
| 1221 | } |
| 1222 | }; |
| 1223 | |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 1224 | function handleStateGetStream(state: "deploy" | "draft"): express.Handler { |
| 1225 | return async (req, resp) => { |
| 1226 | resp.setHeader("Content-Type", "text/event-stream"); |
| 1227 | resp.setHeader("Cache-Control", "no-cache"); |
| 1228 | resp.setHeader("Connection", "keep-alive"); |
| 1229 | resp.flushHeaders(); |
| 1230 | |
| 1231 | try { |
| 1232 | let intervalId: NodeJS.Timeout | null = null; |
| 1233 | let lastState: Graph | null = null; |
| 1234 | const sendState = async () => { |
| 1235 | const currentState = await getState(Number(req.params["projectId"]), resp.locals.userId, state); |
| 1236 | if (currentState == null) { |
| 1237 | resp.status(404).end(); |
| 1238 | return; |
| 1239 | } |
| 1240 | if (JSON.stringify(currentState) !== JSON.stringify(lastState)) { |
| 1241 | lastState = currentState; |
| 1242 | resp.write("event: message\n"); |
| 1243 | resp.write(`data: ${JSON.stringify(currentState)}\n\n`); |
| 1244 | } |
| 1245 | intervalId = setTimeout(sendState, 500); |
| 1246 | }; |
| 1247 | |
| 1248 | await sendState(); |
| 1249 | |
| 1250 | req.on("close", () => { |
| 1251 | if (intervalId) { |
| 1252 | clearTimeout(intervalId); |
| 1253 | } |
| 1254 | resp.end(); |
| 1255 | }); |
| 1256 | } catch (e) { |
| 1257 | console.log(e); |
| 1258 | resp.end(); |
| 1259 | } |
| 1260 | }; |
| 1261 | } |
| 1262 | |
| gio | 785c988 | 2025-07-07 16:40:25 +0000 | [diff] [blame] | 1263 | const handleAgentStatus: express.Handler = async (req, resp) => { |
| 1264 | const projectId = Number(req.params["projectId"]); |
| 1265 | const agentName = req.params["agentName"]; |
| 1266 | try { |
| 1267 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 1268 | const agent = env.access.find((a): a is AgentAccess => a.type === "https" && a.agentName === agentName); |
| 1269 | if (!agent) { |
| 1270 | resp.status(404).send({ status: 404 }); |
| 1271 | return; |
| 1272 | } |
| 1273 | const agentResp = await axios.get(agent.address); |
| 1274 | resp.status(200).send({ status: agentResp.status }); |
| 1275 | } catch { |
| 1276 | resp.status(200).send({ status: 500 }); |
| 1277 | } |
| 1278 | }; |
| 1279 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1280 | async function start() { |
| 1281 | await db.$connect(); |
| 1282 | const app = express(); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1283 | app.set("json spaces", 2); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1284 | app.use(express.json()); // Global JSON parsing |
| 1285 | |
| 1286 | // Public webhook route - no auth needed |
| 1287 | app.post("/api/webhook/github/push", handleGithubPushWebhook); |
| 1288 | |
| gio | 43e0aad | 2025-08-01 16:17:27 +0400 | [diff] [blame] | 1289 | // Public machines route - no auth needed |
| 1290 | app.get("/api/machines", auth, handleMachines); |
| 1291 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1292 | // Authenticated project routes |
| 1293 | const projectRouter = express.Router(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1294 | projectRouter.use(auth); |
| 1295 | projectRouter.post("/:projectId/analyze", handleAnalyzeRepo); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1296 | projectRouter.post("/:projectId/saved", handleSave); |
| gio | 8a5f12f | 2025-07-05 07:02:31 +0000 | [diff] [blame] | 1297 | projectRouter.get("/:projectId/state/stream/deploy", handleStateGetStream("deploy")); |
| 1298 | projectRouter.get("/:projectId/state/stream/draft", handleStateGetStream("draft")); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1299 | projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy")); |
| 1300 | projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft")); |
| 1301 | projectRouter.post("/:projectId/deploy", handleDeploy); |
| 1302 | projectRouter.get("/:projectId/status", handleStatus); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1303 | projectRouter.get("/:projectId/config", handleConfigGet); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1304 | projectRouter.delete("/:projectId", handleProjectDelete); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1305 | projectRouter.get("/:projectId/repos/github", handleGithubRepos); |
| 1306 | projectRouter.post("/:projectId/github-token", handleUpdateGithubToken); |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 1307 | projectRouter.post("/:projectId/gemini-token", handleUpdateGeminiToken); |
| gio | 69ff759 | 2025-07-03 06:27:21 +0000 | [diff] [blame] | 1308 | projectRouter.post("/:projectId/anthropic-token", handleUpdateAnthropicToken); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1309 | projectRouter.get("/:projectId/env", handleEnv); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 1310 | projectRouter.post("/:projectId/reload/:serviceName/:workerId", handleReloadWorker); |
| gio | 577d234 | 2025-07-03 12:50:18 +0000 | [diff] [blame] | 1311 | projectRouter.post("/:projectId/quitquitquit/:serviceName/:workerId", handleQuitWorker); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1312 | projectRouter.post("/:projectId/reload", handleReload); |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 1313 | projectRouter.get("/:projectId/logs/:service/:workerId", handleServiceLogs); |
| gio | 785c988 | 2025-07-07 16:40:25 +0000 | [diff] [blame] | 1314 | projectRouter.get("/:projectId/agent/:agentName/status", handleAgentStatus); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1315 | projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment); |
| 1316 | projectRouter.get("/", handleProjectAll); |
| 1317 | projectRouter.post("/", handleProjectCreate); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 1318 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1319 | app.use("/api/project", projectRouter); // Mount the authenticated router |
| 1320 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1321 | app.use("/", express.static("../front/dist")); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1322 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1323 | const internalApi = express(); |
| 1324 | internalApi.use(express.json()); |
| 1325 | internalApi.post("/api/project/:projectId/workers", handleRegisterWorker); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1326 | internalApi.get("/api/project/:projectId/config", handleConfigGet); |
| gio | 10ff134 | 2025-07-05 10:22:15 +0000 | [diff] [blame] | 1327 | internalApi.post("/api/project/:projectId/saved", handleSave); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1328 | internalApi.post("/api/project/:projectId/deploy", handleDeploy); |
| gio | 007c857 | 2025-07-08 04:27:35 +0000 | [diff] [blame] | 1329 | internalApi.get("/api/project/:projectId/env", handleInternalEnv); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1330 | internalApi.post("/api/validate-config", handleValidateConfig); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1331 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1332 | app.listen(env.DODO_PORT_WEB, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1333 | console.log("Web server started on port", env.DODO_PORT_WEB); |
| 1334 | }); |
| 1335 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1336 | internalApi.listen(env.DODO_PORT_API, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1337 | console.log("Internal API server started on port", env.DODO_PORT_API); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1338 | }); |
| 1339 | } |
| 1340 | |
| gio | 166d992 | 2025-07-07 17:30:21 +0000 | [diff] [blame] | 1341 | function cleanupWorkers() { |
| 1342 | const now = Date.now(); |
| 1343 | projectMonitors.forEach((monitor) => { |
| 1344 | monitor.cleanupWorkers(now); |
| 1345 | }); |
| 1346 | setTimeout(cleanupWorkers, 1000); |
| 1347 | } |
| 1348 | |
| 1349 | setTimeout(cleanupWorkers, 1000); |
| 1350 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1351 | start(); |