CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | /**
* Per-branch preview URLs (migration 0062).
*
* Every push to a non-default branch enqueues a "preview build" row.
* For v1 the row + URL are the deliverable — actual hosting (Caddy /
* nginx vhost provisioning, container spin-up) is a follow-up. The
* preview URL is computed deterministically from the branch and repo
* names so it can be shown immediately, even while the build is still
* in flight or, in the no-hosting case, forever.
*
* URL pattern:
*
* https://${branchSlug}-${repoSlug}.preview.gluecron.com
*
* The domain suffix is configurable via the `PREVIEW_DOMAIN` env var so
* self-hosted installs can swap it for their own wildcard subdomain
* (e.g. `*.preview.acme.dev`). Owner and repo are slug-encoded so that
* branch names containing `/` (e.g. `feat/foo`) collapse safely into a
* single hostname label.
*
* Philosophy (mirrors workflow-runner.ts / post-receive.ts): never
* throw — every DB call is wrapped in try/catch so a Postgres outage
* cannot break the push path. Callers fire-and-forget.
*/
import { and, eq, lt } from "drizzle-orm";
import { db } from "../db";
import { branchPreviews, type BranchPreview } from "../db/schema";
/** TTL since the last push to the branch. */
const PREVIEW_TTL_MS = 24 * 60 * 60 * 1000;
/**
* Slugify a string into a single DNS label.
* - lowercase
* - replace any non-alphanumeric run with `-`
* - strip leading/trailing `-`
* - clip to 50 chars (RFC 1035 says a label is <= 63; we leave headroom
* so the joined "${branch}-${repo}" still fits under 63 in most cases)
*
* Exported for tests + UI helpers.
*/
export function slugifyForUrl(value: string): string {
return (value || "")
.toString()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 50);
}
/**
* Compute the preview URL for `<owner>/<repo>@<branch>`. Pure — exported
* so route handlers + the UI can render it without going through the DB.
*/
export function buildPreviewUrl(
ownerName: string,
repoName: string,
branchName: string
): string {
const domain = (process.env.PREVIEW_DOMAIN || "preview.gluecron.com").replace(
/^https?:\/\//,
""
);
const repoSlug = slugifyForUrl(`${ownerName}-${repoName}`);
const branchSlug = slugifyForUrl(branchName) || "branch";
return `https://${branchSlug}-${repoSlug}.${domain}`;
}
export interface EnqueueArgs {
repositoryId: string;
ownerName: string;
repoName: string;
branchName: string;
commitSha: string;
/** Override the computed URL — only used by tests. */
previewUrl?: string;
/** Override the "now" clock — only used by tests. */
now?: () => Date;
}
/**
* Upsert a preview-build row for the given branch.
*
* Pushing the same branch again replaces commit_sha, bumps
* build_started_at, resets status to 'building', and clears any prior
* error_message. The unique index on (repository_id, branch_name)
* guarantees there's exactly one row per branch.
*
* Returns the inserted/updated row, or `null` if the DB is unavailable
* or the underlying table is missing (graceful no-op).
*/
export async function enqueuePreviewBuild(
args: EnqueueArgs
): Promise<BranchPreview | null> {
if (!args.repositoryId || !args.branchName || !args.commitSha) return null;
const now = (args.now ?? (() => new Date()))();
const expiresAt = new Date(now.getTime() + PREVIEW_TTL_MS);
const url =
args.previewUrl ??
buildPreviewUrl(args.ownerName, args.repoName, args.branchName);
try {
const [row] = await db
.insert(branchPreviews)
.values({
repositoryId: args.repositoryId,
branchName: args.branchName,
commitSha: args.commitSha,
previewUrl: url,
status: "building",
buildStartedAt: now,
buildCompletedAt: null,
expiresAt,
errorMessage: null,
})
.onConflictDoUpdate({
target: [branchPreviews.repositoryId, branchPreviews.branchName],
set: {
commitSha: args.commitSha,
previewUrl: url,
status: "building",
buildStartedAt: now,
buildCompletedAt: null,
expiresAt,
errorMessage: null,
},
})
.returning();
return row ?? null;
} catch (err) {
console.warn(
"[branch-previews] enqueue failed:",
err instanceof Error ? err.message : err
);
return null;
}
}
/**
* Look up the current preview row for `repo/branch`, or null if there
* isn't one. Used by the /previews list page + the PR detail pill.
*/
export async function getPreviewForBranch(
repositoryId: string,
branchName: string
): Promise<BranchPreview | null> {
if (!repositoryId || !branchName) return null;
try {
const [row] = await db
.select()
.from(branchPreviews)
.where(
and(
eq(branchPreviews.repositoryId, repositoryId),
eq(branchPreviews.branchName, branchName)
)
)
.limit(1);
return row ?? null;
} catch {
return null;
}
}
/**
* Mark a preview as successfully built. `previewUrl` is optional — the
* URL is already recorded at enqueue time, but a hoster can update it
* here if it picked a different host (e.g. promoted to a custom domain).
*/
export async function markPreviewReady(
id: string,
previewUrl?: string,
now: () => Date = () => new Date()
): Promise<void> {
if (!id) return;
try {
await db
.update(branchPreviews)
.set({
status: "ready",
buildCompletedAt: now(),
errorMessage: null,
...(previewUrl ? { previewUrl } : {}),
})
.where(eq(branchPreviews.id, id));
} catch (err) {
console.warn(
"[branch-previews] markReady failed:",
err instanceof Error ? err.message : err
);
}
}
/**
* Mark a preview as failed and record the error. `error` is truncated
* to avoid blowing up the row on very large stack traces.
*/
export async function markPreviewFailed(
id: string,
error: string,
now: () => Date = () => new Date()
): Promise<void> {
if (!id) return;
try {
await db
.update(branchPreviews)
.set({
status: "failed",
buildCompletedAt: now(),
errorMessage: (error || "").slice(0, 2_000),
})
.where(eq(branchPreviews.id, id));
} catch (err) {
console.warn(
"[branch-previews] markFailed failed:",
err instanceof Error ? err.message : err
);
}
}
/**
* Autopilot task: flip every active row whose `expires_at` is in the
* past to status='expired'. Already-expired/failed rows are not
* re-touched so the autopilot loop is cheap to run hourly. Returns the
* number of rows transitioned for observability.
*/
export async function expireOldPreviews(
now: () => Date = () => new Date()
): Promise<number> {
try {
const rows = await db
.update(branchPreviews)
.set({ status: "expired" })
.where(
and(
lt(branchPreviews.expiresAt, now()),
// Only flip non-terminal-but-non-expired rows. We keep `failed`
// as-is so users still see why the last build failed.
eq(branchPreviews.status, "ready")
)
)
.returning({ id: branchPreviews.id });
// Also expire still-building rows that have been stuck past the TTL.
const stuck = await db
.update(branchPreviews)
.set({ status: "expired" })
.where(
and(
lt(branchPreviews.expiresAt, now()),
eq(branchPreviews.status, "building")
)
)
.returning({ id: branchPreviews.id });
return rows.length + stuck.length;
} catch (err) {
console.warn(
"[branch-previews] expireOldPreviews failed:",
err instanceof Error ? err.message : err
);
return 0;
}
}
/**
* List every preview row for a repo, newest first by build_started_at.
* Used by the /previews list page + the JSON API.
*/
export async function listPreviewsForRepo(
repositoryId: string,
limit = 100
): Promise<BranchPreview[]> {
if (!repositoryId) return [];
try {
const rows = await db
.select()
.from(branchPreviews)
.where(eq(branchPreviews.repositoryId, repositoryId))
.limit(Math.max(1, Math.min(500, limit)));
// Sort in JS — the table is tiny per-repo, no need for an extra index.
rows.sort((a, b) => {
const at = a.buildStartedAt?.getTime?.() ?? 0;
const bt = b.buildStartedAt?.getTime?.() ?? 0;
return bt - at;
});
return rows;
} catch {
return [];
}
}
/**
* Compute a human-readable "expires in" label like "23h 14m" / "less
* than a minute" / "expired". Pure — used by the list view + API.
*/
export function formatExpiresIn(
expiresAt: Date | null | undefined,
now: Date = new Date()
): string {
if (!expiresAt) return "—";
const ms = expiresAt.getTime() - now.getTime();
if (ms <= 0) return "expired";
const minutes = Math.floor(ms / 60_000);
if (minutes < 1) return "less than a minute";
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours <= 0) return `${minutes}m`;
return `${hours}h ${mins}m`;
}
/** Visible string for the status pill. */
export function previewStatusLabel(status: string): string {
switch (status) {
case "building":
return "Building";
case "ready":
return "Ready";
case "failed":
return "Failed";
case "expired":
return "Expired";
default:
return status;
}
}
|