@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 482 lines 18.3 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetProjectBranchesResponse,
4 type GetProjectsResponse,
5 deleteBranch,
6 getBranch,
7 getProjects,
8 getProjectBranches,
9 updateBranch,
10 createProjectBranch,
11 } from "@distilled.cloud/prisma/management";
12 import { Unowned } from "alchemy/AdoptPolicy";
13 import { isResolved } from "alchemy/Diff";
14 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
15 import { createPhysicalName } from "alchemy/PhysicalName";
16 import * as Provider from "alchemy/Provider";
17 import { Resource } from "alchemy/Resource";
18 import * as Data from "effect/Data";
19 import * as Effect from "effect/Effect";
20 import * as Schedule from "effect/Schedule";
21 import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
22 import type { ObservedBranch } from "./internal/Observed.ts";
23 import { PrismaPaginationError } from "./internal/Pagination.ts";
24 import {
25 concreteIdsChanged,
26 isInputObject,
27 isPrismaDevId,
28 resolveProjectId,
29 unresolvedProjectIdOf,
30 } from "./internal/Refs.ts";
31 import type { Project } from "./Project.ts";
32 import type { Providers } from "./Providers.ts";
33
34 export class BranchConflict extends Data.TaggedError("BranchConflict")<{
35 readonly message: string;
36 readonly cause?: unknown;
37 }> {}
38
39 export class BranchOperationFailed extends Data.TaggedError("BranchOperationFailed")<{
40 readonly message: string;
41 readonly cause?: unknown;
42 }> {}
43
44 export class BranchUnexpectedResponse extends Data.TaggedError("BranchUnexpectedResponse")<{
45 readonly message: string;
46 readonly cause?: unknown;
47 }> {}
48
49 export interface BranchProps {
50 /**
51 * Project ID or `project.projectId` output that owns this branch.
52 */
53 project: string | Project;
54 /**
55 * Git-style branch name. If omitted, Alchemy generates a stable physical
56 * name.
57 */
58 gitName?: string;
59 /**
60 * Promote this branch to be the project's default branch. Setting this to
61 * `false` does not demote a current default because the Management API only
62 * supports promotion; promoting another branch atomically demotes it.
63 * Promotion changes `isDefault`, not the branch's immutable `preview` role.
64 *
65 * @default false
66 */
67 isDefault?: boolean;
68 }
69
70 export interface Branch extends Resource<
71 "Prisma.Branch",
72 BranchProps,
73 {
74 /**
75 * Prisma branch ID.
76 */
77 branchId: string;
78 /**
79 * Git-style branch name.
80 */
81 gitName: string;
82 /**
83 * Project ID that owns the branch.
84 */
85 projectId: string;
86 /**
87 * Whether this branch is the project's default branch.
88 */
89 isDefault: boolean;
90 /**
91 * Branch that was default before this preview branch was promoted. Alchemy
92 * restores it before deleting this resource so destroy remains reversible.
93 */
94 previousDefaultBranchId?: string;
95 /**
96 * Branch role used by Prisma to resolve deploy-time environment variables.
97 */
98 role: "production" | "preview";
99 /**
100 * ISO timestamp when the branch was created.
101 */
102 createdAt: string;
103 /**
104 * ISO timestamp when the branch was last updated.
105 */
106 updatedAt: string;
107 },
108 never,
109 Providers
110 > {}
111
112 /**
113 * A Prisma project branch for preview-class databases and compute resources.
114 *
115 * Standalone Branch resources always have the `preview` role. Promotion
116 * changes only the default branch; Alchemy restores the previous default
117 * before deleting a promoted branch.
118 *
119 * ### Creating a Branch
120 * **Example:** Preview branch
121 * ```typescript
122 * const branch = yield* Prisma.Branch("preview", {
123 * project: project.projectId,
124 * gitName: "feature/search", // optional — omitted, a stable name is generated
125 * });
126 *
127 * branch.role; // "preview"
128 * branch.isDefault; // false
129 * ```
130 *
131 * ### Promoting a Branch
132 * **Example:** Make a preview branch the default
133 * ```typescript
134 * const release = yield* Prisma.Branch("release", {
135 * project,
136 * gitName: "release/next",
137 * isDefault: true,
138 * });
139 *
140 * release.role; // still "preview"
141 * release.isDefault; // true
142 * ```
143 *
144 * @resource
145 * @product Project
146 */
147 export const Branch = Resource<Branch>("Prisma.Branch");
148
149 const createGitName = (id: string, gitName: string | undefined) =>
150 gitName === undefined ? createPhysicalName({ id }) : Effect.succeed(gitName);
151
152 // Distilled emits the cursor-paginated list operations as plain ops, so
153 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
154 const listBranches = (projectId: string, query?: { readonly gitName?: string }) =>
155 Effect.gen(function* () {
156 const branches: GetProjectBranchesResponse["data"][number][] = [];
157 let cursor: string | undefined;
158 while (true) {
159 const page = yield* getProjectBranches({
160 projectId,
161 ...(query?.gitName === undefined ? {} : { gitName: query.gitName }),
162 ...(cursor === undefined ? {} : { cursor }),
163 });
164 branches.push(...page.data);
165 const nextCursor = page.pagination.nextCursor;
166 if (!page.pagination.hasMore) break;
167 if (nextCursor === null) {
168 return yield* new PrismaPaginationError({
169 message:
170 "Invalid Prisma Management API pagination response from getProjectBranches: hasMore was true without a non-empty nextCursor",
171 });
172 }
173 cursor = nextCursor;
174 }
175 return branches;
176 });
177
178 const listProjects = () =>
179 Effect.gen(function* () {
180 const projects: GetProjectsResponse["data"][number][] = [];
181 let cursor: string | undefined;
182 while (true) {
183 const page = yield* getProjects(cursor === undefined ? {} : { cursor });
184 projects.push(...page.data);
185 const nextCursor = page.pagination.nextCursor;
186 if (!page.pagination.hasMore) break;
187 if (nextCursor === null) {
188 return yield* new PrismaPaginationError({
189 message:
190 "Invalid Prisma Management API pagination response from getProjects: hasMore was true without a non-empty nextCursor",
191 });
192 }
193 cursor = nextCursor;
194 }
195 return projects;
196 });
197
198 const findBranch = (projectId: string, gitName: string) =>
199 listBranches(projectId, { gitName }).pipe(
200 Effect.flatMap((branches) => {
201 const matches = branches.filter((b: ObservedBranch) => b.gitName === gitName);
202 return matches.length > 1
203 ? Effect.fail(
204 new BranchConflict({
205 message: `Prisma project '${projectId}' has multiple branches named '${gitName}'; refusing to select one arbitrarily.`,
206 }),
207 )
208 : Effect.succeed(matches[0]);
209 }),
210 );
211
212 const attrsFrom = (
213 branch: ObservedBranch,
214 previousDefaultBranchId?: string,
215 ): Branch["Attributes"] => ({
216 branchId: branch.id,
217 gitName: branch.gitName,
218 projectId: branch.project.id,
219 isDefault: branch.isDefault,
220 ...(previousDefaultBranchId === undefined ? {} : { previousDefaultBranchId }),
221 role: branch.role,
222 createdAt: branch.createdAt,
223 updatedAt: branch.updatedAt,
224 });
225
226 const ensureBranchIdentity = (
227 branch: ObservedBranch,
228 expected: { projectId: string; gitName: string },
229 ) =>
230 branch.project.id === expected.projectId && branch.gitName === expected.gitName
231 ? Effect.void
232 : Effect.fail(
233 new BranchConflict({
234 message: `Prisma branch '${branch.id}' belongs to project '${branch.project.id}' with git name '${branch.gitName}', but this resource requires project '${expected.projectId}' and git name '${expected.gitName}'. Refusing to promote or delete a mismatched branch.`,
235 }),
236 );
237
238 const ProviderLive = () =>
239 Provider.effect(
240 Branch,
241 Effect.gen(function* () {
242 return {
243 stables: ["branchId"],
244 list: Effect.fn(function* () {
245 const projects = yield* listProjects();
246 const branches = yield* Effect.forEach(
247 projects,
248 (project) =>
249 listBranches(project.id).pipe(Effect.catchTag("NotFound", () => Effect.succeed([]))),
250 { concurrency: 8 },
251 );
252 // Current defaults and production-role branches are project-owned
253 // and undeletable through the Branch API. Project deletion removes
254 // them; omit them here so unsafe nuke only receives deletable rows.
255 return branches
256 .flat()
257 .filter((branch) => !branch.isDefault && branch.role !== "production")
258 .map((branch) => attrsFrom(branch));
259 }),
260 diff: Effect.fn(function* ({ id, olds, news, output }) {
261 if (!isInputObject(news)) return undefined;
262 if (isPrismaDevId(output?.branchId)) {
263 return { action: "update" } as const;
264 }
265 const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project);
266 const newProjectId = isResolved(news.project)
267 ? unresolvedProjectIdOf(news.project)
268 : undefined;
269 const newGitName = isResolved(news.gitName)
270 ? yield* createGitName(id, news.gitName)
271 : undefined;
272 if (
273 concreteIdsChanged(oldProjectId, newProjectId) ||
274 (newGitName !== undefined &&
275 newGitName !== (output?.gitName ?? (yield* createGitName(id, olds.gitName))))
276 ) {
277 return { action: "replace" } as const;
278 }
279 if (!isResolved(news.isDefault)) return undefined;
280 // The Management API can promote a branch, atomically demoting the
281 // old default, but explicitly rejects demoting the current default.
282 // `false` therefore means "do not promote", not "demote".
283 if (news.isDefault === true && output?.isDefault !== true) {
284 return { action: "update" } as const;
285 }
286 return undefined;
287 }),
288 read: Effect.fn(function* ({ id, output, olds }) {
289 const branchId = isPrismaDevId(output?.branchId) ? undefined : output?.branchId;
290 const findBranchInProject = Effect.gen(function* () {
291 const projectId = unresolvedProjectIdOf(olds.project);
292 return projectId
293 ? yield* findBranch(projectId, yield* createGitName(id, olds.gitName))
294 : undefined;
295 });
296 const branch = branchId
297 ? yield* getBranch({ branchId }).pipe(
298 Effect.map((response) => response.data),
299 Effect.catchTag("NotFound", () => Effect.undefined),
300 )
301 : yield* findBranchInProject;
302 if (!branch) return undefined;
303 const attrs = attrsFrom(branch, output?.previousDefaultBranchId);
304 return branchId === undefined ? Unowned(attrs) : attrs;
305 }),
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const projectId = yield* resolveProjectId(news.project);
308 const gitName = yield* createGitName(id, news.gitName);
309 let previousDefaultBranchId = output?.previousDefaultBranchId;
310 const branchId = isPrismaDevId(output?.branchId) ? undefined : output?.branchId;
311 let branch = branchId
312 ? yield* getBranch({ branchId }).pipe(
313 Effect.map((response) => response.data),
314 Effect.catchTag("NotFound", () => Effect.undefined),
315 )
316 : undefined;
317 if (!branch) {
318 const liveBranches = yield* listBranches(projectId);
319 const defaults = liveBranches.filter((candidate) => candidate.isDefault);
320 if (defaults.length !== 1) {
321 return yield* new BranchConflict({
322 message:
323 defaults.length === 0
324 ? `Prisma project '${projectId}' has no default branch. Refusing to create a standalone Branch because the Management API would make it the undeletable production branch; create or repair the owning Prisma.Project first.`
325 : `Prisma project '${projectId}' has ${defaults.length} default branches. Refusing to create a Branch until the project invariant is repaired.`,
326 });
327 }
328 previousDefaultBranchId = defaults[0]!.id;
329 branch = yield* createProjectBranch({
330 projectId,
331 gitName,
332 ...(news.isDefault === undefined ? {} : { isDefault: news.isDefault }),
333 }).pipe(
334 // A replayed create would make a second branch; the retry
335 // policy cannot see the request, so opt out explicitly.
336 Retry.none,
337 Effect.map((response) => response.data),
338 Effect.catchTag("Conflict", () =>
339 Effect.fail(
340 new BranchConflict({
341 message: `Prisma branch '${gitName}' appeared after the adoption check. Refusing to take it over; rerun with adoption enabled if it is the intended branch.`,
342 }),
343 ),
344 ),
345 );
346 }
347 yield* ensureBranchIdentity(branch, {
348 projectId,
349 gitName,
350 });
351 if (news.isDefault === true && !branch.isDefault) {
352 const liveBranches = yield* listBranches(projectId);
353 const defaults = liveBranches.filter((candidate) => candidate.isDefault);
354 if (defaults.length !== 1 || defaults[0]!.id === branch.id) {
355 return yield* new BranchConflict({
356 message: `Prisma project '${projectId}' does not have exactly one different default branch to restore later. Refusing to promote '${branch.gitName}'.`,
357 });
358 }
359 previousDefaultBranchId = defaults[0]!.id;
360 branch = (yield* updateBranch({
361 branchId: branch.id,
362 isDefault: true,
363 })).data;
364 yield* ensureBranchIdentity(branch, {
365 projectId,
366 gitName,
367 });
368 if (!branch.isDefault) {
369 return yield* new BranchUnexpectedResponse({
370 message: `Prisma branch '${branch.id}' promotion did not converge to the default branch.`,
371 });
372 }
373 }
374 return attrsFrom(branch, previousDefaultBranchId);
375 }),
376 delete: Effect.fn(function* ({ output }) {
377 if (isPrismaDevId(output.branchId)) return;
378 const branch = yield* getBranch({
379 branchId: output.branchId,
380 }).pipe(
381 Effect.map((response) => response.data),
382 Effect.catchTag("NotFound", () => Effect.undefined),
383 );
384 if (!branch) return;
385 yield* ensureBranchIdentity(branch, {
386 projectId: output.projectId,
387 gitName: output.gitName,
388 });
389 if (branch.role === "production") {
390 return yield* new BranchConflict({
391 message: `Cannot delete Prisma branch '${branch.gitName ?? output.branchId}' directly because its production role is immutable. Delete the owning Prisma.Project.`,
392 });
393 }
394 if (branch.isDefault) {
395 const previousDefaultBranchId = output.previousDefaultBranchId;
396 if (previousDefaultBranchId === undefined || previousDefaultBranchId === branch.id) {
397 return yield* new BranchConflict({
398 message: `Cannot safely delete default Prisma branch '${branch.gitName}' because state does not identify the branch it displaced. Promote another branch explicitly before deleting this resource.`,
399 });
400 }
401 const previous = yield* getBranch({
402 branchId: previousDefaultBranchId,
403 }).pipe(
404 Effect.map((response) => response.data),
405 Effect.catchTag("NotFound", () =>
406 Effect.fail(
407 new BranchOperationFailed({
408 message: `Cannot restore previous default Prisma branch '${previousDefaultBranchId}' because it no longer exists. Promote another branch explicitly before deleting '${branch.gitName}'.`,
409 }),
410 ),
411 ),
412 );
413 if (previous.project.id !== output.projectId || previous.id === branch.id) {
414 return yield* new BranchConflict({
415 message: `Previous default Prisma branch '${previous.id}' does not belong to project '${output.projectId}'. Refusing an unsafe promotion.`,
416 });
417 }
418 const restored = previous.isDefault
419 ? previous
420 : (yield* updateBranch({
421 branchId: previous.id,
422 isDefault: true,
423 })).data;
424 if (
425 restored.id !== previous.id ||
426 restored.project.id !== output.projectId ||
427 !restored.isDefault
428 ) {
429 return yield* new BranchUnexpectedResponse({
430 message: `Prisma did not confirm restoration of previous default branch '${previous.id}'. Refusing to delete '${branch.gitName}'.`,
431 });
432 }
433 const demoted = yield* getBranch({
434 branchId: branch.id,
435 }).pipe(
436 Effect.map((response) => response.data),
437 Effect.catchTag("NotFound", () => Effect.undefined),
438 );
439 if (!demoted) return;
440 yield* ensureBranchIdentity(demoted, {
441 projectId: output.projectId,
442 gitName: output.gitName,
443 });
444 if (demoted.isDefault) {
445 return yield* new BranchUnexpectedResponse({
446 message: `Prisma branch '${branch.gitName}' remained default after restoring '${previous.gitName}'. Refusing to delete it.`,
447 });
448 }
449 }
450 // A member deleted moments ago (e.g. an App) can still count as
451 // live until Prisma's control plane catches up.
452 yield* deleteBranch({
453 branchId: output.branchId,
454 }).pipe(
455 Effect.retry({
456 while: (error) => error._tag === "Conflict",
457 schedule: Schedule.exponential("500 millis"),
458 times: 6,
459 }),
460 Effect.catchTag("NotFound", () => Effect.void),
461 );
462 }),
463 };
464 }),
465 );
466
467 const ProviderLocal = () =>
468 devProvider(Branch, ["branchId"], ({ id, news }) => ({
469 branchId: devId("branch", id),
470 gitName: news.gitName ?? id,
471 projectId: attrOrString(news.project, "projectId"),
472 isDefault: news.isDefault ?? false,
473 role: news.isDefault ? "production" : "preview",
474 createdAt: DEV_TIMESTAMP,
475 updatedAt: DEV_TIMESTAMP,
476 }));
477
478 export const BranchProvider = () =>
479 ProviderLayer.dual(Branch, {
480 local: () => ProviderLocal(),
481 live: () => ProviderLive(),
482 });