-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.ts
More file actions
471 lines (422 loc) · 12.5 KB
/
backend.ts
File metadata and controls
471 lines (422 loc) · 12.5 KB
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { z } from "zod";
import { clearAuthToken, exitBecauseNotLoggedIn, getAuthToken } from "./auth.ts";
import { equal } from "@std/assert/equal";
import { delay } from "@std/async/delay";
import { GLUE_API_SERVER } from "./common.ts";
import { retry } from "@std/async/retry";
import { Registrations } from "@streak-glue/runtime/backendTypes";
export const GlueEnvironment = z.enum(["dev", "deploy"]);
export type GlueEnvironment = z.infer<typeof GlueEnvironment>;
export const DeploymentAsset = z.object({
kind: z.literal("file"),
content: z.string(),
encoding: z.enum(["utf-8", "base64"]).optional(),
});
export type DeploymentAsset = z.infer<typeof DeploymentAsset>;
const DeploymentContent = z.object({
entryPointUrl: z.string(),
assets: z.record(z.string(), DeploymentAsset),
envVars: z.record(z.string(), z.string()).optional(),
});
export type DeploymentContent = z.infer<typeof DeploymentContent>;
export const Runner = z.enum(["deno", "deno-v2", "fly", "cloudflare", "sandbox"]);
export type Runner = z.infer<typeof Runner>;
const CreateDeploymentParams = z.object({
deploymentContent: DeploymentContent.optional(),
optimisticRegistrations: Registrations.optional(),
runner: Runner.optional(),
});
export type CreateDeploymentParams = z.infer<typeof CreateDeploymentParams>;
export const CreateGlueParams = z.object({
name: z.string(),
environment: GlueEnvironment,
description: z.string().optional().nullable(),
tags: z.array(z.string()).optional(),
deployment: CreateDeploymentParams,
});
export type CreateGlueParams = z.infer<typeof CreateGlueParams>;
export const UpdateGlueParams = z.object({
name: z.string().optional(),
description: z.string().optional().nullable(),
tags: z.array(z.string()).optional(),
running: z.boolean().optional(),
currentDeploymentId: z.string().optional(),
triggerStorage: z.record(z.string(), z.unknown()).optional(),
});
export type UpdateGlueParams = z.infer<typeof UpdateGlueParams>;
export async function backendRequest<T>(
path: string,
options: RequestInit = {},
forceTrace = true,
): Promise<T> {
options.signal?.throwIfAborted();
const authToken = await getAuthToken();
const headers: Record<string, string> = {
"Authorization": `Bearer ${authToken}`,
"User-Agent": "glue-cli",
"X-Glue-Set-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
};
if (forceTrace) {
headers["X-Cloud-Trace-Context"] = `00000000000000000000000000000000/0;o=1`;
}
const res = await fetch(`${GLUE_API_SERVER}${path}`, {
...options,
headers,
});
if (res.status === 401) {
await clearAuthToken();
exitBecauseNotLoggedIn();
}
if (!res.ok) {
const body = await res.text();
throw new Error(
`Failed request: ${path} (${
options.method ?? "GET"
}): ${res.status} ${res.statusText} ${body}`,
);
}
return res.json() as Promise<T>;
}
export async function getLoggedInUser(signal?: AbortSignal): Promise<UserDTO> {
return await backendRequest<UserDTO>("/users/me", { signal });
}
export async function getGlueByName(
name: string,
environment: GlueEnvironment,
signal?: AbortSignal,
): Promise<GlueDTO | undefined> {
const params = new URLSearchParams({ name, environment });
const glues = await backendRequest<GlueDTO[]>(`/glues?${params.toString()}`, { signal });
return glues[0];
}
export interface GetGluesFilters {
environment: GlueEnvironment;
name?: string;
includeTags?: string[];
excludeTags?: string[];
}
export async function getGlues(
filters: GetGluesFilters = { environment: "deploy", excludeTags: ["archived"] },
signal?: AbortSignal,
): Promise<GlueDTO[]> {
const params = new URLSearchParams({ environment: filters.environment });
if (filters?.name) {
params.set("name", filters.name);
}
if (filters?.includeTags) {
params.set("includeTags", filters.includeTags.join(","));
}
if (filters?.excludeTags) {
params.set("excludeTags", filters.excludeTags.join(","));
}
return await backendRequest<GlueDTO[]>(`/glues?${params.toString()}`, { signal });
}
export async function getGlueById(id: string, signal?: AbortSignal): Promise<GlueDTO | undefined> {
return await backendRequest<GlueDTO>(`/glues/${id}`, { signal });
}
export async function stopGlue(id: string, signal?: AbortSignal) {
await backendRequest<void>(`/glues/${id}/stop`, {
method: "POST",
signal,
});
}
export async function createGlue(
name: string,
deployment: CreateDeploymentParams,
environment: GlueEnvironment,
options?: { description?: string | null; tags?: string[]; signal?: AbortSignal },
): Promise<GlueDTO> {
const res = await backendRequest<GlueDTO>(`/glues`, {
method: "POST",
body: JSON.stringify(
{
name,
deployment,
environment,
description: options?.description,
tags: options?.tags,
} satisfies CreateGlueParams,
),
signal: options?.signal,
});
return res;
}
export async function updateGlue(
id: string,
params: UpdateGlueParams,
signal?: AbortSignal,
): Promise<GlueDTO> {
const res = await backendRequest<GlueDTO>(`/glues/${id}`, {
method: "POST",
body: JSON.stringify(params satisfies UpdateGlueParams),
signal,
});
return res;
}
export async function createDeployment(
glueId: string,
deployment: CreateDeploymentParams,
signal?: AbortSignal,
): Promise<DeploymentDTO> {
const res = await backendRequest<DeploymentDTO>(
`/glues/${glueId}/deployments`,
{
method: "POST",
body: JSON.stringify(deployment),
signal,
},
);
return res;
}
export async function getDeploymentById(
id: string,
includeBuildStepText = false,
signal?: AbortSignal,
): Promise<DeploymentDTO | undefined> {
const params = new URLSearchParams();
if (includeBuildStepText) {
params.set("includeBuildStepText", "true");
}
return await backendRequest<DeploymentDTO>(`/deployments/${id}?${params.toString()}`, { signal });
}
export async function getDeployments(id: string, signal?: AbortSignal): Promise<DeploymentDTO[]> {
return await backendRequest<DeploymentDTO[]>(`/glues/${id}/deployments`, { signal });
}
function areDeploymentsEqual(a: DeploymentDTO, b: DeploymentDTO): boolean {
if (a.status !== b.status) {
return false;
}
if (!equal(a.buildSteps, b.buildSteps)) {
return false;
}
if (!equal(a.triggers, b.triggers) || !equal(a.accountInjections, b.accountInjections)) {
return false;
}
if (!equal(a.accountsToSetup, b.accountsToSetup)) {
return false;
}
return true;
}
export async function* streamChangesTillDeploymentReady(
deploymentId: string,
signal?: AbortSignal,
): AsyncIterable<DeploymentDTO> {
let lastDeployment: DeploymentDTO | undefined;
while (true) {
signal?.throwIfAborted();
const deployment = await retry(() => getDeploymentById(deploymentId, true, signal), { signal });
if (!deployment) {
throw new Error(`Deployment ${deploymentId} not found`);
}
if (!lastDeployment || !areDeploymentsEqual(lastDeployment, deployment)) {
lastDeployment = deployment;
yield deployment;
if (deployment.status !== "pending" && deployment.status !== "committing") {
return;
}
}
await delay(2_000, { signal });
}
}
export async function getExecutions(
limit: number,
since: Date | undefined,
direction: "asc" | "desc" = "desc",
includeInputData: boolean = false,
filter: string | undefined = undefined,
search: string | undefined = undefined,
glueId?: string,
deploymentId?: string,
signal?: AbortSignal,
): Promise<ExecutionDTO[]> {
const params = new URLSearchParams({
limit: limit.toString(),
direction: direction,
includeInputData: includeInputData.toString(),
});
if (since) {
params.set("since", since.getTime().toString());
}
if (filter) {
params.set("filter", filter);
}
if (search) {
params.set("search", search);
}
if (glueId) {
return await backendRequest<ExecutionDTO[]>(
`/glues/${glueId}/executions?${params.toString()}`,
{ signal },
);
} else if (deploymentId) {
return await backendRequest<ExecutionDTO[]>(
`/deployments/${deploymentId}/executions?${params.toString()}`,
{ signal },
);
}
throw new Error("Either glueId or deploymentId must be provided");
}
export async function getExecutionById(id: string, signal?: AbortSignal): Promise<ExecutionDTO> {
return await backendRequest<ExecutionDTO>(`/executions/${id}`, { signal });
}
export async function getExecutionByIdNoThrow(
id: string,
signal?: AbortSignal,
): Promise<ExecutionDTO | undefined> {
try {
return await backendRequest<ExecutionDTO>(`/executions/${id}`, { signal });
} catch (_e) {
return undefined;
}
}
export async function replayExecution(executionId: string, signal?: AbortSignal) {
await backendRequest<void>(`/executions/${executionId}/replay`, {
method: "POST",
signal,
});
}
export async function sampleTrigger(triggerId: string, signal?: AbortSignal) {
await backendRequest<void>(`/triggers/${triggerId}/sample`, {
method: "POST",
signal,
});
}
export interface ExecutionDTO {
id: string;
deploymentId: string;
trigger: TriggerDTO;
logs: Log[];
inputData: unknown;
startedAt: number;
endedAt?: number;
state: string;
}
export interface Log {
timestamp: number;
type: "stdout" | "stderr";
text: string;
}
export type DeploymentStatus = "pending" | "committing" | "success" | "failure" | "cancelled";
/** taken from glue-backend */
export interface DeploymentDTO {
id: string;
glueId: string;
status: DeploymentStatus;
needsUserAuth: boolean;
createdAt: number; // milliseconds since epoch
updatedAt: number; // milliseconds since epoch
triggers: TriggerDTO[];
accountInjections: AccountInjectionDTO[];
buildSteps: BuildStepDTO[];
accountsToSetup: AccountToSetup[];
totalExecutions: number;
totalFailedExecutions: number;
mostRecentExecution: number | null;
}
export interface AccountToSetup {
type: string;
selector?: string;
accountSetupUrl: string;
triggerIds: string[];
accountInjectionIds: string[];
}
export type StepStatus = "success" | "failure" | "in_progress" | "not_started" | "skipped";
export type BuildStepName =
| "createTunnel"
| "createTriggers"
| "deployCode"
| "registrationAuth"
| "registrationSetup";
export interface BuildStepDTO {
name: BuildStepName;
deploymentId: string;
status: StepStatus;
text?: string;
startTime?: number;
endTime?: number;
}
export interface TriggerDTO {
id: string;
deploymentId: string;
glueId: string;
type: string;
label: string;
routingId?: string;
accountId?: string;
config?: Record<string, unknown>;
createdAt: number;
updatedAt: number;
accountSetupUrl?: string;
description?: string;
supportsSampleEvents: boolean;
}
export interface AccountInjectionDTO {
id: string;
deploymentId: string;
type: string;
label: string;
accountId?: string;
config?: Record<string, unknown>;
createdAt: number;
updatedAt: number;
accountSetupUrl?: string;
description?: string;
}
export interface GlueDTO {
id: string;
name: string;
environment: GlueEnvironment;
userId: string;
description: string | null;
tags: string[];
createdAt: number;
updatedAt: number;
creator: UserDTO;
running: boolean;
executionSummary: ExecutionSummaryDTO;
currentDeployment?: DeploymentDTO;
pendingDeployment?: DeploymentDTO;
devEventsWebsocketUrl?: string;
}
export interface ExecutionSummaryDTO {
totalCount: number;
totalErrorCount: number;
mostRecent: number | null;
currentDeploymentCount: number;
currentDeploymentErrorCount: number;
}
export interface UserDTO {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
avatarUrl: string | null;
createdAt: number; // milliseconds since epoch
updatedAt: number; // milliseconds since epoch
}
export interface AccountDTO {
id: string;
type: string;
selector: string;
displayName?: string;
redactedApiKey?: string;
scopes?: string[];
userId: string;
/** milliseconds since epoch */
createdAt: number;
/** milliseconds since epoch */
updatedAt: number;
/** Live glues that use this account */
liveGlues: GlueDTO[];
}
export async function getAccounts(): Promise<AccountDTO[]> {
return await backendRequest<AccountDTO[]>(`/accounts`);
}
export async function getAccountById(id: string): Promise<AccountDTO | undefined> {
return await backendRequest<AccountDTO>(`/accounts/${id}`);
}
export async function deleteAccount(id: string): Promise<void> {
await backendRequest<void>(`/accounts/${id}`, {
method: "DELETE",
});
}