-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcomputeTemplateCreation.server.ts
More file actions
286 lines (249 loc) · 8.93 KB
/
Copy pathcomputeTemplateCreation.server.ts
File metadata and controls
286 lines (249 loc) · 8.93 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
import { ComputeClient, stripImageDigest } from "@internal/compute";
import type { TemplateCreateResultEntry } from "@internal/compute";
import { MachinePresetName } from "@trigger.dev/core/v3";
import { machinePresetFromName } from "~/v3/machinePresets.server";
import { env } from "~/env.server";
import { logger } from "~/services/logger.server";
import type { PrismaClientOrTransaction } from "~/db.server";
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { ServiceValidationError } from "./baseService.server";
import { FailDeploymentService } from "./failDeployment.server";
import { resolveComputeAccess } from "../regionAccess.server";
import { WorkerGroupService } from "./worker/workerGroupService.server";
type TemplateCreationMode = "required" | "shadow" | "skip";
type ResolvedPreset = {
name: MachinePresetName;
cpu: number;
memory_gb: number;
};
export class ComputeTemplateCreationService {
private client: ComputeClient | undefined;
private presets: ResolvedPreset[];
private requiredPresets: Set<MachinePresetName>;
constructor() {
if (env.COMPUTE_GATEWAY_URL) {
this.client = new ComputeClient({
gatewayUrl: env.COMPUTE_GATEWAY_URL,
authToken: env.COMPUTE_GATEWAY_AUTH_TOKEN,
timeoutMs: 5 * 60 * 1000, // 5 minutes
});
}
this.presets = env.COMPUTE_TEMPLATE_MACHINE_PRESETS.map((name) => {
const machine = machinePresetFromName(name);
return { name, cpu: machine.cpu, memory_gb: machine.memory };
});
this.requiredPresets = new Set(env.COMPUTE_TEMPLATE_MACHINE_PRESETS_REQUIRED);
}
/**
* Handle template creation for a deployment. Call this before setting DEPLOYED.
*
* - Required mode: creates template synchronously, fails deployment on error
* - Shadow mode: fires background template creation (returns immediately)
* - Skip: no-op
*
* Throws ServiceValidationError if required mode fails (caller should stop finalize).
*/
async handleDeployTemplate(options: {
projectId: string;
imageReference: string;
deploymentFriendlyId: string;
authenticatedEnv: AuthenticatedEnvironment;
prisma: PrismaClientOrTransaction;
writer?: WritableStreamDefaultWriter;
}): Promise<void> {
const mode = await this.resolveMode(options.authenticatedEnv, options.prisma);
if (mode === "skip") {
return;
}
if (mode === "shadow") {
this.createTemplate(options.imageReference, { background: true })
.then((outcome) => {
if (outcome.error) {
logger.error("Shadow template creation failed", {
id: options.deploymentFriendlyId,
imageReference: options.imageReference,
error: outcome.error,
});
}
})
.catch((error) => {
logger.error("Shadow template creation threw unexpectedly", {
id: options.deploymentFriendlyId,
imageReference: options.imageReference,
error: error instanceof Error ? error.message : String(error),
});
});
return;
}
// Required mode
if (options.writer) {
try {
await options.writer.write(
`event: log\ndata: ${JSON.stringify({ message: "Building compute template..." })}\n\n`
);
} catch {
// Stream may be closed if client disconnected - continue with template creation
}
}
logger.info("Creating compute template (required mode)", {
id: options.deploymentFriendlyId,
imageReference: options.imageReference,
presets: this.presets.map((p) => p.name),
requiredPresets: [...this.requiredPresets],
});
const outcome = await this.createTemplate(options.imageReference);
const failureMessage = this.failureMessageForRequiredMode(
outcome,
options.deploymentFriendlyId,
options.imageReference
);
if (failureMessage) {
logger.error("Compute template creation failed", {
id: options.deploymentFriendlyId,
imageReference: options.imageReference,
error: failureMessage,
});
const failService = new FailDeploymentService();
await failService.call(options.authenticatedEnv, options.deploymentFriendlyId, {
error: {
name: "TemplateCreationFailed",
message: `Failed to create compute template: ${failureMessage}`,
},
});
throw new ServiceValidationError(`Compute template creation failed: ${failureMessage}`);
}
logger.info("Compute template created", {
id: options.deploymentFriendlyId,
imageReference: options.imageReference,
results: outcome.results.length,
});
}
async resolveMode(
authenticatedEnv: AuthenticatedEnvironment,
prisma: PrismaClientOrTransaction
): Promise<TemplateCreationMode> {
if (!this.client) {
return "skip";
}
const project = await prisma.project.findFirst({
where: { id: authenticatedEnv.projectId },
select: {
organization: {
select: { featureFlags: true },
},
},
});
if (!project) {
return "skip";
}
// Reuse the trigger path's resolution so the template decision matches the
// region runs actually deploy to: env default -> project default -> global default.
const defaultWorkerGroup = await new WorkerGroupService().getDefaultWorkerGroupForProject({
projectId: authenticatedEnv.projectId,
environmentDefaultWorkerGroupId: authenticatedEnv.defaultWorkerGroupId,
});
if (defaultWorkerGroup?.workloadType === "MICROVM") {
return "required";
}
const hasComputeAccess = await resolveComputeAccess(prisma, project.organization.featureFlags);
if (hasComputeAccess) {
return "shadow";
}
const rolloutPct = Number(env.COMPUTE_TEMPLATE_SHADOW_ROLLOUT_PCT ?? "0");
if (rolloutPct > 0 && Math.random() * 100 < rolloutPct) {
return "shadow";
}
return "skip";
}
async createTemplate(
imageReference: string,
options?: { background?: boolean }
): Promise<CreateTemplateOutcome> {
if (!this.client) {
return { error: "Compute gateway not configured", results: [] };
}
try {
const machineConfigs = this.presets.map((p) => ({
cpu: p.cpu,
memory_gb: p.memory_gb,
}));
const response = await this.client.templates.create({
image: stripImageDigest(imageReference),
machine_configs: machineConfigs,
background: options?.background,
});
// Background mode (202 Accepted): no body to inspect.
if (options?.background || !response) {
return { results: [] };
}
return {
error: response.error,
results: response.results,
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
logger.error("Failed to create compute template", {
imageReference,
error: message,
});
return { error: message, results: [] };
}
}
// Returns a human-readable failure message if any required preset failed
// or the request itself failed. Optional preset failures are logged and
// do not contribute to the message. Returns undefined on success.
private failureMessageForRequiredMode(
outcome: CreateTemplateOutcome,
deploymentFriendlyId: string,
imageReference: string
): string | undefined {
if (this.presets.length === 0) {
return undefined;
}
const failures: string[] = [];
this.presets.forEach((preset) => {
const isRequired = this.requiredPresets.has(preset.name);
// Match results to presets by (cpu, memory_gb) content with a small
// epsilon to tolerate float round-trip noise (memory_gb passes through
// gb -> mb -> gb conversion in the compute layer).
const result = outcome.results.find(
(r) =>
Math.abs(r.machine_config.cpu - preset.cpu) < 1e-9 &&
Math.abs(r.machine_config.memory_gb - preset.memory_gb) < 1e-9
);
if (!result) {
if (isRequired) {
failures.push(`${preset.name}: not built`);
} else {
logger.warn("Optional compute template preset not built", {
id: deploymentFriendlyId,
imageReference,
preset: preset.name,
});
}
return;
}
if (result.error) {
if (isRequired) {
failures.push(`${preset.name}: ${result.error}`);
} else {
logger.warn("Optional compute template preset failed", {
id: deploymentFriendlyId,
imageReference,
preset: preset.name,
error: result.error,
});
}
}
});
// Surface request-level errors only when no per-preset failure attributed.
if (outcome.error && failures.length === 0) {
failures.push(outcome.error);
}
return failures.length > 0 ? failures.join("; ") : undefined;
}
}
type CreateTemplateOutcome = {
error?: string;
results: TemplateCreateResultEntry[];
};