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