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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
import { and, desc, eq, isNotNull, lte, sql } from "drizzle-orm";
import { db } from "../db";
import {
environments,
deploymentApprovals,
deployments,
repositories,
} from "../db/schema";
import type { Environment, DeploymentApproval } from "../db/schema";
function normaliseRef(ref: string): string {
if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
if (ref.startsWith("refs/tags/")) return ref.slice("refs/tags/".length);
return ref;
}
export function matchGlob(value: string, pattern: string): boolean {
const v = normaliseRef(value);
const p = normaliseRef(pattern);
if (v === p) return true;
const re = p
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*\*/g, "::DOUBLESTAR::")
.replace(/\*/g, "[^/]*")
.replace(/::DOUBLESTAR::/g, ".*");
return new RegExp(`^${re}$`).test(v);
}
function matchesAny(value: string, patterns: string[]): boolean {
if (patterns.length === 0) return true;
return patterns.some((p) => matchGlob(value, p));
}
export async function listEnvironments(
repositoryId: string
): Promise<Environment[]> {
try {
return await db
.select()
.from(environments)
.where(eq(environments.repositoryId, repositoryId))
.orderBy(desc(environments.createdAt));
} catch (err) {
console.error("[environments] list failed:", err);
return [];
}
}
export async function getEnvironmentById(
repositoryId: string,
id: string
): Promise<Environment | null> {
try {
const [row] = await db
.select()
.from(environments)
.where(
and(eq(environments.id, id), eq(environments.repositoryId, repositoryId))
)
.limit(1);
return row || null;
} catch (err) {
console.error("[environments] getById failed:", err);
return null;
}
}
export async function getEnvironmentByName(
repositoryId: string,
name: string
): Promise<Environment | null> {
try {
const [row] = await db
.select()
.from(environments)
.where(
and(
eq(environments.repositoryId, repositoryId),
eq(environments.name, name)
)
)
.limit(1);
return row || null;
} catch (err) {
console.error("[environments] getByName failed:", err);
return null;
}
}
export async function getOrCreateEnvironment(
repositoryId: string,
name: string
): Promise<Environment> {
const existing = await getEnvironmentByName(repositoryId, name);
if (existing) return existing;
try {
const [inserted] = await db
.insert(environments)
.values({ repositoryId, name })
.returning();
if (inserted) return inserted;
} catch (err) {
console.error("[environments] create failed:", err);
}
const reread = await getEnvironmentByName(repositoryId, name);
if (reread) return reread;
return {
id: "",
repositoryId,
name,
requireApproval: false,
reviewers: "[]",
waitTimerMinutes: 0,
allowedBranches: "[]",
createdAt: new Date(),
updatedAt: new Date(),
} as Environment;
}
function parseJsonArray(raw: string | null | undefined): string[] {
if (!raw) return [];
try {
const v = JSON.parse(raw);
return Array.isArray(v) ? v.map(String) : [];
} catch {
return [];
}
}
export function reviewerIdsOf(env: Environment): string[] {
return parseJsonArray(env.reviewers);
}
export function allowedBranchesOf(env: Environment): string[] {
return parseJsonArray(env.allowedBranches);
}
export async function isReviewer(
env: Environment,
userId: string
): Promise<boolean> {
const reviewers = reviewerIdsOf(env);
if (reviewers.includes(userId)) return true;
if (reviewers.length === 0) {
try {
const [row] = await db
.select({ ownerId: repositories.ownerId })
.from(repositories)
.where(eq(repositories.id, env.repositoryId))
.limit(1);
return row?.ownerId === userId;
} catch (err) {
console.error("[environments] isReviewer owner lookup failed:", err);
return false;
}
}
return false;
}
export async function listApprovals(
deploymentId: string
): Promise<DeploymentApproval[]> {
try {
return await db
.select()
.from(deploymentApprovals)
.where(eq(deploymentApprovals.deploymentId, deploymentId))
.orderBy(desc(deploymentApprovals.createdAt));
} catch (err) {
console.error("[environments] listApprovals failed:", err);
return [];
}
}
export function reduceApprovalState(decided: DeploymentApproval[]): {
approved: boolean;
rejected: boolean;
decided: DeploymentApproval[];
} {
const rejected = decided.some((d) => d.decision === "rejected");
const approved = !rejected && decided.some((d) => d.decision === "approved");
return { approved, rejected, decided };
}
export function latestApprovalAt(
decided: DeploymentApproval[]
): Date | null {
let latest: Date | null = null;
for (const d of decided) {
if (d.decision !== "approved") continue;
const t = d.createdAt ? new Date(d.createdAt) : null;
if (!t || isNaN(t.getTime())) continue;
if (!latest || t.getTime() > latest.getTime()) latest = t;
}
return latest;
}
export function computeReadyAfter(
env: Pick<Environment, "waitTimerMinutes">,
decided: DeploymentApproval[]
): Date | null {
const minutes = Number(env.waitTimerMinutes || 0);
if (!Number.isFinite(minutes) || minutes <= 0) return null;
const last = latestApprovalAt(decided);
if (!last) return null;
return new Date(last.getTime() + minutes * 60_000);
}
export async function computeApprovalState(
deploymentId: string,
env: Environment
): Promise<{
approved: boolean;
rejected: boolean;
decided: DeploymentApproval[];
readyAfter: Date | null;
}> {
const decided = await listApprovals(deploymentId);
const base = reduceApprovalState(decided);
const readyAfter = base.approved ? computeReadyAfter(env, decided) : null;
return { ...base, readyAfter };
}
export async function recordApproval(opts: {
deploymentId: string;
userId: string;
decision: "approved" | "rejected";
comment?: string;
}): Promise<DeploymentApproval | null> {
try {
const [row] = await db
.insert(deploymentApprovals)
.values({
deploymentId: opts.deploymentId,
userId: opts.userId,
decision: opts.decision,
comment: opts.comment ?? null,
})
.returning();
return row || null;
} catch (err) {
console.error("[environments] recordApproval failed:", err);
return null;
}
}
export async function requiresApprovalFor(
repositoryId: string,
envName: string,
ref: string
): Promise<{ required: boolean; env: Environment | null }> {
const env = await getEnvironmentByName(repositoryId, envName);
if (!env) return { required: false, env: null };
const allowed = allowedBranchesOf(env);
if (allowed.length > 0 && !matchesAny(ref, allowed)) {
return { required: true, env };
}
if (env.requireApproval) return { required: true, env };
return { required: false, env };
}
export async function releaseExpiredWaitTimers(
now: Date = new Date()
): Promise<number> {
try {
const rows = await db
.update(deployments)
.set({ status: "pending" })
.where(
and(
eq(deployments.status, "waiting_timer"),
isNotNull(deployments.readyAfter),
lte(deployments.readyAfter, sql`${now.toISOString()}::timestamptz`)
)
)
.returning({ id: deployments.id });
return rows ? rows.length : 0;
} catch (err) {
console.error("[environments] releaseExpiredWaitTimers failed:", err);
return 0;
}
}
export const __test = {
latestApprovalAt,
computeReadyAfter,
};
|