Repository navigation
Expand file tree
/
Copy pathworkflow.ts
More file actions
331 lines (312 loc) · 11.1 KB
/
Copy pathworkflow.ts
File metadata and controls
331 lines (312 loc) · 11.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
/**
* prompt-to-app — one API call to a deployed app on Render.
* delete-app — one API call to remove that app again.
*
* Each stage is one call here. The details live in each stage's module:
* build, verify, publish, deploy, or delete.
*/
import { type TaskContext, task } from "@renderinc/sdk/workflows";
import {
appPath,
appRelativePath,
factoryConfig,
} from "../factory.config.js";
import { architectTask } from "./agents.js";
import { buildAndVerify } from "./build.js";
import { agentJson } from "./claude.js";
import { appsRepo, renderWorkspaceId } from "./config.js";
import {
type AppSpec,
type DeleteAppInput,
deleteAppInputSchema,
deployPlanSchema,
type WorkflowResult,
workflowInputSchema,
} from "./contracts.js";
import {
DELETE_STEP_TIMEOUT_SECONDS,
deleteResourcesTask,
removeFilesTask,
removeFromBlueprintTask,
waitForSyncsTask,
} from "./delete.js";
import { awaitDeployment, deploysBeforePublish } from "./deploy.js";
import { initAppDir } from "./git.js";
import { collectImages } from "./images.js";
import { oneLine, publishAppTask } from "./publish.js";
import {
createSandbox,
ensureSandboxPostgres,
type Sandbox,
sandboxGroupId,
} from "./sandbox.js";
import {
claimRunApp,
deleteRuns,
failDelete,
finishRun,
setRunSandbox,
setRunStage,
} from "./store.js";
import { materializeTemplate } from "./templates.js";
const SANDBOX_TIMEOUT_SECONDS = 2 * 60 * 60;
/** Directory under templates/ that a multi-service app starts from. */
const FULLSTACK_TEMPLATE = "fullstack";
/** delete-app waits for its four steps. */
const DELETE_TIMEOUT_SECONDS = 4 * DELETE_STEP_TIMEOUT_SECONDS;
export const promptToApp = task(
{
name: "prompt-to-app",
plan: "flex",
timeoutSeconds: SANDBOX_TIMEOUT_SECONDS,
// Render Workflows retries a failed run three times by default. A retry
// starts again at the architect with a new sandbox, and after a push it
// can deploy a second app. It also starts after the catch below sets the
// runs row to "failed", so the concurrency limit does not count it. A
// caller posts the prompt again to start a new run.
retry: { maxRetries: 0, waitDurationMs: 0 },
},
async function promptToApp(
tasks: TaskContext,
rawInput: unknown,
): Promise<WorkflowResult> {
const { prompt, user, runId } = workflowInputSchema.parse(rawInput);
try {
const result = await run(tasks, prompt, user, runId);
await finishRun(runId, result.status, {
summary: result.summary.slice(0, 4_000),
});
return result;
} catch (error) {
const summary = error instanceof Error ? error.message : String(error);
await finishRun(runId, "failed", {
summary: summary.slice(0, 1_000),
}).catch((storeError) =>
console.error("Failed to record run failure:", storeError),
);
throw error;
}
},
);
/**
* The pipeline. Each agent, verify-app, and publish-app runs as a subtask on
* its own compute through `tasks`, the context Render Workflows gives
* prompt-to-app. On Render, each subtask has its own run, input, result, and
* logs.
*
* The builder and verify-app work in the run's sandbox. publish-app copies
* the app's files out of it.
*/
async function run(
tasks: TaskContext,
prompt: string,
user: string,
runId: string,
): Promise<WorkflowResult> {
const repo = appsRepo();
const workspaceId = renderWorkspaceId();
// ── Design ──────────────────────────────────────────────────────────
await setRunStage(runId, "designing");
const plan = await agentJson(
(message) => tasks.run(architectTask, { message }),
deployPlanSchema,
`Product prompt:\n${prompt}`,
"architect",
);
const appName = uniqueAppName(plan.appName, runId);
const blueprintPath = `${appRelativePath(user, appName)}/render.yaml`;
// Returned, not thrown: a delete in progress, or a different run of the
// same app, is an expected result, not a fault in the run.
const claim = await claimRunApp(runId, user, { appName, blueprintPath });
if (!claim.claimed) {
return {
status: "failed",
summary:
claim.reason === "deleting"
? `${user}/${appName} is being deleted. Submit the prompt again when the delete finishes.`
: `A different run is building ${user}/${appName}. Submit the prompt again when that run finishes.`,
};
}
const sandbox = await createSandbox({
timeoutSeconds: SANDBOX_TIMEOUT_SECONDS,
egress: factoryConfig.sandbox.buildEgress,
});
try {
await recordSandbox(runId, sandbox);
const appDir = appPath(user, appName);
// Every agent path resolves against this, so it has to exist first.
// The agents can run any command in this sandbox, so it gets no clone
// of the apps repository and no GitHub token: it holds only this app.
// publish-app pushes from a sandbox of its own.
await initAppDir(sandbox, appDir);
// ── Database and skeleton ───────────────────────────────────────
// A real Postgres, before the builder starts, so the schema and the
// seed are exercised here rather than for the first time in production.
let databaseUrl: string | null = null;
let template: string[] = [];
if (plan.tiers.some((tier) => tier.kind === "postgres")) {
await setRunStage(runId, "provisioning");
databaseUrl = await ensureSandboxPostgres(sandbox);
}
// A multi-service app has to get CORS, the API's base URL, and the
// migration path right before it works at all, and none of those are
// things the prompt can reliably re-derive per run. The template
// answers them; the builder still owns the product.
if (plan.tiers.some((tier) => tier.kind === "web_service")) {
template = await materializeTemplate(sandbox, FULLSTACK_TEMPLATE, appDir);
}
// ── Imagery ─────────────────────────────────────────────────────
await setRunStage(runId, "curating");
const images = await collectImages(sandbox, appDir, plan.assetQueries);
// ── Build and verify ────────────────────────────────────────────
await setRunStage(runId, "building");
const built = await buildAndVerify({
tasks,
sandbox,
appDir,
user,
appName,
plan,
prompt,
runId,
images,
databaseUrl,
template,
});
if (!built.passed) {
return { status: "build_failed", summary: built.failures.slice(0, 2_000) };
}
const spec: AppSpec = {
user,
appName,
prompt,
summary: plan.summary,
createdAt: new Date().toISOString(),
resourcePrefix: factoryConfig.resourcePrefix,
manifest: built.manifest,
};
// ── Publish ─────────────────────────────────────────────────────
await setRunStage(runId, "publishing");
// Read before the push. If the app's services already exist, their
// newest deploys right after the push are still the old ones.
const deploysBefore = await deploysBeforePublish(workspaceId, spec);
const { commit, changedServices } = await tasks.run(publishAppTask, {
sandboxId: sandbox.id,
spec,
message: `${user}/${appName}: ${oneLine(prompt)}`,
});
if (!commit) {
return { status: "build_failed", summary: "The run produced no files." };
}
// ── Deploy ──────────────────────────────────────────────────────
return await awaitDeployment({
tasks,
sandbox,
workspaceId,
repoUrl: repo.url,
spec,
appDir,
runId,
summary: built.summary,
databaseUrl,
deploysBefore,
changedServices,
});
} finally {
await sandbox
.terminate()
.catch((error) => console.error("Failed to terminate sandbox:", error));
}
}
/**
* The architect names the app from the prompt, so two similar prompts can
* choose the same name, and the second run would replace the first app. The
* start of the run ID keeps them apart. resourceStem() keeps 24 characters
* of the name, so the base is cut to 19 to keep the suffix.
*/
export function uniqueAppName(base: string, runId: string): string {
const suffix = runId.replace(/[^a-z0-9]/gi, "").slice(0, 4).toLowerCase();
return `${base.slice(0, 19).replace(/-+$/, "")}-${suffix}`;
}
/**
* The UI links to the sandbox in the Render Dashboard. Only the link needs
* this, so a failure does not stop the run.
*/
async function recordSandbox(runId: string, sandbox: Sandbox): Promise<void> {
const groupId = await sandboxGroupId().catch((error) => {
console.error("Failed to read the sandbox group:", error);
return null;
});
await setRunSandbox(runId, { id: sandbox.id, groupId }).catch((error) =>
console.error("Failed to record the sandbox of the run:", error),
);
}
interface DeleteResult {
status: "deleted";
user: string;
appName: string;
/** The Render resources that the delete removed. */
deleted: string[];
}
/**
* Render does not retry this task. A delete that fails marks the runs of the
* app delete_failed, and a new request starts it again. Each step reads the
* state that an earlier attempt left, so a new attempt does only what is left.
*/
export const deleteApp = task(
{
name: "delete-app",
plan: "flex",
timeoutSeconds: DELETE_TIMEOUT_SECONDS,
retry: { maxRetries: 0, waitDurationMs: 0 },
},
async function deleteApp(
tasks: TaskContext,
rawInput: unknown,
): Promise<DeleteResult> {
const app = deleteAppInputSchema.parse(rawInput);
try {
const deleted = await removeApp(tasks, app);
await deleteRuns(app.user, app.appName);
console.log(JSON.stringify({ event: "app_deleted", ...app, deleted }));
return { status: "deleted", ...app, deleted };
} catch (error) {
const summary = error instanceof Error ? error.message : String(error);
console.error(
JSON.stringify({ event: "app_delete_failed", ...app, error: summary }),
);
await failDelete(app.user, app.appName, summary.slice(0, 1_000)).catch(
(storeError) =>
console.error("Failed to record delete failure:", storeError),
);
throw error;
}
},
);
/**
* Delete one app in the order that a Blueprint allows. A sync recreates a
* declared resource that is missing, and it never deletes a resource that
* leaves the file. So the first step takes the app out of the root Blueprint,
* the resources are deleted when no sync of an earlier commit can run, and
* the last step removes the files. Until then factory.json stays, with
* deletedAt set, because a new attempt reads it to find the resources.
*
* Each step is a subtask. On Render, each one has its own run, with its
* input, its result, and its logs.
*/
export async function removeApp(
tasks: TaskContext,
app: DeleteAppInput,
): Promise<string[]> {
const removed = await tasks.run(removeFromBlueprintTask, app);
let deleted: string[] = [];
if (removed) {
await tasks.run(waitForSyncsTask, { ...app, pushedAt: removed.pushedAt });
deleted = await tasks.run(deleteResourcesTask, {
...app,
resourcePrefix: removed.resourcePrefix,
});
}
await tasks.run(removeFilesTask, app);
return deleted;
}