| 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 | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 329 | }, |
| 330 | }); |
| 331 | if (p === null) { |
| 332 | resp.status(404); |
| 333 | return; |
| 334 | } |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 335 | const config = ConfigSchema.safeParse(req.body.config); |
| 336 | if (!config.success) { |
| 337 | resp.status(400); |
| 338 | resp.write(JSON.stringify({ error: "Invalid configuration", issues: config.error.format() })); |
| 339 | return; |
| 340 | } |
| gio | 9b7421a | 2025-06-18 12:31:13 +0000 | [diff] [blame] | 341 | let repos: GithubRepository[] = []; |
| 342 | if (p.githubToken) { |
| 343 | const github = new GithubClient(p.githubToken); |
| 344 | repos = await github.getRepositories(); |
| 345 | } |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 346 | const state = req.body.state |
| 347 | ? JSON.stringify(req.body.state) |
| 348 | : JSON.stringify( |
| 349 | configToGraph( |
| 350 | config.data, |
| 351 | getNetworks(resp.locals.username), |
| gio | 9b7421a | 2025-06-18 12:31:13 +0000 | [diff] [blame] | 352 | repos, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 353 | p.state ? JSON.parse(Buffer.from(p.state).toString("utf8")) : null, |
| 354 | ), |
| 355 | ); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 356 | await db.project.update({ |
| 357 | where: { |
| 358 | id: projectId, |
| 359 | }, |
| 360 | data: { |
| 361 | draft: state, |
| 362 | }, |
| 363 | }); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 364 | let deployKey: string | null = p.deployKey; |
| 365 | let deployKeyPublic: string | null = p.deployKeyPublic; |
| 366 | if (deployKeyPublic == null) { |
| 367 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 368 | await db.project.update({ |
| 369 | where: { id: projectId }, |
| 370 | data: { deployKeyPublic, deployKey }, |
| 371 | }); |
| 372 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 373 | let diff: RepoDiff | null = null; |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 374 | const cfg: ConfigWithInput = { |
| 375 | ...config.data, |
| 376 | input: { |
| 377 | appId: projectId.toString(), |
| 378 | managerAddr: env.INTERNAL_API_ADDR!, |
| 379 | key: { |
| 380 | public: deployKeyPublic!, |
| 381 | private: deployKey!, |
| 382 | }, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 383 | geminiApiKey: p.geminiApiKey ?? undefined, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 384 | }, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 385 | }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 386 | try { |
| 387 | if (p.instanceId == null) { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 388 | const deployResponse = await appManager.deploy(cfg); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 389 | await db.project.update({ |
| 390 | where: { |
| 391 | id: projectId, |
| 392 | }, |
| 393 | data: { |
| 394 | state, |
| 395 | draft: null, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 396 | instanceId: deployResponse.id, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 397 | access: JSON.stringify(deployResponse.access), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 398 | }, |
| 399 | }); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 400 | diff = { toAdd: extractGithubRepos(state) }; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 401 | } else { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 402 | const deployResponse = await appManager.update(p.instanceId, cfg); |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 403 | diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(state)); |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 404 | await db.project.update({ |
| 405 | where: { |
| 406 | id: projectId, |
| 407 | }, |
| 408 | data: { |
| 409 | state, |
| 410 | draft: null, |
| 411 | access: JSON.stringify(deployResponse.access), |
| 412 | }, |
| 413 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 414 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 415 | if (diff && p.githubToken && deployKey) { |
| 416 | const github = new GithubClient(p.githubToken); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 417 | await manageGithubRepos(github, diff, deployKeyPublic!, env.PUBLIC_ADDR); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 418 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 419 | resp.status(200); |
| 420 | } catch (error) { |
| 421 | console.error("Deployment error:", error); |
| 422 | resp.status(500); |
| 423 | resp.write(JSON.stringify({ error: "Deployment failed" })); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 424 | } |
| 425 | } catch (e) { |
| 426 | console.log(e); |
| 427 | resp.status(500); |
| 428 | } finally { |
| 429 | resp.end(); |
| 430 | } |
| 431 | }; |
| 432 | |
| 433 | const handleStatus: express.Handler = async (req, resp) => { |
| 434 | try { |
| 435 | const projectId = Number(req.params["projectId"]); |
| 436 | const p = await db.project.findUnique({ |
| 437 | where: { |
| 438 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 439 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 440 | }, |
| 441 | select: { |
| 442 | instanceId: true, |
| 443 | }, |
| 444 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 445 | if (p === null) { |
| 446 | resp.status(404); |
| 447 | return; |
| 448 | } |
| 449 | if (p.instanceId == null) { |
| 450 | resp.status(404); |
| 451 | return; |
| 452 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 453 | try { |
| 454 | const status = await appManager.getStatus(p.instanceId); |
| 455 | resp.status(200); |
| 456 | resp.write(JSON.stringify(status)); |
| 457 | } catch (error) { |
| 458 | console.error("Error getting status:", error); |
| 459 | resp.status(500); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 460 | } |
| 461 | } catch (e) { |
| 462 | console.log(e); |
| 463 | resp.status(500); |
| 464 | } finally { |
| 465 | resp.end(); |
| 466 | } |
| 467 | }; |
| 468 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 469 | const handleConfigGet: express.Handler = async (req, resp) => { |
| 470 | try { |
| 471 | const projectId = Number(req.params["projectId"]); |
| 472 | const project = await db.project.findUnique({ |
| 473 | where: { |
| 474 | id: projectId, |
| 475 | }, |
| 476 | select: { |
| 477 | state: true, |
| 478 | }, |
| 479 | }); |
| 480 | |
| 481 | if (!project || !project.state) { |
| 482 | resp.status(404).send({ error: "No deployed configuration found." }); |
| 483 | return; |
| 484 | } |
| 485 | |
| 486 | const state = JSON.parse(Buffer.from(project.state).toString("utf8")); |
| 487 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| 488 | const config = generateDodoConfig(projectId.toString(), state.nodes, env); |
| 489 | |
| 490 | if (!config) { |
| 491 | resp.status(500).send({ error: "Failed to generate configuration." }); |
| 492 | return; |
| 493 | } |
| 494 | resp.status(200).json(config); |
| 495 | } catch (e) { |
| 496 | console.log(e); |
| 497 | resp.status(500).send({ error: "Internal server error" }); |
| 498 | } finally { |
| 499 | console.log("config get done"); |
| 500 | resp.end(); |
| 501 | } |
| 502 | }; |
| 503 | |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 504 | const handleRemoveDeployment: express.Handler = async (req, resp) => { |
| 505 | try { |
| 506 | const projectId = Number(req.params["projectId"]); |
| 507 | const p = await db.project.findUnique({ |
| 508 | where: { |
| 509 | id: projectId, |
| 510 | userId: resp.locals.userId, |
| 511 | }, |
| 512 | select: { |
| 513 | instanceId: true, |
| 514 | githubToken: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 515 | deployKeyPublic: true, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 516 | state: true, |
| 517 | draft: true, |
| 518 | }, |
| 519 | }); |
| 520 | if (p === null) { |
| 521 | resp.status(404); |
| 522 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 523 | return; |
| 524 | } |
| 525 | if (p.instanceId == null) { |
| 526 | resp.status(400); |
| 527 | resp.write(JSON.stringify({ error: "Project not deployed" })); |
| 528 | return; |
| 529 | } |
| 530 | const removed = await appManager.removeInstance(p.instanceId); |
| 531 | if (!removed) { |
| 532 | resp.status(500); |
| 533 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 534 | return; |
| 535 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 536 | if (p.githubToken && p.deployKeyPublic && p.state) { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 537 | try { |
| 538 | const github = new GithubClient(p.githubToken); |
| 539 | const repos = extractGithubRepos(p.state); |
| 540 | const diff = { toDelete: repos, toAdd: [] }; |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 541 | await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 542 | } catch (error) { |
| 543 | console.error("Error removing GitHub deploy keys:", error); |
| 544 | } |
| 545 | } |
| 546 | await db.project.update({ |
| 547 | where: { |
| 548 | id: projectId, |
| 549 | }, |
| 550 | data: { |
| 551 | instanceId: null, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 552 | deployKeyPublic: null, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 553 | access: null, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 554 | state: null, |
| 555 | draft: p.draft ?? p.state, |
| 556 | }, |
| 557 | }); |
| 558 | resp.status(200); |
| 559 | resp.write(JSON.stringify({ success: true })); |
| 560 | } catch (e) { |
| 561 | console.error("Error removing deployment:", e); |
| 562 | resp.status(500); |
| 563 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 564 | } finally { |
| 565 | resp.end(); |
| 566 | } |
| 567 | }; |
| 568 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 569 | const handleGithubRepos: express.Handler = async (req, resp) => { |
| 570 | try { |
| 571 | const projectId = Number(req.params["projectId"]); |
| 572 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 573 | where: { |
| 574 | id: projectId, |
| 575 | userId: resp.locals.userId, |
| 576 | }, |
| 577 | select: { |
| 578 | githubToken: true, |
| 579 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 580 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 581 | if (!project?.githubToken) { |
| 582 | resp.status(400); |
| 583 | resp.write(JSON.stringify({ error: "GitHub token not configured" })); |
| 584 | return; |
| 585 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 586 | const github = new GithubClient(project.githubToken); |
| 587 | const repositories = await github.getRepositories(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 588 | resp.status(200); |
| 589 | resp.header("Content-Type", "application/json"); |
| 590 | resp.write(JSON.stringify(repositories)); |
| 591 | } catch (e) { |
| 592 | console.log(e); |
| 593 | resp.status(500); |
| 594 | resp.write(JSON.stringify({ error: "Failed to fetch repositories" })); |
| 595 | } finally { |
| 596 | resp.end(); |
| 597 | } |
| 598 | }; |
| 599 | |
| 600 | const handleUpdateGithubToken: express.Handler = async (req, resp) => { |
| 601 | try { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 602 | await db.project.update({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 603 | where: { |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 604 | id: Number(req.params["projectId"]), |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 605 | userId: resp.locals.userId, |
| 606 | }, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 607 | data: { |
| 608 | githubToken: req.body.githubToken, |
| 609 | }, |
| 610 | }); |
| 611 | resp.status(200); |
| 612 | } catch (e) { |
| 613 | console.log(e); |
| 614 | resp.status(500); |
| 615 | } finally { |
| 616 | resp.end(); |
| 617 | } |
| 618 | }; |
| 619 | |
| 620 | const handleUpdateGeminiToken: express.Handler = async (req, resp) => { |
| 621 | try { |
| 622 | await db.project.update({ |
| 623 | where: { |
| 624 | id: Number(req.params["projectId"]), |
| 625 | userId: resp.locals.userId, |
| 626 | }, |
| 627 | data: { |
| 628 | geminiApiKey: req.body.geminiApiKey, |
| 629 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 630 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 631 | resp.status(200); |
| 632 | } catch (e) { |
| 633 | console.log(e); |
| 634 | resp.status(500); |
| 635 | } finally { |
| 636 | resp.end(); |
| 637 | } |
| 638 | }; |
| 639 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 640 | const getNetworks = (username?: string | undefined): Network[] => { |
| 641 | return [ |
| 642 | { |
| 643 | name: "Trial", |
| 644 | domain: "trial.dodoapp.xyz", |
| 645 | hasAuth: false, |
| 646 | }, |
| 647 | // TODO(gio): Remove |
| 648 | ].concat( |
| 649 | username === "gio" || 1 == 1 |
| 650 | ? [ |
| 651 | { |
| 652 | name: "Public", |
| 653 | domain: "v1.dodo.cloud", |
| 654 | hasAuth: true, |
| 655 | }, |
| 656 | { |
| 657 | name: "Private", |
| 658 | domain: "p.v1.dodo.cloud", |
| 659 | hasAuth: true, |
| 660 | }, |
| 661 | ] |
| 662 | : [], |
| 663 | ); |
| 664 | }; |
| 665 | |
| 666 | const getEnv = async (projectId: number, userId: string, username: string): Promise<Env> => { |
| 667 | const project = await db.project.findUnique({ |
| 668 | where: { |
| 669 | id: projectId, |
| 670 | userId, |
| 671 | }, |
| 672 | select: { |
| 673 | deployKeyPublic: true, |
| 674 | githubToken: true, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 675 | geminiApiKey: true, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 676 | access: true, |
| 677 | instanceId: true, |
| 678 | }, |
| 679 | }); |
| 680 | if (!project) { |
| 681 | throw new Error("Project not found"); |
| 682 | } |
| 683 | const monitor = projectMonitors.get(projectId); |
| 684 | const serviceNames = monitor ? monitor.getAllServiceNames() : []; |
| 685 | const services = serviceNames.map((name: string) => ({ |
| 686 | name, |
| 687 | workers: [...(monitor ? monitor.getWorkerStatusesForService(name) : new Map()).entries()].map( |
| 688 | ([id, status]) => ({ |
| 689 | ...status, |
| 690 | id, |
| 691 | }), |
| 692 | ), |
| 693 | })); |
| 694 | return { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 695 | deployKeyPublic: project.deployKeyPublic == null ? undefined : project.deployKeyPublic, |
| 696 | instanceId: project.instanceId == null ? undefined : project.instanceId, |
| 697 | access: JSON.parse(project.access ?? "[]"), |
| 698 | integrations: { |
| 699 | github: !!project.githubToken, |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 700 | gemini: !!project.geminiApiKey, |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 701 | }, |
| 702 | networks: getNetworks(username), |
| 703 | services, |
| 704 | user: { |
| 705 | id: userId, |
| 706 | username: username, |
| 707 | }, |
| 708 | }; |
| 709 | }; |
| 710 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 711 | const handleEnv: express.Handler = async (req, resp) => { |
| 712 | const projectId = Number(req.params["projectId"]); |
| 713 | try { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 714 | const env = await getEnv(projectId, resp.locals.userId, resp.locals.username); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 715 | resp.status(200); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 716 | resp.write(JSON.stringify(env)); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 717 | } catch (error) { |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 718 | console.error("Error getting env:", error); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 719 | resp.status(500); |
| 720 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 721 | } finally { |
| 722 | resp.end(); |
| 723 | } |
| 724 | }; |
| 725 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 726 | const handleServiceLogs: express.Handler = async (req, resp) => { |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 727 | const projectId = Number(req.params["projectId"]); |
| 728 | const service = req.params["service"]; |
| 729 | const workerId = req.params["workerId"]; |
| 730 | |
| 731 | resp.setHeader("Content-Type", "text/event-stream"); |
| 732 | resp.setHeader("Cache-Control", "no-cache"); |
| 733 | resp.setHeader("Connection", "keep-alive"); |
| 734 | resp.flushHeaders(); |
| 735 | |
| 736 | const timestampFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| 737 | const sendLogs = (logs: LogItem[]) => { |
| 738 | if (logs.length == 0) { |
| 739 | return; |
| 740 | } |
| 741 | const logString = logs |
| 742 | .map((l) => { |
| 743 | const t = Instant.ofEpochMilli(l.timestampMilli); |
| 744 | const formattedTimestamp = t.atZone(ZoneId.UTC).format(timestampFormat); |
| 745 | return `\x1b[38;5;240m${formattedTimestamp}\x1b[0m ${l.contents}`; |
| 746 | }) |
| 747 | .join("\n"); |
| 748 | resp.write("event: message\n"); |
| 749 | resp.write(`data: ${JSON.stringify({ logs: logString })}\n\n`); |
| 750 | }; |
| 751 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 752 | try { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 753 | const project = await db.project.findUnique({ |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 754 | where: { id: projectId, userId: resp.locals.userId }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 755 | }); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 756 | |
| 757 | if (!project) { |
| 758 | resp.status(404).end(); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 759 | return; |
| 760 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 761 | |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 762 | const monitor = projectMonitors.get(projectId); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 763 | if (!monitor) { |
| 764 | resp.status(404).end(); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 765 | return; |
| 766 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 767 | |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 768 | let lastLogId: number | undefined = undefined; |
| 769 | const initialLogs = (await logStore.get(projectId, service, workerId)) || []; |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 770 | sendLogs(initialLogs); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 771 | if (initialLogs.length > 0) { |
| 772 | lastLogId = initialLogs[initialLogs.length - 1].id; |
| 773 | } |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 774 | resp.flushHeaders(); |
| 775 | |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 776 | const intervalId = setInterval(async () => { |
| 777 | const currentLogs = (await logStore.get(projectId, service, workerId, lastLogId)) || []; |
| 778 | if (currentLogs.length > 0) { |
| 779 | sendLogs(currentLogs); |
| 780 | lastLogId = currentLogs[currentLogs.length - 1].id; |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 781 | } |
| 782 | }, 500); |
| 783 | |
| 784 | req.on("close", () => { |
| 785 | clearInterval(intervalId); |
| 786 | resp.end(); |
| 787 | }); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 788 | } catch (e) { |
| 789 | console.log(e); |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 790 | resp.status(500).end(); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 791 | } |
| 792 | }; |
| 793 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 794 | const handleRegisterWorker: express.Handler = async (req, resp) => { |
| 795 | try { |
| 796 | const projectId = Number(req.params["projectId"]); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 797 | const result = WorkerSchema.safeParse(req.body); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 798 | if (!result.success) { |
| gio | a70535a | 2025-07-02 15:50:25 +0000 | [diff] [blame] | 799 | console.log(JSON.stringify(result.error)); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 800 | resp.status(400); |
| 801 | resp.write( |
| 802 | JSON.stringify({ |
| 803 | error: "Invalid request data", |
| 804 | details: result.error.format(), |
| 805 | }), |
| 806 | ); |
| 807 | return; |
| 808 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 809 | let monitor = projectMonitors.get(projectId); |
| 810 | if (!monitor) { |
| 811 | monitor = new ProjectMonitor(); |
| 812 | projectMonitors.set(projectId, monitor); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 813 | } |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 814 | monitor.registerWorker(result.data); |
| gio | 40c0c99 | 2025-07-02 13:18:05 +0000 | [diff] [blame] | 815 | if (result.data.logs) { |
| 816 | await logStore.store(projectId, result.data.service, result.data.id, result.data.logs); |
| 817 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 818 | resp.status(200); |
| 819 | resp.write( |
| 820 | JSON.stringify({ |
| 821 | success: true, |
| gio | 78a2288 | 2025-07-01 18:56:01 +0000 | [diff] [blame] | 822 | logItemsConsumed: result.data.logs?.length ?? 0, |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 823 | }), |
| 824 | ); |
| 825 | } catch (e) { |
| 826 | console.log(e); |
| 827 | resp.status(500); |
| 828 | resp.write(JSON.stringify({ error: "Failed to register worker" })); |
| 829 | } finally { |
| 830 | resp.end(); |
| 831 | } |
| 832 | }; |
| 833 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 834 | async function reloadProject(projectId: number): Promise<boolean> { |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 835 | const monitor = projectMonitors.get(projectId); |
| 836 | const projectWorkers = monitor ? monitor.getWorkerAddresses() : []; |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 837 | const workerCount = projectWorkers.length; |
| 838 | if (workerCount === 0) { |
| 839 | return true; |
| 840 | } |
| 841 | const results = await Promise.all( |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 842 | projectWorkers.map(async (workerAddress: string) => { |
| 843 | try { |
| 844 | const { data } = await axios.get(`http://${workerAddress}/reload`); |
| 845 | return data.every((s: { status: string }) => s.status === "ok"); |
| 846 | } catch (error) { |
| 847 | console.error(`Failed to reload worker ${workerAddress}:`, error); |
| 848 | return false; |
| 849 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 850 | }), |
| 851 | ); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 852 | return results.reduce((acc: boolean, curr: boolean) => acc && curr, true); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 853 | } |
| 854 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 855 | const handleReload: express.Handler = async (req, resp) => { |
| 856 | try { |
| 857 | const projectId = Number(req.params["projectId"]); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 858 | const projectAuth = await db.project.findFirst({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 859 | where: { |
| 860 | id: projectId, |
| 861 | userId: resp.locals.userId, |
| 862 | }, |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 863 | select: { id: true }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 864 | }); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 865 | if (!projectAuth) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 866 | resp.status(404); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 867 | return; |
| 868 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 869 | const success = await reloadProject(projectId); |
| 870 | if (success) { |
| 871 | resp.status(200); |
| 872 | } else { |
| 873 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 874 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 875 | } catch (e) { |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 876 | console.error(e); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 877 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 878 | } |
| 879 | }; |
| 880 | |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 881 | const handleReloadWorker: express.Handler = async (req, resp) => { |
| 882 | const projectId = Number(req.params["projectId"]); |
| 883 | const serviceName = req.params["serviceName"]; |
| 884 | const workerId = req.params["workerId"]; |
| 885 | |
| 886 | const projectMonitor = projectMonitors.get(projectId); |
| 887 | if (!projectMonitor) { |
| 888 | resp.status(404).send({ error: "Project monitor not found" }); |
| 889 | return; |
| 890 | } |
| 891 | |
| 892 | try { |
| 893 | await projectMonitor.reloadWorker(serviceName, workerId); |
| 894 | resp.status(200).send({ message: "Worker reload initiated" }); |
| 895 | } catch (error) { |
| 896 | console.error(`Failed to reload worker ${workerId} in service ${serviceName} for project ${projectId}:`, error); |
| 897 | const errorMessage = error instanceof Error ? error.message : "Unknown error"; |
| 898 | resp.status(500).send({ error: `Failed to reload worker: ${errorMessage}` }); |
| 899 | } |
| 900 | }; |
| 901 | |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 902 | const analyzeRepoReqSchema = z.object({ |
| 903 | address: z.string(), |
| 904 | }); |
| 905 | |
| 906 | const handleAnalyzeRepo: express.Handler = async (req, resp) => { |
| 907 | const projectId = Number(req.params["projectId"]); |
| 908 | const project = await db.project.findUnique({ |
| 909 | where: { |
| 910 | id: projectId, |
| 911 | userId: resp.locals.userId, |
| 912 | }, |
| 913 | select: { |
| 914 | githubToken: true, |
| 915 | deployKey: true, |
| 916 | deployKeyPublic: true, |
| 917 | }, |
| 918 | }); |
| 919 | if (!project) { |
| 920 | resp.status(404).send({ error: "Project not found" }); |
| 921 | return; |
| 922 | } |
| 923 | if (!project.githubToken) { |
| 924 | resp.status(400).send({ error: "GitHub token not configured" }); |
| 925 | return; |
| 926 | } |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame] | 927 | let tmpDir: tmp.DirResult | null = null; |
| 928 | try { |
| 929 | let deployKey: string | null = project.deployKey; |
| 930 | let deployKeyPublic: string | null = project.deployKeyPublic; |
| 931 | if (!deployKeyPublic) { |
| 932 | [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name); |
| 933 | await db.project.update({ |
| 934 | where: { id: projectId }, |
| 935 | data: { |
| 936 | deployKeyPublic: deployKeyPublic, |
| 937 | deployKey: deployKey, |
| 938 | }, |
| 939 | }); |
| 940 | } |
| 941 | const github = new GithubClient(project.githubToken); |
| 942 | const result = analyzeRepoReqSchema.safeParse(req.body); |
| 943 | if (!result.success) { |
| 944 | resp.status(400).send({ error: "Invalid request data" }); |
| 945 | return; |
| 946 | } |
| 947 | const { address } = result.data; |
| 948 | tmpDir = tmp.dirSync({ |
| 949 | unsafeCleanup: true, |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 950 | }); |
| gio | 8e74dc0 | 2025-06-13 10:19:26 +0000 | [diff] [blame] | 951 | await github.addDeployKey(address, deployKeyPublic); |
| 952 | await fs.promises.writeFile(path.join(tmpDir.name, "key"), deployKey!, { |
| 953 | mode: 0o600, |
| 954 | }); |
| 955 | shell.exec( |
| 956 | `GIT_SSH_COMMAND='ssh -i ${tmpDir.name}/key -o IdentitiesOnly=yes' git clone ${address} ${tmpDir.name}/code`, |
| 957 | ); |
| 958 | const fsc = new RealFileSystem(`${tmpDir.name}/code`); |
| 959 | const analyzer = new NodeJSAnalyzer(); |
| 960 | const info = await analyzer.analyze(fsc, "/"); |
| 961 | resp.status(200).send([info]); |
| 962 | } catch (e) { |
| 963 | console.error(e); |
| 964 | resp.status(500).send({ error: "Failed to analyze repository" }); |
| 965 | } finally { |
| 966 | if (tmpDir) { |
| 967 | tmpDir.removeCallback(); |
| 968 | } |
| 969 | resp.end(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 970 | } |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 971 | }; |
| 972 | |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 973 | const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => { |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 974 | // Hardcoded user for development |
| 975 | resp.locals.userId = "1"; |
| 976 | resp.locals.username = "gio"; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 977 | next(); |
| 978 | }; |
| 979 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 980 | const handleGithubPushWebhook: express.Handler = async (req, resp) => { |
| 981 | try { |
| 982 | // TODO(gio): Implement GitHub signature verification for security |
| 983 | const webhookSchema = z.object({ |
| 984 | repository: z.object({ |
| 985 | ssh_url: z.string(), |
| 986 | }), |
| 987 | }); |
| 988 | |
| 989 | const result = webhookSchema.safeParse(req.body); |
| 990 | if (!result.success) { |
| 991 | console.warn("GitHub webhook: Invalid payload:", result.error.issues); |
| 992 | resp.status(400).json({ error: "Invalid webhook payload" }); |
| 993 | return; |
| 994 | } |
| 995 | const { ssh_url: addr } = result.data.repository; |
| 996 | const allProjects = await db.project.findMany({ |
| 997 | select: { |
| 998 | id: true, |
| 999 | state: true, |
| 1000 | }, |
| 1001 | where: { |
| 1002 | instanceId: { |
| 1003 | not: null, |
| 1004 | }, |
| 1005 | }, |
| 1006 | }); |
| 1007 | // TODO(gio): This should run in background |
| 1008 | new Promise<boolean>((resolve, reject) => { |
| 1009 | setTimeout(() => { |
| 1010 | const projectsToReloadIds: number[] = []; |
| 1011 | for (const project of allProjects) { |
| 1012 | if (project.state && project.state.length > 0) { |
| 1013 | const projectRepos = extractGithubRepos(project.state); |
| 1014 | if (projectRepos.includes(addr)) { |
| 1015 | projectsToReloadIds.push(project.id); |
| 1016 | } |
| 1017 | } |
| 1018 | } |
| 1019 | Promise.all(projectsToReloadIds.map((id) => reloadProject(id))) |
| 1020 | .then((results) => { |
| 1021 | resolve(results.reduce((acc, curr) => acc && curr, true)); |
| 1022 | }) |
| 1023 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 1024 | .catch((reason: any) => reject(reason)); |
| 1025 | }, 10); |
| 1026 | }); |
| 1027 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 1028 | } catch (error: any) { |
| 1029 | console.error(error); |
| 1030 | resp.status(500); |
| 1031 | } |
| 1032 | }; |
| 1033 | |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1034 | const handleValidateConfig: express.Handler = async (req, resp) => { |
| 1035 | try { |
| 1036 | const validationResult = ConfigSchema.safeParse(req.body); |
| 1037 | if (!validationResult.success) { |
| 1038 | resp.status(400); |
| 1039 | resp.header("Content-Type", "application/json"); |
| 1040 | resp.write(JSON.stringify({ success: false, errors: validationResult.error.flatten() })); |
| 1041 | } else { |
| 1042 | resp.status(200); |
| 1043 | resp.header("Content-Type", "application/json"); |
| 1044 | resp.write(JSON.stringify({ success: true })); |
| 1045 | } |
| 1046 | } catch (e) { |
| 1047 | console.log(e); |
| 1048 | resp.status(500); |
| 1049 | } finally { |
| 1050 | resp.end(); |
| 1051 | } |
| 1052 | }; |
| 1053 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1054 | async function start() { |
| 1055 | await db.$connect(); |
| 1056 | const app = express(); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1057 | app.set("json spaces", 2); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1058 | app.use(express.json()); // Global JSON parsing |
| 1059 | |
| 1060 | // Public webhook route - no auth needed |
| 1061 | app.post("/api/webhook/github/push", handleGithubPushWebhook); |
| 1062 | |
| 1063 | // Authenticated project routes |
| 1064 | const projectRouter = express.Router(); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1065 | projectRouter.use(auth); |
| 1066 | projectRouter.post("/:projectId/analyze", handleAnalyzeRepo); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1067 | projectRouter.post("/:projectId/saved", handleSave); |
| 1068 | projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy")); |
| 1069 | projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft")); |
| 1070 | projectRouter.post("/:projectId/deploy", handleDeploy); |
| 1071 | projectRouter.get("/:projectId/status", handleStatus); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1072 | projectRouter.get("/:projectId/config", handleConfigGet); |
| gio | a71316d | 2025-05-24 09:41:36 +0400 | [diff] [blame] | 1073 | projectRouter.delete("/:projectId", handleProjectDelete); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1074 | projectRouter.get("/:projectId/repos/github", handleGithubRepos); |
| 1075 | projectRouter.post("/:projectId/github-token", handleUpdateGithubToken); |
| gio | 6914832 | 2025-06-19 23:16:12 +0400 | [diff] [blame] | 1076 | projectRouter.post("/:projectId/gemini-token", handleUpdateGeminiToken); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1077 | projectRouter.get("/:projectId/env", handleEnv); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 1078 | projectRouter.post("/:projectId/reload/:serviceName/:workerId", handleReloadWorker); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1079 | projectRouter.post("/:projectId/reload", handleReload); |
| gio | a1efbad | 2025-05-21 07:16:45 +0000 | [diff] [blame] | 1080 | projectRouter.get("/:projectId/logs/:service/:workerId", handleServiceLogs); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1081 | projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment); |
| 1082 | projectRouter.get("/", handleProjectAll); |
| 1083 | projectRouter.post("/", handleProjectCreate); |
| gio | 918780d | 2025-05-22 08:24:41 +0000 | [diff] [blame] | 1084 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1085 | app.use("/api/project", projectRouter); // Mount the authenticated router |
| 1086 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1087 | app.use("/", express.static("../front/dist")); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1088 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1089 | const internalApi = express(); |
| 1090 | internalApi.use(express.json()); |
| 1091 | internalApi.post("/api/project/:projectId/workers", handleRegisterWorker); |
| gio | c31bf14 | 2025-06-16 07:48:20 +0000 | [diff] [blame] | 1092 | internalApi.get("/api/project/:projectId/config", handleConfigGet); |
| 1093 | internalApi.post("/api/project/:projectId/deploy", handleDeploy); |
| 1094 | internalApi.post("/api/validate-config", handleValidateConfig); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1095 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1096 | app.listen(env.DODO_PORT_WEB, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1097 | console.log("Web server started on port", env.DODO_PORT_WEB); |
| 1098 | }); |
| 1099 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame] | 1100 | internalApi.listen(env.DODO_PORT_API, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 1101 | console.log("Internal API server started on port", env.DODO_PORT_API); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1102 | }); |
| 1103 | } |
| 1104 | |
| 1105 | start(); |