-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathplatform.v3.server.ts
More file actions
485 lines (415 loc) · 13.1 KB
/
platform.v3.server.ts
File metadata and controls
485 lines (415 loc) · 13.1 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
import type { Organization, Project } from "@trigger.dev/database";
import {
BillingClient,
type Limits,
type SetPlanBody,
type UsageSeriesParams,
type UsageResult,
defaultMachine as defaultMachineFromPlatform,
machines as machinesFromPlatform,
type MachineCode,
} from "@trigger.dev/platform/v3";
import { createCache, DefaultStatefulContext, Namespace } from "@unkey/cache";
import { MemoryStore } from "@unkey/cache/stores";
import { redirect } from "remix-typedjson";
import { $replica } from "~/db.server";
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 { existsSync, readFileSync } from "node:fs";
import { z } from "zod";
import { MachinePresetName } from "@trigger.dev/core/v3";
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,
});
console.log(`🤑 Billing client initialized: ${process.env.BILLING_API_URL}`);
return client;
} else {
console.log(`🤑 Billing client not initialized`);
}
}
const client = singleton("billingClient", initializeClient);
function initializePlatformCache() {
const ctx = new DefaultStatefulContext();
const memory = new MemoryStore({ persistentMap: new Map() });
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,
};
}
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", { 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", { 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", { orgId, error: result.error });
return undefined;
}
return result.v3Subscription?.plan?.limits;
} catch (e) {
logger.error("Error getting limits", { 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 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", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting plans", { error: e });
return undefined;
}
}
export async function setPlan(
organization: { id: string; slug: string },
request: Request,
callerPath: string,
plan: SetPlanBody
) {
if (!client) {
throw redirectWithErrorMessage(callerPath, request, "Error setting plan");
}
try {
const result = await client.setPlan(organization.id, plan);
if (!result) {
throw redirectWithErrorMessage(callerPath, request, "Error setting plan");
}
if (!result.success) {
throw redirectWithErrorMessage(callerPath, request, result.error);
}
switch (result.action) {
case "free_connect_required": {
return redirect(result.connectUrl);
}
case "free_connected": {
if (result.accepted) {
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."
);
}
}
case "create_subscription_flow_start": {
return redirect(result.checkoutUrl);
}
case "updated_subscription": {
return redirectWithSuccessMessage(
callerPath,
request,
"Subscription updated successfully."
);
}
case "canceled_subscription": {
return redirectWithSuccessMessage(callerPath, request, "Subscription canceled.");
}
}
} catch (e) {
logger.error("Error setting plan", { organizationId: organization.id, error: e });
throw redirectWithErrorMessage(
callerPath,
request,
e instanceof Error ? e.message : "Error setting plan"
);
}
}
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", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting usage", { 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", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error getting usage series", { 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", { error: result.error });
return undefined;
}
return result;
} catch (e) {
logger.error("Error reporting invocation", { 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) {
if (!client) return undefined;
try {
const result = await client.getEntitlement(organizationId);
if (!result.success) {
logger.error("Error getting entitlement", { error: result.error });
return {
hasAccess: true as const,
};
}
return result;
} catch (e) {
logger.error("Error getting entitlement", { error: e });
return {
hasAccess: true as const,
};
}
}
export async function projectCreated(organization: Organization, 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,
});
}
}
}
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;
}