| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 1 | import { PrismaClient } from "@prisma/client"; |
| 2 | import express from "express"; |
| 3 | import { env } from "node:process"; |
| 4 | import axios from "axios"; |
| 5 | import { GithubClient } from "./github"; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 6 | import { AppManager } from "./app_manager"; |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 7 | import { z } from "zod"; |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 8 | |
| 9 | const db = new PrismaClient(); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 10 | const appManager = new AppManager(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 11 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 12 | const workers = new Map<number, string[]>(); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 13 | const logs = new Map<number, Map<string, string>>(); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 14 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 15 | const handleProjectCreate: express.Handler = async (req, resp) => { |
| 16 | try { |
| 17 | const { id } = await db.project.create({ |
| 18 | data: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 19 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 20 | name: req.body.name, |
| 21 | }, |
| 22 | }); |
| 23 | resp.status(200); |
| 24 | resp.header("Content-Type", "application/json"); |
| 25 | resp.write( |
| 26 | JSON.stringify({ |
| gio | 74ab785 | 2025-05-13 13:19:31 +0000 | [diff] [blame] | 27 | id: id.toString(), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 28 | }), |
| 29 | ); |
| 30 | } catch (e) { |
| 31 | console.log(e); |
| 32 | resp.status(500); |
| 33 | } finally { |
| 34 | resp.end(); |
| 35 | } |
| 36 | }; |
| 37 | |
| 38 | const handleProjectAll: express.Handler = async (req, resp) => { |
| 39 | try { |
| 40 | const r = await db.project.findMany({ |
| 41 | where: { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 42 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 43 | }, |
| 44 | }); |
| 45 | resp.status(200); |
| 46 | resp.header("Content-Type", "application/json"); |
| 47 | resp.write( |
| 48 | JSON.stringify( |
| 49 | r.map((p) => ({ |
| 50 | id: p.id.toString(), |
| 51 | name: p.name, |
| 52 | })), |
| 53 | ), |
| 54 | ); |
| 55 | } catch (e) { |
| 56 | console.log(e); |
| 57 | resp.status(500); |
| 58 | } finally { |
| 59 | resp.end(); |
| 60 | } |
| 61 | }; |
| 62 | |
| 63 | const handleSave: express.Handler = async (req, resp) => { |
| 64 | try { |
| 65 | await db.project.update({ |
| 66 | where: { |
| 67 | id: Number(req.params["projectId"]), |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 68 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 69 | }, |
| 70 | data: { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 71 | draft: JSON.stringify(req.body), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 72 | }, |
| 73 | }); |
| 74 | resp.status(200); |
| 75 | } catch (e) { |
| 76 | console.log(e); |
| 77 | resp.status(500); |
| 78 | } finally { |
| 79 | resp.end(); |
| 80 | } |
| 81 | }; |
| 82 | |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 83 | function handleSavedGet(state: "deploy" | "draft"): express.Handler { |
| 84 | return async (req, resp) => { |
| 85 | try { |
| 86 | const r = await db.project.findUnique({ |
| 87 | where: { |
| 88 | id: Number(req.params["projectId"]), |
| 89 | userId: resp.locals.userId, |
| 90 | }, |
| 91 | select: { |
| 92 | state: true, |
| 93 | draft: true, |
| 94 | }, |
| 95 | }); |
| 96 | if (r == null) { |
| 97 | resp.status(404); |
| 98 | return; |
| 99 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 100 | resp.status(200); |
| 101 | resp.header("content-type", "application/json"); |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 102 | if (state === "deploy") { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 103 | if (r.state == null) { |
| 104 | resp.send({ |
| 105 | nodes: [], |
| 106 | edges: [], |
| 107 | viewport: { x: 0, y: 0, zoom: 1 }, |
| 108 | }); |
| 109 | } else { |
| 110 | resp.send(JSON.parse(Buffer.from(r.state).toString("utf8"))); |
| 111 | } |
| 112 | } else { |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 113 | if (r.draft == null) { |
| 114 | if (r.state == null) { |
| 115 | resp.send({ |
| 116 | nodes: [], |
| 117 | edges: [], |
| 118 | viewport: { x: 0, y: 0, zoom: 1 }, |
| 119 | }); |
| 120 | } else { |
| 121 | resp.send(JSON.parse(Buffer.from(r.state).toString("utf8"))); |
| 122 | } |
| 123 | } else { |
| 124 | resp.send(JSON.parse(Buffer.from(r.draft).toString("utf8"))); |
| 125 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 126 | } |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 127 | } catch (e) { |
| 128 | console.log(e); |
| 129 | resp.status(500); |
| 130 | } finally { |
| 131 | resp.end(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 132 | } |
| gio | 818da4e | 2025-05-12 14:45:35 +0000 | [diff] [blame] | 133 | }; |
| 134 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 135 | |
| 136 | const handleDelete: express.Handler = async (req, resp) => { |
| 137 | try { |
| 138 | const projectId = Number(req.params["projectId"]); |
| 139 | const p = await db.project.findUnique({ |
| 140 | where: { |
| 141 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 142 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 143 | }, |
| 144 | select: { |
| 145 | instanceId: true, |
| 146 | }, |
| 147 | }); |
| 148 | if (p === null) { |
| 149 | resp.status(404); |
| 150 | return; |
| 151 | } |
| gio | e440db8 | 2025-05-13 12:21:44 +0000 | [diff] [blame] | 152 | let ok = false; |
| 153 | if (p.instanceId === null) { |
| 154 | ok = true; |
| 155 | } else { |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 156 | ok = await appManager.removeInstance(p.instanceId); |
| gio | e440db8 | 2025-05-13 12:21:44 +0000 | [diff] [blame] | 157 | } |
| 158 | if (ok) { |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 159 | await db.project.delete({ |
| 160 | where: { |
| 161 | id: projectId, |
| 162 | }, |
| 163 | }); |
| 164 | } |
| 165 | resp.status(200); |
| 166 | } catch (e) { |
| 167 | console.log(e); |
| 168 | resp.status(500); |
| 169 | } finally { |
| 170 | resp.end(); |
| 171 | } |
| 172 | }; |
| 173 | |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 174 | function extractGithubRepos(serializedState: string | null): string[] { |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 175 | if (!serializedState) { |
| 176 | return []; |
| 177 | } |
| 178 | try { |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 179 | const stateObj = JSON.parse(serializedState); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 180 | const githubNodes = stateObj.nodes.filter( |
| 181 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 182 | (n: any) => n.type === "github" && n.data?.repository?.id, |
| 183 | ); |
| 184 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 185 | return githubNodes.map((n: any) => n.data.repository.sshURL); |
| 186 | } catch (error) { |
| 187 | console.error("Failed to parse state or extract GitHub repos:", error); |
| 188 | return []; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | type RepoDiff = { |
| 193 | toAdd?: string[]; |
| 194 | toDelete?: string[]; |
| 195 | }; |
| 196 | |
| 197 | function calculateRepoDiff(oldRepos: string[], newRepos: string[]): RepoDiff { |
| 198 | const toAdd = newRepos.filter((repo) => !oldRepos.includes(repo)); |
| 199 | const toDelete = oldRepos.filter((repo) => !newRepos.includes(repo)); |
| 200 | return { toAdd, toDelete }; |
| 201 | } |
| 202 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 203 | async function manageGithubRepos( |
| 204 | github: GithubClient, |
| 205 | diff: RepoDiff, |
| 206 | deployKey: string, |
| 207 | publicAddr?: string, |
| 208 | ): Promise<void> { |
| 209 | console.log(publicAddr); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 210 | for (const repoUrl of diff.toDelete ?? []) { |
| 211 | try { |
| 212 | await github.removeDeployKey(repoUrl, deployKey); |
| 213 | console.log(`Removed deploy key from repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 214 | if (publicAddr) { |
| 215 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 216 | await github.removePushWebhook(repoUrl, webhookCallbackUrl); |
| 217 | console.log(`Removed push webhook from repository ${repoUrl}`); |
| 218 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 219 | } catch (error) { |
| 220 | console.error(`Failed to remove deploy key from repository ${repoUrl}:`, error); |
| 221 | } |
| 222 | } |
| 223 | for (const repoUrl of diff.toAdd ?? []) { |
| 224 | try { |
| 225 | await github.addDeployKey(repoUrl, deployKey); |
| 226 | console.log(`Added deploy key to repository ${repoUrl}`); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 227 | if (publicAddr) { |
| 228 | const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`; |
| 229 | await github.addPushWebhook(repoUrl, webhookCallbackUrl); |
| 230 | console.log(`Added push webhook to repository ${repoUrl}`); |
| 231 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 232 | } catch (error) { |
| 233 | console.error(`Failed to add deploy key from repository ${repoUrl}:`, error); |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 238 | const handleDeploy: express.Handler = async (req, resp) => { |
| 239 | try { |
| 240 | const projectId = Number(req.params["projectId"]); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 241 | const state = JSON.stringify(req.body.state); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 242 | const p = await db.project.findUnique({ |
| 243 | where: { |
| 244 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 245 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 246 | }, |
| 247 | select: { |
| 248 | instanceId: true, |
| 249 | githubToken: true, |
| 250 | deployKey: true, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 251 | state: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 252 | }, |
| 253 | }); |
| 254 | if (p === null) { |
| 255 | resp.status(404); |
| 256 | return; |
| 257 | } |
| 258 | await db.project.update({ |
| 259 | where: { |
| 260 | id: projectId, |
| 261 | }, |
| 262 | data: { |
| 263 | draft: state, |
| 264 | }, |
| 265 | }); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 266 | let diff: RepoDiff | null = null; |
| 267 | let deployKey: string | null = null; |
| 268 | try { |
| 269 | if (p.instanceId == null) { |
| 270 | const deployResponse = await appManager.deploy(req.body.config); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 271 | await db.project.update({ |
| 272 | where: { |
| 273 | id: projectId, |
| 274 | }, |
| 275 | data: { |
| 276 | state, |
| 277 | draft: null, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 278 | instanceId: deployResponse.id, |
| 279 | deployKey: deployResponse.deployKey, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 280 | access: JSON.stringify(deployResponse.access), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 281 | }, |
| 282 | }); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 283 | diff = { toAdd: extractGithubRepos(state) }; |
| 284 | deployKey = deployResponse.deployKey; |
| 285 | } else { |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 286 | const deployResponse = await appManager.update(p.instanceId, req.body.config); |
| 287 | diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(state)); |
| 288 | deployKey = p.deployKey; |
| 289 | await db.project.update({ |
| 290 | where: { |
| 291 | id: projectId, |
| 292 | }, |
| 293 | data: { |
| 294 | state, |
| 295 | draft: null, |
| 296 | access: JSON.stringify(deployResponse.access), |
| 297 | }, |
| 298 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 299 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 300 | if (diff && p.githubToken && deployKey) { |
| 301 | const github = new GithubClient(p.githubToken); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 302 | await manageGithubRepos(github, diff, deployKey, env.PUBLIC_ADDR); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 303 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 304 | resp.status(200); |
| 305 | } catch (error) { |
| 306 | console.error("Deployment error:", error); |
| 307 | resp.status(500); |
| 308 | resp.write(JSON.stringify({ error: "Deployment failed" })); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 309 | } |
| 310 | } catch (e) { |
| 311 | console.log(e); |
| 312 | resp.status(500); |
| 313 | } finally { |
| 314 | resp.end(); |
| 315 | } |
| 316 | }; |
| 317 | |
| 318 | const handleStatus: express.Handler = async (req, resp) => { |
| 319 | try { |
| 320 | const projectId = Number(req.params["projectId"]); |
| 321 | const p = await db.project.findUnique({ |
| 322 | where: { |
| 323 | id: projectId, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 324 | userId: resp.locals.userId, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 325 | }, |
| 326 | select: { |
| 327 | instanceId: true, |
| 328 | }, |
| 329 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 330 | if (p === null) { |
| 331 | resp.status(404); |
| 332 | return; |
| 333 | } |
| 334 | if (p.instanceId == null) { |
| 335 | resp.status(404); |
| 336 | return; |
| 337 | } |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 338 | try { |
| 339 | const status = await appManager.getStatus(p.instanceId); |
| 340 | resp.status(200); |
| 341 | resp.write(JSON.stringify(status)); |
| 342 | } catch (error) { |
| 343 | console.error("Error getting status:", error); |
| 344 | resp.status(500); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 345 | } |
| 346 | } catch (e) { |
| 347 | console.log(e); |
| 348 | resp.status(500); |
| 349 | } finally { |
| 350 | resp.end(); |
| 351 | } |
| 352 | }; |
| 353 | |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 354 | const handleRemoveDeployment: express.Handler = async (req, resp) => { |
| 355 | try { |
| 356 | const projectId = Number(req.params["projectId"]); |
| 357 | const p = await db.project.findUnique({ |
| 358 | where: { |
| 359 | id: projectId, |
| 360 | userId: resp.locals.userId, |
| 361 | }, |
| 362 | select: { |
| 363 | instanceId: true, |
| 364 | githubToken: true, |
| 365 | deployKey: true, |
| 366 | state: true, |
| 367 | draft: true, |
| 368 | }, |
| 369 | }); |
| 370 | if (p === null) { |
| 371 | resp.status(404); |
| 372 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 373 | return; |
| 374 | } |
| 375 | if (p.instanceId == null) { |
| 376 | resp.status(400); |
| 377 | resp.write(JSON.stringify({ error: "Project not deployed" })); |
| 378 | return; |
| 379 | } |
| 380 | const removed = await appManager.removeInstance(p.instanceId); |
| 381 | if (!removed) { |
| 382 | resp.status(500); |
| 383 | resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" })); |
| 384 | return; |
| 385 | } |
| 386 | if (p.githubToken && p.deployKey && p.state) { |
| 387 | try { |
| 388 | const github = new GithubClient(p.githubToken); |
| 389 | const repos = extractGithubRepos(p.state); |
| 390 | const diff = { toDelete: repos, toAdd: [] }; |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 391 | await manageGithubRepos(github, diff, p.deployKey, env.PUBLIC_ADDR); |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 392 | } catch (error) { |
| 393 | console.error("Error removing GitHub deploy keys:", error); |
| 394 | } |
| 395 | } |
| 396 | await db.project.update({ |
| 397 | where: { |
| 398 | id: projectId, |
| 399 | }, |
| 400 | data: { |
| 401 | instanceId: null, |
| 402 | deployKey: null, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 403 | access: null, |
| gio | bd37a2b | 2025-05-15 04:28:42 +0000 | [diff] [blame] | 404 | state: null, |
| 405 | draft: p.draft ?? p.state, |
| 406 | }, |
| 407 | }); |
| 408 | resp.status(200); |
| 409 | resp.write(JSON.stringify({ success: true })); |
| 410 | } catch (e) { |
| 411 | console.error("Error removing deployment:", e); |
| 412 | resp.status(500); |
| 413 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 414 | } finally { |
| 415 | resp.end(); |
| 416 | } |
| 417 | }; |
| 418 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 419 | const handleGithubRepos: express.Handler = async (req, resp) => { |
| 420 | try { |
| 421 | const projectId = Number(req.params["projectId"]); |
| 422 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 423 | where: { |
| 424 | id: projectId, |
| 425 | userId: resp.locals.userId, |
| 426 | }, |
| 427 | select: { |
| 428 | githubToken: true, |
| 429 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 430 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 431 | if (!project?.githubToken) { |
| 432 | resp.status(400); |
| 433 | resp.write(JSON.stringify({ error: "GitHub token not configured" })); |
| 434 | return; |
| 435 | } |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 436 | const github = new GithubClient(project.githubToken); |
| 437 | const repositories = await github.getRepositories(); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 438 | resp.status(200); |
| 439 | resp.header("Content-Type", "application/json"); |
| 440 | resp.write(JSON.stringify(repositories)); |
| 441 | } catch (e) { |
| 442 | console.log(e); |
| 443 | resp.status(500); |
| 444 | resp.write(JSON.stringify({ error: "Failed to fetch repositories" })); |
| 445 | } finally { |
| 446 | resp.end(); |
| 447 | } |
| 448 | }; |
| 449 | |
| 450 | const handleUpdateGithubToken: express.Handler = async (req, resp) => { |
| 451 | try { |
| 452 | const projectId = Number(req.params["projectId"]); |
| 453 | const { githubToken } = req.body; |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 454 | await db.project.update({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 455 | where: { |
| 456 | id: projectId, |
| 457 | userId: resp.locals.userId, |
| 458 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 459 | data: { githubToken }, |
| 460 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 461 | resp.status(200); |
| 462 | } catch (e) { |
| 463 | console.log(e); |
| 464 | resp.status(500); |
| 465 | } finally { |
| 466 | resp.end(); |
| 467 | } |
| 468 | }; |
| 469 | |
| 470 | const handleEnv: express.Handler = async (req, resp) => { |
| 471 | const projectId = Number(req.params["projectId"]); |
| 472 | try { |
| 473 | const project = await db.project.findUnique({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 474 | where: { |
| 475 | id: projectId, |
| 476 | userId: resp.locals.userId, |
| 477 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 478 | select: { |
| 479 | deployKey: true, |
| 480 | githubToken: true, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 481 | access: true, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 482 | }, |
| 483 | }); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 484 | if (!project) { |
| 485 | resp.status(404); |
| 486 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 487 | return; |
| 488 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 489 | const projectLogs = logs.get(projectId) || new Map(); |
| 490 | const services = Array.from(projectLogs.keys()); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 491 | resp.status(200); |
| 492 | resp.write( |
| 493 | JSON.stringify({ |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 494 | // TODO(gio): get from env or command line flags |
| gio | 3304672 | 2025-05-16 14:49:55 +0000 | [diff] [blame] | 495 | managerAddr: "http://10.42.0.95:8081", |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 496 | deployKey: project.deployKey, |
| gio | b77cb93 | 2025-05-19 09:37:14 +0000 | [diff] [blame] | 497 | access: JSON.parse(project.access ?? "[]"), |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 498 | integrations: { |
| 499 | github: !!project.githubToken, |
| 500 | }, |
| 501 | networks: [ |
| 502 | { |
| gio | 3304672 | 2025-05-16 14:49:55 +0000 | [diff] [blame] | 503 | name: "Trial", |
| 504 | domain: "trial.dodoapp.xyz", |
| gio | 6d8b71c | 2025-05-19 12:57:35 +0000 | [diff] [blame] | 505 | hasAuth: false, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 506 | }, |
| 507 | ], |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 508 | services, |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 509 | user: { |
| 510 | id: resp.locals.userId, |
| 511 | username: resp.locals.username, |
| 512 | }, |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 513 | }), |
| 514 | ); |
| 515 | } catch (error) { |
| 516 | console.error("Error checking integrations:", error); |
| 517 | resp.status(500); |
| 518 | resp.write(JSON.stringify({ error: "Internal server error" })); |
| 519 | } finally { |
| 520 | resp.end(); |
| 521 | } |
| 522 | }; |
| 523 | |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 524 | const handleServiceLogs: express.Handler = async (req, resp) => { |
| 525 | try { |
| 526 | const projectId = Number(req.params["projectId"]); |
| 527 | const service = req.params["service"]; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 528 | const project = await db.project.findUnique({ |
| 529 | where: { |
| 530 | id: projectId, |
| 531 | userId: resp.locals.userId, |
| 532 | }, |
| 533 | }); |
| 534 | if (project == null) { |
| 535 | resp.status(404); |
| 536 | resp.write(JSON.stringify({ error: "Project not found" })); |
| 537 | return; |
| 538 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 539 | const projectLogs = logs.get(projectId); |
| 540 | if (!projectLogs) { |
| 541 | resp.status(404); |
| 542 | resp.write(JSON.stringify({ error: "No logs found for this project" })); |
| 543 | return; |
| 544 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 545 | const serviceLog = projectLogs.get(service); |
| 546 | if (!serviceLog) { |
| 547 | resp.status(404); |
| 548 | resp.write(JSON.stringify({ error: "No logs found for this service" })); |
| 549 | return; |
| 550 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 551 | resp.status(200); |
| 552 | resp.write(JSON.stringify({ logs: serviceLog })); |
| 553 | } catch (e) { |
| 554 | console.log(e); |
| 555 | resp.status(500); |
| 556 | resp.write(JSON.stringify({ error: "Failed to get service logs" })); |
| 557 | } finally { |
| 558 | resp.end(); |
| 559 | } |
| 560 | }; |
| 561 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 562 | const WorkerSchema = z.object({ |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 563 | service: z.string(), |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 564 | address: z.string().url(), |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 565 | logs: z.optional(z.string()), |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 566 | }); |
| 567 | |
| 568 | const handleRegisterWorker: express.Handler = async (req, resp) => { |
| 569 | try { |
| 570 | const projectId = Number(req.params["projectId"]); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 571 | const result = WorkerSchema.safeParse(req.body); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 572 | if (!result.success) { |
| 573 | resp.status(400); |
| 574 | resp.write( |
| 575 | JSON.stringify({ |
| 576 | error: "Invalid request data", |
| 577 | details: result.error.format(), |
| 578 | }), |
| 579 | ); |
| 580 | return; |
| 581 | } |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 582 | const { service, address, logs: log } = result.data; |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 583 | const projectWorkers = workers.get(projectId) || []; |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 584 | if (!projectWorkers.includes(address)) { |
| 585 | projectWorkers.push(address); |
| 586 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 587 | workers.set(projectId, projectWorkers); |
| gio | 3a921b8 | 2025-05-10 07:36:09 +0000 | [diff] [blame] | 588 | if (log) { |
| 589 | const svcLogs: Map<string, string> = logs.get(projectId) || new Map(); |
| 590 | svcLogs.set(service, log); |
| 591 | logs.set(projectId, svcLogs); |
| 592 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 593 | resp.status(200); |
| 594 | resp.write( |
| 595 | JSON.stringify({ |
| 596 | success: true, |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 597 | }), |
| 598 | ); |
| 599 | } catch (e) { |
| 600 | console.log(e); |
| 601 | resp.status(500); |
| 602 | resp.write(JSON.stringify({ error: "Failed to register worker" })); |
| 603 | } finally { |
| 604 | resp.end(); |
| 605 | } |
| 606 | }; |
| 607 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 608 | async function reloadProject(projectId: number): Promise<boolean> { |
| 609 | const projectWorkers = workers.get(projectId) || []; |
| 610 | const workerCount = projectWorkers.length; |
| 611 | if (workerCount === 0) { |
| 612 | return true; |
| 613 | } |
| 614 | const results = await Promise.all( |
| 615 | projectWorkers.map(async (workerAddress) => { |
| 616 | const resp = await axios.post(`${workerAddress}/update`); |
| 617 | return resp.status === 200; |
| 618 | }), |
| 619 | ); |
| 620 | return results.reduce((acc, curr) => acc && curr, true); |
| 621 | } |
| 622 | |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 623 | const handleReload: express.Handler = async (req, resp) => { |
| 624 | try { |
| 625 | const projectId = Number(req.params["projectId"]); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 626 | const projectAuth = await db.project.findFirst({ |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 627 | where: { |
| 628 | id: projectId, |
| 629 | userId: resp.locals.userId, |
| 630 | }, |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 631 | select: { id: true }, |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 632 | }); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 633 | if (!projectAuth) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 634 | resp.status(404); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 635 | return; |
| 636 | } |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 637 | const success = await reloadProject(projectId); |
| 638 | if (success) { |
| 639 | resp.status(200); |
| 640 | } else { |
| 641 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 642 | } |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 643 | } catch (e) { |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 644 | console.error(e); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 645 | resp.status(500); |
| gio | 7d81370 | 2025-05-08 18:29:52 +0000 | [diff] [blame] | 646 | } |
| 647 | }; |
| 648 | |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 649 | const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => { |
| 650 | const userId = req.get("x-forwarded-userid"); |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 651 | const username = req.get("x-forwarded-user"); |
| 652 | if (userId == null || username == null) { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 653 | resp.status(401); |
| 654 | resp.write("Unauthorized"); |
| 655 | resp.end(); |
| 656 | return; |
| 657 | } |
| 658 | resp.locals.userId = userId; |
| gio | 3ed5959 | 2025-05-14 16:51:09 +0000 | [diff] [blame] | 659 | resp.locals.username = username; |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 660 | next(); |
| 661 | }; |
| 662 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 663 | const handleGithubPushWebhook: express.Handler = async (req, resp) => { |
| 664 | try { |
| 665 | // TODO(gio): Implement GitHub signature verification for security |
| 666 | const webhookSchema = z.object({ |
| 667 | repository: z.object({ |
| 668 | ssh_url: z.string(), |
| 669 | }), |
| 670 | }); |
| 671 | |
| 672 | const result = webhookSchema.safeParse(req.body); |
| 673 | if (!result.success) { |
| 674 | console.warn("GitHub webhook: Invalid payload:", result.error.issues); |
| 675 | resp.status(400).json({ error: "Invalid webhook payload" }); |
| 676 | return; |
| 677 | } |
| 678 | const { ssh_url: addr } = result.data.repository; |
| 679 | const allProjects = await db.project.findMany({ |
| 680 | select: { |
| 681 | id: true, |
| 682 | state: true, |
| 683 | }, |
| 684 | where: { |
| 685 | instanceId: { |
| 686 | not: null, |
| 687 | }, |
| 688 | }, |
| 689 | }); |
| 690 | // TODO(gio): This should run in background |
| 691 | new Promise<boolean>((resolve, reject) => { |
| 692 | setTimeout(() => { |
| 693 | const projectsToReloadIds: number[] = []; |
| 694 | for (const project of allProjects) { |
| 695 | if (project.state && project.state.length > 0) { |
| 696 | const projectRepos = extractGithubRepos(project.state); |
| 697 | if (projectRepos.includes(addr)) { |
| 698 | projectsToReloadIds.push(project.id); |
| 699 | } |
| 700 | } |
| 701 | } |
| 702 | Promise.all(projectsToReloadIds.map((id) => reloadProject(id))) |
| 703 | .then((results) => { |
| 704 | resolve(results.reduce((acc, curr) => acc && curr, true)); |
| 705 | }) |
| 706 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 707 | .catch((reason: any) => reject(reason)); |
| 708 | }, 10); |
| 709 | }); |
| 710 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 711 | } catch (error: any) { |
| 712 | console.error(error); |
| 713 | resp.status(500); |
| 714 | } |
| 715 | }; |
| 716 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 717 | async function start() { |
| 718 | await db.$connect(); |
| 719 | const app = express(); |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 720 | app.use(express.json()); // Global JSON parsing |
| 721 | |
| 722 | // Public webhook route - no auth needed |
| 723 | app.post("/api/webhook/github/push", handleGithubPushWebhook); |
| 724 | |
| 725 | // Authenticated project routes |
| 726 | const projectRouter = express.Router(); |
| 727 | projectRouter.use(auth); // Apply auth middleware to this router |
| 728 | projectRouter.post("/:projectId/saved", handleSave); |
| 729 | projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy")); |
| 730 | projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft")); |
| 731 | projectRouter.post("/:projectId/deploy", handleDeploy); |
| 732 | projectRouter.get("/:projectId/status", handleStatus); |
| 733 | projectRouter.delete("/:projectId", handleDelete); |
| 734 | projectRouter.get("/:projectId/repos/github", handleGithubRepos); |
| 735 | projectRouter.post("/:projectId/github-token", handleUpdateGithubToken); |
| 736 | projectRouter.get("/:projectId/env", handleEnv); |
| 737 | projectRouter.post("/:projectId/reload", handleReload); |
| 738 | projectRouter.get("/:projectId/logs/:service", handleServiceLogs); |
| 739 | projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment); |
| 740 | projectRouter.get("/", handleProjectAll); |
| 741 | projectRouter.post("/", handleProjectCreate); |
| 742 | app.use("/api/project", projectRouter); // Mount the authenticated router |
| 743 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 744 | app.use("/", express.static("../front/dist")); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 745 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 746 | const internalApi = express(); |
| 747 | internalApi.use(express.json()); |
| 748 | internalApi.post("/api/project/:projectId/workers", handleRegisterWorker); |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 749 | |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 750 | app.listen(env.DODO_PORT_WEB, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 751 | console.log("Web server started on port", env.DODO_PORT_WEB); |
| 752 | }); |
| 753 | |
| gio | 76d8ae6 | 2025-05-19 15:21:54 +0000 | [diff] [blame^] | 754 | internalApi.listen(env.DODO_PORT_API, () => { |
| gio | 09fcab5 | 2025-05-12 14:05:07 +0000 | [diff] [blame] | 755 | console.log("Internal API server started on port", env.DODO_PORT_API); |
| gio | d002661 | 2025-05-08 13:00:36 +0000 | [diff] [blame] | 756 | }); |
| 757 | } |
| 758 | |
| 759 | start(); |