-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathplatform.v3.server.ts
More file actions
684 lines (590 loc) · 19 KB
/
platform.v3.server.ts
File metadata and controls
684 lines (590 loc) · 19 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
import { MachinePresetName, tryCatch } from "@trigger.dev/core/v3";
import type { Organization, Project, RuntimeEnvironmentType } from "@trigger.dev/database";
import {
BillingClient,
defaultMachine as defaultMachineFromPlatform,
machines as machinesFromPlatform,
type BillingAlertsResult,
type Limits,
type MachineCode,
type ReportUsageResult,
type SetPlanBody,
type UpdateBillingAlertsRequest,
type UsageResult,
type UsageSeriesParams,
type CurrentPlan,
} from "@trigger.dev/platform";
import { createCache, DefaultStatefulContext, Namespace } from "@unkey/cache";
import { createLRUMemoryStore } from "@internal/cache";
import { existsSync, readFileSync } from "node:fs";
import { redirect } from "remix-typedjson";
import { z } from "zod";
import { env } from "~/env.server";
import { redirectWithErrorMessage, redirectWithSuccessMessage } from "~/models/message.server";
import { createEnvironment } from "~/models/organization.server";
import { logger } from "~/services/logger.server";
import { newProjectPath, organizationBillingPath } from "~/utils/pathBuilder";
import { singleton } from "~/utils/singleton";
import { RedisCacheStore } from "./unkey/redisCacheStore.server";
import { $replica } from "~/db.server";
function initializeClient() {
if (isCloud() && process.env.BILLING_API_URL && process.env.BILLING_API_KEY) {
const client = new BillingClient({
url: process.env.BILLING_API_URL,
apiKey: process.env.BILLING_API_KEY,
});
return client;
}
}
const client = singleton("billingClient", initializeClient);
function initializePlatformCache() {
const ctx = new DefaultStatefulContext();
const memory = createLRUMemoryStore(1000);
const redisCacheStore = new RedisCacheStore({
connection: {
keyPrefix: "tr:cache:platform:v3",
port: env.CACHE_REDIS_PORT,
host: env.CACHE_REDIS_HOST,
username: env.CACHE_REDIS_USERNAME,
password: env.CACHE_REDIS_PASSWORD,
tlsDisabled: env.CACHE_REDIS_TLS_DISABLED === "true",
clusterMode: env.CACHE_REDIS_CLUSTER_MODE_ENABLED === "1",
},
});
// This cache holds the limits fetched from the platform service
const cache = createCache({
limits: new Namespace<number>(ctx, {
stores: [memory, redisCacheStore],
fresh: 60_000 * 5, // 5 minutes
stale: 60_000 * 10, // 10 minutes
}),
usage: new Namespace<UsageResult>(ctx, {
stores: [memory, redisCacheStore],
fresh: 60_000 * 5, // 5 minutes
stale: 60_000 * 10, // 10 minutes
}),
});
return cache;
}
const platformCache = singleton("platformCache", initializePlatformCache);
type Machines = typeof machinesFromPlatform;
const MachineOverrideValues = z.object({
cpu: z.number(),
memory: z.number(),
});
type MachineOverrideValues = z.infer<typeof MachineOverrideValues>;
const MachineOverrides = z.record(MachinePresetName, MachineOverrideValues.partial());
type MachineOverrides = z.infer<typeof MachineOverrides>;
const MachinePresetOverrides = z.object({
defaultMachine: MachinePresetName.optional(),
machines: MachineOverrides.optional(),
});
function initializeMachinePresets(): {
defaultMachine: MachineCode;
machines: Machines;
} {
const overrides = getMachinePresetOverrides();
if (!overrides) {
return {
defaultMachine: defaultMachineFromPlatform,
machines: machinesFromPlatform,
};
}
logger.info("🎛️ Overriding machine presets", { overrides });
return {
defaultMachine: overrideDefaultMachine(defaultMachineFromPlatform, overrides.defaultMachine),
machines: overrideMachines(machinesFromPlatform, overrides.machines),
};
}
export const { defaultMachine, machines } = singleton("machinePresets", initializeMachinePresets);
function overrideDefaultMachine(defaultMachine: MachineCode, override?: MachineCode): MachineCode {
if (!override) {
return defaultMachine;
}
return override;
}
function overrideMachines(machines: Machines, overrides?: MachineOverrides): Machines {
if (!overrides) {
return machines;
}
const mergedMachines = {
...machines,
};
for (const machine of Object.keys(overrides) as MachinePresetName[]) {
mergedMachines[machine] = {
...mergedMachines[machine],
...overrides[machine],
};
}
return mergedMachines;
}
function getMachinePresetOverrides() {
const path = env.MACHINE_PRESETS_OVERRIDE_PATH;
if (!path) {
return;
}
const overrides = safeReadMachinePresetOverrides(path);
if (!overrides) {
return;
}
const parsed = MachinePresetOverrides.safeParse(overrides);
if (!parsed.success) {
logger.error("Error parsing machine preset overrides", { path, error: parsed.error });
return;
}
return parsed.data;
}
function safeReadMachinePresetOverrides(path: string) {
try {
const fileExists = existsSync(path);
if (!fileExists) {
logger.error("Machine preset overrides file does not exist", { path });
return;
}
const fileContents = readFileSync(path, "utf8");
return JSON.parse(fileContents);
} catch (error) {
logger.error("Error reading machine preset overrides", {
path,
error: error instanceof Error ? error.message : String(error),
});
return;
}
}
export async function getCurrentPlan(orgId: string) {
if (!client) return undefined;
try {
const result = await client.currentPlan(orgId);
const firstDayOfMonth = new Date();
firstDayOfMonth.setUTCDate(1);
firstDayOfMonth.setUTCHours(0, 0, 0, 0);
const firstDayOfNextMonth = new Date();
firstDayOfNextMonth.setUTCDate(1);
firstDayOfNextMonth.setUTCMonth(firstDayOfNextMonth.getUTCMonth() + 1);
firstDayOfNextMonth.setUTCHours(0, 0, 0, 0);
if (!result.success) {
logger.error("Error getting current plan - no success", { orgId, error: result.error });
return undefined;
}
const periodStart = firstDayOfMonth;
const periodEnd = firstDayOfNextMonth;
const periodRemainingDuration = periodEnd.getTime() - new Date().getTime();
const usage = {
periodStart,
periodEnd,
periodRemainingDuration,
};
return { ...result, usage };
} catch (e) {
logger.error("Error getting current plan - caught error", { orgId, error: e });
return undefined;
}
}
export async function getLimits(orgId: string) {
if (!client) return undefined;
try {
const result = await client.currentPlan(orgId);
if (!result.success) {
logger.error("Error getting limits - no success", { orgId, error: result.error });
return undefined;
}
return result.v3Subscription?.plan?.limits;
} catch (e) {
logger.error("Error getting limits - caught error", { orgId, error: e });
return undefined;
}
}
export async function getLimit(orgId: string, limit: keyof Limits, fallback: number) {
const limits = await getLimits(orgId);
if (!limits) return fallback;
const result = limits[limit];
if (!result) return fallback;
if (typeof result === "number") return result;
if (typeof result === "object" && "number" in result) return result.number;
return fallback;
}
export async function getDefaultEnvironmentConcurrencyLimit(
organizationId: string,
environmentType: RuntimeEnvironmentType
): Promise<number> {
if (!client) {
const org = await $replica.organization.findFirst({
where: {
id: organizationId,
},
select: {
maximumConcurrencyLimit: true,
},
});
if (!org) throw new Error("Organization not found");
return org.maximumConcurrencyLimit;
}
const result = await client.currentPlan(organizationId);
if (!result.success) throw new Error("Error getting current plan");
const limit = getDefaultEnvironmentLimitFromPlan(environmentType, result);
if (!limit) throw new Error("No plan found");
return limit;
}
export function getDefaultEnvironmentLimitFromPlan(
environmentType: RuntimeEnvironmentType,
plan: CurrentPlan
): number | undefined {
if (!plan.v3Subscription?.plan) return undefined;
switch (environmentType) {
case "DEVELOPMENT":
return plan.v3Subscription.plan.limits.concurrentRuns.development;
case "STAGING":
return plan.v3Subscription.plan.limits.concurrentRuns.staging;
case "PREVIEW":
return plan.v3Subscription.plan.limits.concurrentRuns.preview;
case "PRODUCTION":
return plan.v3Subscription.plan.limits.concurrentRuns.production;
default:
return plan.v3Subscription.plan.limits.concurrentRuns.number;
}
}
export async function getCachedLimit(orgId: string, limit: keyof Limits, fallback: number) {
return platformCache.limits.swr(`${orgId}:${limit}`, async () => {
return getLimit(orgId, limit, fallback);
});
}
export async function customerPortalUrl(orgId: string, orgSlug: string) {
if (!client) return undefined;
try {
return client.createPortalSession(orgId, {
returnUrl: `${env.APP_ORIGIN}${organizationBillingPath({ slug: orgSlug })}`,
});
} catch (e) {
logger.error("Error getting customer portal Url", { orgId, error: e });
return undefined;
}
}
export async function getPlans() {
if (!client) return undefined;
try {
const result = await client.plans();
if (!result.success) {
logger.error("Error getting plans - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting plans - caught error", { error: e });
return undefined;
}
}
export async function setPlan(
organization: { id: string; slug: string },
request: Request,
callerPath: string,
plan: SetPlanBody,
opts?: { invalidateBillingCache?: (orgId: string) => void }
) {
if (!client) {
return redirectWithErrorMessage(callerPath, request, "Error setting plan", {
ephemeral: false,
});
}
const [error, result] = await tryCatch(client.setPlan(organization.id, plan));
if (error) {
return redirectWithErrorMessage(callerPath, request, error.message, { ephemeral: false });
}
if (!result) {
return redirectWithErrorMessage(callerPath, request, "Error setting plan", {
ephemeral: false,
});
}
if (!result.success) {
return redirectWithErrorMessage(callerPath, request, result.error, { ephemeral: false });
}
switch (result.action) {
case "free_connect_required": {
return redirect(result.connectUrl);
}
case "free_connected": {
if (result.accepted) {
// Invalidate billing cache since plan changed
opts?.invalidateBillingCache?.(organization.id);
return redirect(newProjectPath(organization, "You're on the Free plan."));
} else {
return redirectWithErrorMessage(
callerPath,
request,
"Free tier unlock failed, your GitHub account is too new.",
{ ephemeral: false }
);
}
}
case "create_subscription_flow_start": {
return redirect(result.checkoutUrl);
}
case "updated_subscription": {
// Invalidate billing cache since subscription changed
opts?.invalidateBillingCache?.(organization.id);
return redirectWithSuccessMessage(callerPath, request, "Subscription updated successfully.");
}
case "canceled_subscription": {
// Invalidate billing cache since subscription was canceled
opts?.invalidateBillingCache?.(organization.id);
return redirectWithSuccessMessage(callerPath, request, "Subscription canceled.");
}
}
}
export async function setConcurrencyAddOn(organizationId: string, amount: number) {
if (!client) return undefined;
try {
const result = await client.setAddOn(organizationId, { type: "concurrency", amount });
if (!result.success) {
logger.error("Error setting concurrency add on - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error setting concurrency add on - caught error", { error: e });
return undefined;
}
}
export async function setSeatsAddOn(organizationId: string, amount: number) {
if (!client) return undefined;
try {
const result = await client.setAddOn(organizationId, { type: "seats", amount });
if (!result.success) {
logger.error("Error setting seats add on - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error setting seats add on - caught error", { error: e });
return undefined;
}
}
export async function setBranchesAddOn(organizationId: string, amount: number) {
if (!client) return undefined;
try {
const result = await client.setAddOn(organizationId, { type: "branches", amount });
if (!result.success) {
logger.error("Error setting branches add on - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error setting branches add on - caught error", { error: e });
return undefined;
}
}
export async function getUsage(organizationId: string, { from, to }: { from: Date; to: Date }) {
if (!client) return undefined;
try {
const result = await client.usage(organizationId, { from, to });
if (!result.success) {
logger.error("Error getting usage - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting usage - caught error", { error: e });
return undefined;
}
}
export async function getCachedUsage(
organizationId: string,
{ from, to }: { from: Date; to: Date }
) {
if (!client) return undefined;
const result = await platformCache.usage.swr(
`${organizationId}:${from.toISOString()}:${to.toISOString()}`,
async () => {
const usageResponse = await getUsage(organizationId, { from, to });
return usageResponse;
}
);
return result.val;
}
export async function getUsageSeries(organizationId: string, params: UsageSeriesParams) {
if (!client) return undefined;
try {
const result = await client.usageSeries(organizationId, params);
if (!result.success) {
logger.error("Error getting usage series - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting usage series - caught error", { error: e });
return undefined;
}
}
export async function reportInvocationUsage(
organizationId: string,
costInCents: number,
additionalData?: Record<string, any>
) {
if (!client) return undefined;
try {
const result = await client.reportInvocationUsage({
organizationId,
costInCents,
additionalData,
});
if (!result.success) {
logger.error("Error reporting invocation - no success", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error reporting invocation - caught error", { error: e });
return undefined;
}
}
export async function reportComputeUsage(request: Request) {
if (!client) return undefined;
return fetch(`${process.env.BILLING_API_URL}/api/v1/usage/ingest/compute`, {
method: "POST",
headers: request.headers,
body: await request.text(),
});
}
export async function getEntitlement(
organizationId: string
): Promise<ReportUsageResult | undefined> {
if (!client) return undefined;
try {
const result = await client.getEntitlement(organizationId);
if (!result.success) {
logger.error("Error getting entitlement - no success", { error: result.error });
return {
hasAccess: true as const,
};
}
return result;
} catch (e) {
logger.error("Error getting entitlement - caught error", { error: e });
return {
hasAccess: true as const,
};
}
}
export async function projectCreated(
organization: Pick<Organization, "id" | "maximumConcurrencyLimit">,
project: Project
) {
if (!isCloud()) {
await createEnvironment({ organization, project, type: "STAGING" });
await createEnvironment({
organization,
project,
type: "PREVIEW",
isBranchableEnvironment: true,
});
} else {
//staging is only available on certain plans
const plan = await getCurrentPlan(organization.id);
if (plan?.v3Subscription.plan?.limits.hasStagingEnvironment) {
await createEnvironment({ organization, project, type: "STAGING" });
await createEnvironment({
organization,
project,
type: "PREVIEW",
isBranchableEnvironment: true,
});
}
}
}
export async function getBillingAlerts(
organizationId: string
): Promise<BillingAlertsResult | undefined> {
if (!client) return undefined;
const result = await client.getBillingAlerts(organizationId);
if (!result.success) {
logger.error("Error getting billing alert", { error: result.error, organizationId });
throw new Error("Error getting billing alert");
}
return result;
}
export async function setBillingAlert(
organizationId: string,
alert: UpdateBillingAlertsRequest
): Promise<BillingAlertsResult | undefined> {
if (!client) return undefined;
const result = await client.updateBillingAlerts(organizationId, alert);
if (!result.success) {
logger.error("Error setting billing alert", { error: result.error, organizationId });
throw new Error("Error setting billing alert");
}
return result;
}
export async function generateRegistryCredentials(
projectId: string,
region: "us-east-1" | "eu-central-1"
) {
if (!client) return undefined;
const result = await client.generateRegistryCredentials(projectId, region);
if (!result.success) {
logger.error("Error generating registry credentials", {
error: result.error,
projectId,
region,
});
throw new Error("Failed to generate registry credentials");
}
return result;
}
export async function enqueueBuild(
projectId: string,
deploymentId: string,
artifactKey: string,
options: {
skipPromotion?: boolean;
configFilePath?: string;
}
) {
if (!client) return undefined;
const result = await client.enqueueBuild(projectId, { deploymentId, artifactKey, options });
if (!result.success) {
logger.error("Error enqueuing build", {
error: result.error,
projectId,
deploymentId,
artifactKey,
options,
});
throw new Error("Failed to enqueue build");
}
return result;
}
export async function triggerInitialDeployment(
projectId: string,
options: { environment: "preview" | "prod" | "staging" }
): Promise<void> {
if (!client) return;
const [error, result] = await tryCatch(client.triggerInitialDeployment(projectId, options));
if (error) {
logger.warn("Error triggering initial deployment", {
projectId,
environment: options.environment,
error,
});
return;
}
if (!result.success) {
logger.warn("Failed to trigger initial deployment", {
projectId,
environment: options.environment,
error: result.error,
});
}
}
function isCloud(): boolean {
const acceptableHosts = [
"https://cloud.trigger.dev",
"https://test-cloud.trigger.dev",
"https://internal.trigger.dev",
];
if (acceptableHosts.includes(env.LOGIN_ORIGIN)) {
return true;
}
if (process.env.CLOUD_ENV === "development" && process.env.NODE_ENV === "development") {
return true;
}
return false;
}