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
|
export const crontechEnv = {
get apiKey(): string {
return process.env.CRONTECH_API_KEY || "";
},
get baseUrl(): string {
return (process.env.CRONTECH_BASE_URL || "https://crontech.ai").replace(
/\/+$/,
""
);
},
};
export function isConfigured(): boolean {
return !!crontechEnv.apiKey;
}
export function buildAuthHeaders(): Record<string, string> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
const key = crontechEnv.apiKey;
if (key) headers["Authorization"] = `Bearer ${key}`;
return headers;
}
export type DeploymentStatus =
| "pending"
| "deploying"
| "live"
| "failed"
| "rolled_back";
export type Deployment = {
deployId: string;
commitSha: string;
status: DeploymentStatus;
environment: string;
url?: string;
startedAt: string;
finishedAt?: string;
};
export type DeployError = {
message: string;
stackTrace?: string;
count: number;
};
export type DeployWatchResult = {
deployId: string;
finalStatus: DeploymentStatus;
errors: DeployError[];
watchedForMs: number;
offline: boolean;
};
const TERMINAL_STATUSES: DeploymentStatus[] = ["live", "failed", "rolled_back"];
function isTerminal(s: DeploymentStatus): boolean {
return TERMINAL_STATUSES.includes(s);
}
function coerceStatus(raw: unknown): DeploymentStatus {
const s = String(raw || "").toLowerCase();
if (
s === "pending" ||
s === "deploying" ||
s === "live" ||
s === "failed" ||
s === "rolled_back"
) {
return s;
}
return "pending";
}
function coerceDeployment(data: unknown): Deployment | null {
if (!data || typeof data !== "object") return null;
const d = data as Record<string, unknown>;
const deployId = typeof d.deployId === "string" ? d.deployId : "";
if (!deployId) return null;
return {
deployId,
commitSha: typeof d.commitSha === "string" ? d.commitSha : "",
status: coerceStatus(d.status),
environment:
typeof d.environment === "string" ? d.environment : "production",
url: typeof d.url === "string" ? d.url : undefined,
startedAt:
typeof d.startedAt === "string"
? d.startedAt
: new Date().toISOString(),
finishedAt: typeof d.finishedAt === "string" ? d.finishedAt : undefined,
};
}
async function request(
url: string,
method: "GET" | "POST",
body: unknown,
timeoutMs: number
): Promise<unknown | null> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const init: RequestInit = {
method,
headers: buildAuthHeaders(),
signal: controller.signal,
};
if (method !== "GET") init.body = JSON.stringify(body ?? {});
const res = await fetch(url, init);
if (!res.ok) return null;
return await res.json().catch(() => null);
} catch {
return null;
} finally {
clearTimeout(timer);
}
}
export async function getDeploymentForCommit(params: {
repo: string;
commitSha: string;
}): Promise<Deployment | null> {
if (!isConfigured()) return null;
const qs = new URLSearchParams({
repo: params.repo,
sha: params.commitSha,
});
const url = `${crontechEnv.baseUrl}/api/v1/deployments?${qs.toString()}`;
const data = await request(url, "GET", undefined, 30_000);
return coerceDeployment(data);
}
export async function triggerRedeploy(params: {
repo: string;
commitSha: string;
environment?: string;
}): Promise<Deployment | null> {
if (!isConfigured()) return null;
const url = `${crontechEnv.baseUrl}/api/v1/deployments`;
const data = await request(url, "POST", params, 60_000);
return coerceDeployment(data);
}
export async function rollbackDeployment(params: {
repo: string;
deployId: string;
}): Promise<boolean> {
if (!isConfigured()) return false;
if (!params.deployId) return false;
const url = `${crontechEnv.baseUrl}/api/v1/deployments/${encodeURIComponent(
params.deployId
)}/rollback`;
const data = await request(url, "POST", { repo: params.repo }, 60_000);
if (!data || typeof data !== "object") return false;
const ok = (data as Record<string, unknown>).ok;
return ok === undefined ? true : !!ok;
}
export async function watchDeployment(params: {
repo: string;
deployId: string;
maxWaitMs?: number;
pollIntervalMs?: number;
}): Promise<DeployWatchResult> {
const maxWaitMs = params.maxWaitMs ?? 300_000;
const pollIntervalMs = params.pollIntervalMs ?? 10_000;
if (!isConfigured()) {
return {
deployId: params.deployId,
finalStatus: "failed",
errors: [],
watchedForMs: 0,
offline: true,
};
}
if (!params.deployId) {
return {
deployId: "",
finalStatus: "failed",
errors: [],
watchedForMs: 0,
offline: true,
};
}
const started = Date.now();
const statusUrl = `${crontechEnv.baseUrl}/api/v1/deployments/${encodeURIComponent(
params.deployId
)}/status`;
const errorsUrl = `${crontechEnv.baseUrl}/api/v1/deployments/${encodeURIComponent(
params.deployId
)}/errors`;
let currentStatus: DeploymentStatus = "pending";
let errors: DeployError[] = [];
let pollsFailed = 0;
const maxPollFailures = 3;
while (Date.now() - started < maxWaitMs) {
const statusRes = await request(statusUrl, "GET", undefined, 30_000);
if (!statusRes || typeof statusRes !== "object") {
pollsFailed++;
if (pollsFailed >= maxPollFailures) {
return {
deployId: params.deployId,
finalStatus: "failed",
errors,
watchedForMs: Date.now() - started,
offline: true,
};
}
} else {
pollsFailed = 0;
currentStatus = coerceStatus(
(statusRes as Record<string, unknown>).status
);
if (isTerminal(currentStatus)) {
const errRes = await request(errorsUrl, "GET", undefined, 30_000);
if (errRes && typeof errRes === "object") {
const list = (errRes as Record<string, unknown>).errors;
if (Array.isArray(list)) {
errors = list
.filter((e) => e && typeof e === "object")
.map((e) => {
const obj = e as Record<string, unknown>;
return {
message:
typeof obj.message === "string" ? obj.message : "",
stackTrace:
typeof obj.stackTrace === "string"
? obj.stackTrace
: undefined,
count: Number(obj.count || 1),
};
});
}
}
return {
deployId: params.deployId,
finalStatus: currentStatus,
errors,
watchedForMs: Date.now() - started,
offline: false,
};
}
}
const remaining = maxWaitMs - (Date.now() - started);
if (remaining <= 0) break;
await new Promise((r) => setTimeout(r, Math.min(pollIntervalMs, remaining)));
}
return {
deployId: params.deployId,
finalStatus: isTerminal(currentStatus) ? currentStatus : "failed",
errors,
watchedForMs: Date.now() - started,
offline: false,
};
}
export const __internal = {
isTerminal,
coerceStatus,
coerceDeployment,
request,
TERMINAL_STATUSES,
};
|