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