CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history
events.ts
Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.
| 9e1e93a | 1 | /** |
| 2 | * Inbound deploy-event receiver for Crontech (Signal Bus P1 — E3/E4). | |
| 3 | * | |
| 4 | * Wire contract reference: chat-defined spec for Crontech → Gluecron deploy | |
| 5 | * events. Gluecron's OWN copy per HTTP-only coupling rule — do NOT import any | |
| 6 | * types from Crontech. If the contract is renegotiated, update this comment | |
| 7 | * and the validation below in lock-step. | |
| 8 | * | |
| 9 | * POST /api/events/deploy | |
| 10 | * Authorization: Bearer ${CRONTECH_EVENT_TOKEN} | |
| 11 | * Content-Type: application/json | |
| 12 | * | |
| 13 | * { | |
| 14 | * "event": "deploy.succeeded" | "deploy.failed", | |
| 15 | * "eventId": "<uuid-v4>", // idempotency key | |
| 16 | * "repository": "owner/name", | |
| 17 | * "sha": "<40-hex>", | |
| 18 | * "environment": "production", | |
| 19 | * "deploymentId": "<crontech-id>", | |
| 20 | * "durationMs": <int>, // optional | |
| 21 | * "errorCategory": "build|runtime|timeout|config", // required on failed | |
| 22 | * "errorSummary": "<string ≤500>", // required on failed | |
| 23 | * "logsUrl": "<string>", // optional | |
| 24 | * "timestamp": "<ISO-8601>" | |
| 25 | * } | |
| 26 | * | |
| 27 | * → 200 { ok: true, duplicate: false } | |
| 28 | * → 200 { ok: true, duplicate: true } | |
| 29 | * → 401 invalid bearer | |
| 30 | * → 400 malformed payload | |
| 31 | * | |
| 32 | * Idempotency: an incoming `eventId` is first looked up in `processed_events`. | |
| 33 | * On hit we return { duplicate: true } immediately — no side-effects. On miss | |
| 34 | * we INSERT the idempotency record BEFORE performing the side-effect update so | |
| 35 | * that a retry after a crash between steps sees the record and short-circuits. | |
| 36 | * | |
| 37 | * Side-effect: look up the matching `deployments` row by | |
| 38 | * (repository_id, commit_sha, environment) — `deployments` has no | |
| 39 | * `crontech_deployment_id` column so we key off the tuple that | |
| 40 | * `triggerCrontechDeploy` writes on the way out. | |
| 41 | * | |
| 42 | * E3 deploy.succeeded → status='success', completedAt=now | |
| 43 | * E4 deploy.failed → status='failed', blockedReason=errorSummary, | |
| 44 | * completedAt=now, notify(owner, 'deploy_failed') | |
| 45 | */ | |
| 46 | ||
| 47 | import { Hono } from "hono"; | |
| 48 | import { and, desc, eq } from "drizzle-orm"; | |
| 49 | import { timingSafeEqual } from "crypto"; | |
| 50 | import { db } from "../db"; | |
| 51 | import { deployments, repositories, users } from "../db/schema"; | |
| 52 | import { processedEvents } from "../db/schema-events"; | |
| 53 | import { notify } from "../lib/notify"; | |
| 54 | ||
| 55 | const events = new Hono(); | |
| 56 | ||
| 57 | // --------------------------------------------------------------------------- | |
| 58 | // Bearer auth — timing-safe comparison against CRONTECH_EVENT_TOKEN. | |
| 59 | // --------------------------------------------------------------------------- | |
| 60 | ||
| 61 | function constantTimeEq(a: string, b: string): boolean { | |
| 62 | const A = Buffer.from(a); | |
| 63 | const B = Buffer.from(b); | |
| 64 | if (A.length !== B.length) return false; | |
| 65 | try { | |
| 66 | return timingSafeEqual(A, B); | |
| 67 | } catch { | |
| 68 | return false; | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | function verifyBearer(c: any): { ok: boolean; error?: string } { | |
| 73 | const expected = process.env.CRONTECH_EVENT_TOKEN || ""; | |
| 74 | if (!expected) { | |
| 75 | // Refuse by default — an unset secret must NOT allow anonymous writes. | |
| 76 | return { | |
| 77 | ok: false, | |
| 78 | error: | |
| 79 | "Event endpoint not configured: set CRONTECH_EVENT_TOKEN in the environment", | |
| 80 | }; | |
| 81 | } | |
| 82 | const auth = c.req.header("authorization") || ""; | |
| 83 | if (!auth.startsWith("Bearer ")) { | |
| 84 | return { ok: false, error: "Missing Bearer token" }; | |
| 85 | } | |
| 86 | const token = auth.slice(7).trim(); | |
| 87 | if (!constantTimeEq(token, expected)) { | |
| 88 | return { ok: false, error: "Invalid bearer token" }; | |
| 89 | } | |
| 90 | return { ok: true }; | |
| 91 | } | |
| 92 | ||
| 93 | // --------------------------------------------------------------------------- | |
| 94 | // Payload validation — no zod in this repo, use manual checks mirroring the | |
| 95 | // existing hooks.ts style. Keep error messages specific enough to diagnose a | |
| 96 | // mis-built emitter without leaking internals. | |
| 97 | // --------------------------------------------------------------------------- | |
| 98 | ||
| 99 | type DeployEvent = "deploy.succeeded" | "deploy.failed"; | |
| 100 | type ErrorCategory = "build" | "runtime" | "timeout" | "config"; | |
| 101 | ||
| 102 | interface DeployEventPayload { | |
| 103 | event: DeployEvent; | |
| 104 | eventId: string; | |
| 105 | repository: string; | |
| 106 | sha: string; | |
| 107 | environment: string; | |
| 108 | deploymentId: string; | |
| 109 | durationMs?: number; | |
| 110 | errorCategory?: ErrorCategory; | |
| 111 | errorSummary?: string; | |
| 112 | logsUrl?: string; | |
| 113 | timestamp: string; | |
| 114 | } | |
| 115 | ||
| 116 | const UUID_V4_RE = | |
| 117 | /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | |
| 118 | const SHA_RE = /^[0-9a-f]{40}$/i; | |
| 119 | const VALID_EVENTS: ReadonlySet<string> = new Set([ | |
| 120 | "deploy.succeeded", | |
| 121 | "deploy.failed", | |
| 122 | ]); | |
| 123 | const VALID_CATEGORIES: ReadonlySet<string> = new Set([ | |
| 124 | "build", | |
| 125 | "runtime", | |
| 126 | "timeout", | |
| 127 | "config", | |
| 128 | ]); | |
| 129 | ||
| 130 | function validatePayload(raw: unknown): { | |
| 131 | ok: true; | |
| 132 | payload: DeployEventPayload; | |
| 133 | } | { ok: false; error: string } { | |
| 134 | if (!raw || typeof raw !== "object") { | |
| 135 | return { ok: false, error: "Body must be a JSON object" }; | |
| 136 | } | |
| 137 | const p = raw as Record<string, unknown>; | |
| 138 | ||
| 139 | if (typeof p.event !== "string" || !VALID_EVENTS.has(p.event)) { | |
| 140 | return { | |
| 141 | ok: false, | |
| 142 | error: "event must be 'deploy.succeeded' or 'deploy.failed'", | |
| 143 | }; | |
| 144 | } | |
| 145 | if (typeof p.eventId !== "string" || !UUID_V4_RE.test(p.eventId)) { | |
| 146 | return { ok: false, error: "eventId must be a uuid-v4 string" }; | |
| 147 | } | |
| 148 | if (typeof p.repository !== "string" || !p.repository.includes("/")) { | |
| 149 | return { ok: false, error: "repository must be '<owner>/<name>'" }; | |
| 150 | } | |
| 151 | if (typeof p.sha !== "string" || !SHA_RE.test(p.sha)) { | |
| 152 | return { ok: false, error: "sha must be a 40-hex commit id" }; | |
| 153 | } | |
| 154 | if (typeof p.environment !== "string" || p.environment.length === 0) { | |
| 155 | return { ok: false, error: "environment must be a non-empty string" }; | |
| 156 | } | |
| 157 | if (typeof p.deploymentId !== "string" || p.deploymentId.length === 0) { | |
| 158 | return { ok: false, error: "deploymentId must be a non-empty string" }; | |
| 159 | } | |
| 160 | if (typeof p.timestamp !== "string" || Number.isNaN(Date.parse(p.timestamp))) { | |
| 161 | return { ok: false, error: "timestamp must be an ISO-8601 string" }; | |
| 162 | } | |
| 163 | if (p.durationMs !== undefined) { | |
| 164 | if ( | |
| 165 | typeof p.durationMs !== "number" || | |
| 166 | !Number.isFinite(p.durationMs) || | |
| 167 | p.durationMs < 0 | |
| 168 | ) { | |
| 169 | return { ok: false, error: "durationMs must be a non-negative number" }; | |
| 170 | } | |
| 171 | } | |
| 172 | if (p.logsUrl !== undefined && typeof p.logsUrl !== "string") { | |
| 173 | return { ok: false, error: "logsUrl must be a string when present" }; | |
| 174 | } | |
| 175 | ||
| 176 | if (p.event === "deploy.failed") { | |
| 177 | if ( | |
| 178 | typeof p.errorCategory !== "string" || | |
| 179 | !VALID_CATEGORIES.has(p.errorCategory) | |
| 180 | ) { | |
| 181 | return { | |
| 182 | ok: false, | |
| 183 | error: | |
| 184 | "errorCategory is required for deploy.failed and must be one of build|runtime|timeout|config", | |
| 185 | }; | |
| 186 | } | |
| 187 | if ( | |
| 188 | typeof p.errorSummary !== "string" || | |
| 189 | p.errorSummary.length === 0 || | |
| 190 | p.errorSummary.length > 500 | |
| 191 | ) { | |
| 192 | return { | |
| 193 | ok: false, | |
| 194 | error: | |
| 195 | "errorSummary is required for deploy.failed and must be 1-500 chars", | |
| 196 | }; | |
| 197 | } | |
| 198 | } | |
| 199 | ||
| 200 | return { ok: true, payload: p as unknown as DeployEventPayload }; | |
| 201 | } | |
| 202 | ||
| 203 | // --------------------------------------------------------------------------- | |
| 204 | // Helpers | |
| 205 | // --------------------------------------------------------------------------- | |
| 206 | ||
| 207 | async function resolveRepo( | |
| 208 | full: string | |
| 209 | ): Promise<{ id: string; ownerId: string } | null> { | |
| 210 | if (!full.includes("/")) return null; | |
| 211 | const [owner, name] = full.split("/", 2); | |
| 212 | try { | |
| 213 | const [row] = await db | |
| 214 | .select({ | |
| 215 | id: repositories.id, | |
| 216 | ownerId: repositories.ownerId, | |
| 217 | }) | |
| 218 | .from(repositories) | |
| 219 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 220 | .where(and(eq(users.username, owner), eq(repositories.name, name))) | |
| 221 | .limit(1); | |
| 222 | return row || null; | |
| 223 | } catch { | |
| 224 | return null; | |
| 225 | } | |
| 226 | } | |
| 227 | ||
| 228 | async function findTargetDeployment( | |
| 229 | repositoryId: string, | |
| 230 | commitSha: string, | |
| 231 | environment: string | |
| 232 | ): Promise<{ id: string } | null> { | |
| 233 | try { | |
| 234 | const [row] = await db | |
| 235 | .select({ id: deployments.id }) | |
| 236 | .from(deployments) | |
| 237 | .where( | |
| 238 | and( | |
| 239 | eq(deployments.repositoryId, repositoryId), | |
| 240 | eq(deployments.commitSha, commitSha), | |
| 241 | eq(deployments.environment, environment) | |
| 242 | ) | |
| 243 | ) | |
| 244 | .orderBy(desc(deployments.createdAt)) | |
| 245 | .limit(1); | |
| 246 | return row || null; | |
| 247 | } catch { | |
| 248 | return null; | |
| 249 | } | |
| 250 | } | |
| 251 | ||
| 252 | // --------------------------------------------------------------------------- | |
| 253 | // POST /api/events/deploy | |
| 254 | // --------------------------------------------------------------------------- | |
| 255 | ||
| 256 | events.post("/deploy", async (c) => { | |
| 257 | const auth = verifyBearer(c); | |
| 258 | if (!auth.ok) { | |
| 259 | return c.json({ ok: false, error: auth.error || "Unauthorized" }, 401); | |
| 260 | } | |
| 261 | ||
| 262 | let raw: unknown; | |
| 263 | try { | |
| 264 | raw = await c.req.json(); | |
| 265 | } catch { | |
| 266 | return c.json({ ok: false, error: "Invalid JSON body" }, 400); | |
| 267 | } | |
| 268 | ||
| 269 | const validated = validatePayload(raw); | |
| 270 | if (!validated.ok) { | |
| 271 | return c.json({ ok: false, error: validated.error }, 400); | |
| 272 | } | |
| 273 | const payload = validated.payload; | |
| 274 | ||
| 275 | // --- Idempotency check --------------------------------------------------- | |
| 276 | // If we've already processed this eventId, return duplicate:true without | |
| 277 | // firing any side-effects. | |
| 278 | try { | |
| 279 | const [existing] = await db | |
| 280 | .select({ id: processedEvents.id }) | |
| 281 | .from(processedEvents) | |
| 282 | .where(eq(processedEvents.eventId, payload.eventId)) | |
| 283 | .limit(1); | |
| 284 | if (existing) { | |
| 285 | return c.json({ ok: true, duplicate: true }); | |
| 286 | } | |
| 287 | } catch (err) { | |
| 288 | console.error("[events/deploy] idempotency lookup failed:", err); | |
| 289 | // Fall through — better to process than to wedge on a transient DB blip. | |
| 290 | } | |
| 291 | ||
| 292 | // --- Record the idempotency token BEFORE side-effects -------------------- | |
| 293 | // Race: two simultaneous deliveries of the same eventId. The UNIQUE | |
| 294 | // constraint on event_id makes the losing insert throw; we catch that and | |
| 295 | // return duplicate:true to keep behaviour stable. | |
| 296 | try { | |
| 297 | await db.insert(processedEvents).values({ | |
| 298 | eventId: payload.eventId, | |
| 299 | eventType: payload.event, | |
| 300 | source: "crontech", | |
| 301 | payload: payload as unknown as Record<string, unknown>, | |
| 302 | }); | |
| 303 | } catch (err) { | |
| 304 | const msg = err instanceof Error ? err.message : String(err); | |
| 305 | if (msg.includes("unique") || msg.includes("duplicate")) { | |
| 306 | return c.json({ ok: true, duplicate: true }); | |
| 307 | } | |
| 308 | console.error("[events/deploy] processed_events insert failed:", err); | |
| 309 | return c.json({ ok: false, error: "Failed to persist event" }, 500); | |
| 310 | } | |
| 311 | ||
| 312 | // --- Side-effect: update the matching deployments row -------------------- | |
| 313 | const repo = await resolveRepo(payload.repository); | |
| 314 | if (!repo) { | |
| 315 | // The idempotency row is already committed; we accept the event so we | |
| 316 | // don't invite infinite retries for a repo that genuinely doesn't exist | |
| 317 | // on this side of the wire. Log for operator follow-up. | |
| 318 | console.warn( | |
| 319 | `[events/deploy] unknown repository ${payload.repository} — event ${payload.eventId} accepted but no deployment update applied` | |
| 320 | ); | |
| 321 | return c.json({ ok: true, duplicate: false }); | |
| 322 | } | |
| 323 | ||
| 324 | const target = await findTargetDeployment( | |
| 325 | repo.id, | |
| 326 | payload.sha, | |
| 327 | payload.environment | |
| 328 | ); | |
| 329 | ||
| 330 | if (target) { | |
| 331 | try { | |
| 332 | if (payload.event === "deploy.succeeded") { | |
| 333 | await db | |
| 334 | .update(deployments) | |
| 335 | .set({ | |
| 336 | status: "success", | |
| 337 | completedAt: new Date(), | |
| 338 | }) | |
| 339 | .where(eq(deployments.id, target.id)); | |
| 340 | } else { | |
| 341 | await db | |
| 342 | .update(deployments) | |
| 343 | .set({ | |
| 344 | status: "failed", | |
| 345 | blockedReason: payload.errorSummary, | |
| 346 | completedAt: new Date(), | |
| 347 | }) | |
| 348 | .where(eq(deployments.id, target.id)); | |
| 349 | } | |
| 350 | } catch (err) { | |
| 351 | console.error("[events/deploy] deployments update failed:", err); | |
| 352 | } | |
| 353 | } else { | |
| 354 | console.warn( | |
| 355 | `[events/deploy] no deployments row found for ${payload.repository}@${payload.sha} env=${payload.environment}` | |
| 356 | ); | |
| 357 | } | |
| 358 | ||
| 359 | // --- On failure: notify the repo owner ---------------------------------- | |
| 360 | if (payload.event === "deploy.failed") { | |
| 361 | try { | |
| 362 | await notify(repo.ownerId, { | |
| 363 | kind: "deploy_failed", | |
| 364 | title: `Deploy failed on ${payload.repository}`, | |
| 365 | body: | |
| 366 | payload.errorSummary || | |
| 367 | `Crontech reported deploy failure (${payload.errorCategory || "unknown"})`, | |
| 368 | url: payload.logsUrl, | |
| 369 | repositoryId: repo.id, | |
| 370 | }); | |
| 371 | } catch (err) { | |
| 372 | console.error("[events/deploy] notify failed:", err); | |
| 373 | } | |
| 374 | } | |
| 375 | ||
| 376 | return c.json({ ok: true, duplicate: false }); | |
| 377 | }); | |
| 378 | ||
| 379 | // Test-only access for unit tests that want to exercise helpers directly. | |
| 380 | export const __test = { | |
| 381 | constantTimeEq, | |
| 382 | validatePayload, | |
| 383 | resolveRepo, | |
| 384 | findTargetDeployment, | |
| 385 | }; | |
| 386 | ||
| 387 | export default events; |