@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, 04:45 UTC

main
ts 600 lines 22.2 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetServicesResponse,
4 type GetProjectBranchesResponse,
5 type GetProjectDatabasesResponse,
6 type GetProjectsResponse,
7 type GetSourceRepositoriesResponse,
8 deleteSourceRepository,
9 getServices,
10 getService,
11 getDatabase,
12 getProjects,
13 getProjectBranches,
14 getProjectDatabases,
15 getSourceRepositories,
16 getSourceRepository,
17 createSourceRepository,
18 } from "@distilled.cloud/prisma/management";
19 import { Unowned } from "alchemy/AdoptPolicy";
20 import { isResolved } from "alchemy/Diff";
21 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
22 import * as Provider from "alchemy/Provider";
23 import { Resource } from "alchemy/Resource";
24 import * as Data from "effect/Data";
25 import * as Effect from "effect/Effect";
26 import * as Schedule from "effect/Schedule";
27 import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
28 import type { ObservedSourceRepository } from "./internal/Observed.ts";
29 import { PrismaPaginationError } from "./internal/Pagination.ts";
30 import {
31 concreteIdsChanged,
32 isInputObject,
33 isPrismaDevId,
34 resolveProjectId,
35 unresolvedProjectIdOf,
36 } from "./internal/Refs.ts";
37 import type { Project } from "./Project.ts";
38 import type { Providers } from "./Providers.ts";
39
40 export class SourceRepositoryConflict extends Data.TaggedError("SourceRepositoryConflict")<{
41 readonly message: string;
42 readonly cause?: unknown;
43 }> {}
44
45 export class SourceRepositoryInvalidProps extends Data.TaggedError("SourceRepositoryInvalidProps")<{
46 readonly message: string;
47 readonly cause?: unknown;
48 }> {}
49
50 export class SourceRepositoryOperationFailed extends Data.TaggedError(
51 "SourceRepositoryOperationFailed",
52 )<{
53 readonly message: string;
54 readonly cause?: unknown;
55 }> {}
56
57 export interface SourceRepositoryProps {
58 /**
59 * Project ID or project output to link. Linking has Management API side
60 * effects: it creates/renames the default branch and attaches currently
61 * unassigned databases and apps. To order downstream resources
62 * after those effects, pass this resource's `projectId` output to them.
63 * Deleting this resource only disconnects the repository link; Prisma
64 * preserves branches and resources that were attached while linking.
65 */
66 project: string | Project;
67 /**
68 * Git provider.
69 *
70 * @default "github"
71 */
72 provider?: "github";
73 /**
74 * GitHub's permanent numeric repository ID, not `owner/repo`, a Prisma
75 * project ID, or an SCM installation ID. Retrieve it with:
76 *
77 * ```bash
78 * gh api repos/OWNER/REPO --jq '.id'
79 * ```
80 */
81 providerRepositoryId: number;
82 /**
83 * Optional SCM installation ID to use for linking. When omitted, Prisma
84 * auto-picks the workspace's installation.
85 */
86 installationId?: string;
87 }
88
89 export interface SourceRepository extends Resource<
90 "Prisma.SourceRepository",
91 SourceRepositoryProps,
92 {
93 /**
94 * Prisma source repository link ID.
95 */
96 sourceRepositoryId: string;
97 /**
98 * Project ID linked to the repository.
99 */
100 projectId: string;
101 /**
102 * Numeric provider repository ID.
103 */
104 repoId: number;
105 /**
106 * Source control provider.
107 */
108 provider: "github";
109 /**
110 * Full repository name, for example "owner/repo".
111 */
112 repoFullName: string;
113 /**
114 * Default repository branch.
115 */
116 defaultBranch: string;
117 /**
118 * Whether the repository is private.
119 */
120 isPrivate: boolean;
121 /**
122 * Link status.
123 */
124 status: "active" | "archived";
125 /**
126 * SCM installation ID used for the link.
127 */
128 installationId: string;
129 /**
130 * ISO timestamp when the link was created.
131 */
132 createdAt: string;
133 /**
134 * ISO timestamp when the link was last updated.
135 */
136 updatedAt: string;
137 },
138 never,
139 Providers
140 > {}
141
142 /**
143 * A linked source repository for Prisma apps.
144 *
145 * GitHub is currently the only supported provider. Linking requires an
146 * existing Prisma SCM installation. `providerRepositoryId` is GitHub's
147 * permanent numeric repository ID; retrieve it with
148 * `gh api repos/OWNER/REPO --jq '.id'`. When `installationId` is omitted,
149 * Prisma selects the workspace installation.
150 *
151 * Linking creates or renames the repository-owned default branch. Observe
152 * that branch through the Management API; do not declare it again as a
153 * separate `Prisma.Branch` resource. Use this resource's outputs to order
154 * downstream databases and apps after the link side effects complete.
155 * Deleting the link does not roll those side effects back: existing branches,
156 * databases, and apps remain in the project.
157 *
158 * The project, repository ID, provider, and installation form an immutable
159 * link identity. Alchemy refuses an automatic relink because unlinking cannot
160 * roll back branch and resource attachments. Existing links require explicit
161 * adoption.
162 *
163 * ### Finding the Repository ID
164 * **Example:** Read the numeric GitHub repository ID
165 * ```bash
166 * gh api repos/OWNER/REPO --jq '.id'
167 * ```
168 *
169 * ### Linking a Repository
170 * **Example:** GitHub repository
171 * ```typescript
172 * const repo = yield* Prisma.SourceRepository("repo", {
173 * project: project.projectId,
174 * // Replace with the value returned by the GitHub command above.
175 * providerRepositoryId: 123456789,
176 * });
177 * const database = yield* Prisma.Database("database", {
178 * project: repo.projectId,
179 * branchGitName: repo.defaultBranch,
180 * });
181 * ```
182 *
183 * @resource
184 * @product Compute
185 */
186 export const SourceRepository = Resource<SourceRepository>("Prisma.SourceRepository");
187
188 // Distilled emits the cursor-paginated list operations as plain ops, so
189 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
190 const listSourceRepositories = (projectId: string) =>
191 Effect.gen(function* () {
192 const repos: GetSourceRepositoriesResponse["data"][number][] = [];
193 let cursor: string | undefined;
194 while (true) {
195 const page = yield* getSourceRepositories(
196 cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor },
197 );
198 repos.push(...page.data);
199 const nextCursor = page.pagination.nextCursor;
200 if (!page.pagination.hasMore) break;
201 if (nextCursor === null) {
202 return yield* new PrismaPaginationError({
203 message:
204 "Invalid Prisma Management API pagination response from getSourceRepositories: hasMore was true without a non-empty nextCursor",
205 });
206 }
207 cursor = nextCursor;
208 }
209 return repos;
210 });
211
212 const findRepository = (projectId: string) =>
213 listSourceRepositories(projectId).pipe(
214 Effect.flatMap((repos) => {
215 const active = repos.filter((repo: ObservedSourceRepository) => repo.status === "active");
216 return active.length > 1
217 ? Effect.fail(
218 new SourceRepositoryConflict({
219 message: `Prisma project '${projectId}' has multiple active source repositories; refusing to select one arbitrarily.`,
220 }),
221 )
222 : Effect.succeed(active[0]);
223 }),
224 );
225
226 const matchesDesiredRepository = (
227 repo: ObservedSourceRepository,
228 projectId: string,
229 props: SourceRepositoryProps,
230 ) =>
231 repo.status === "active" &&
232 repo.projectId === projectId &&
233 repo.repoId === props.providerRepositoryId &&
234 repo.provider === (props.provider ?? "github") &&
235 (props.installationId === undefined || repo.installationId === props.installationId);
236
237 const attrsFrom = (repo: ObservedSourceRepository): SourceRepository["Attributes"] => ({
238 sourceRepositoryId: repo.id,
239 projectId: repo.projectId,
240 repoId: repo.repoId,
241 provider: repo.provider,
242 repoFullName: repo.repoFullName,
243 defaultBranch: repo.defaultBranch,
244 isPrivate: repo.isPrivate,
245 status: repo.status,
246 installationId: repo.installationId,
247 createdAt: repo.createdAt,
248 updatedAt: repo.updatedAt,
249 });
250
251 class SourceRepositoryLinkNotReady extends Data.TaggedError("SourceRepositoryLinkNotReady")<{
252 readonly message: string;
253 }> {}
254
255 const sourceRepositoryConsistencySchedule = Schedule.max([
256 Schedule.exponential("250 millis"),
257 Schedule.recurs(5),
258 ]);
259
260 const verifyRepositoryLink = Effect.fn(function* (
261 repo: ObservedSourceRepository,
262 expectedAppIds: readonly string[] = [],
263 expectedDatabaseIds: readonly string[] = [],
264 ) {
265 const observed = (yield* getSourceRepository({ id: repo.id })).data;
266 if (
267 observed.status !== "active" ||
268 observed.projectId !== repo.projectId ||
269 observed.repoId !== repo.repoId ||
270 observed.provider !== repo.provider ||
271 observed.installationId !== repo.installationId
272 ) {
273 return yield* new SourceRepositoryLinkNotReady({
274 message: `Prisma source repository link '${repo.id}' has not converged to its requested immutable identity.`,
275 });
276 }
277 const listDefaultBranches = Effect.gen(function* () {
278 const items: GetProjectBranchesResponse["data"][number][] = [];
279 let cursor: string | undefined;
280 while (true) {
281 const page = yield* getProjectBranches(
282 cursor === undefined
283 ? {
284 projectId: repo.projectId,
285 gitName: observed.defaultBranch,
286 limit: 100,
287 }
288 : {
289 projectId: repo.projectId,
290 gitName: observed.defaultBranch,
291 limit: 100,
292 cursor,
293 },
294 );
295 items.push(...page.data);
296 const nextCursor = page.pagination.nextCursor;
297 if (!page.pagination.hasMore) break;
298 if (nextCursor === null) {
299 return yield* new PrismaPaginationError({
300 message:
301 "Invalid Prisma Management API pagination response from getProjectBranches: hasMore was true without a non-empty nextCursor",
302 });
303 }
304 cursor = nextCursor;
305 }
306 return items;
307 });
308 const branches = yield* listDefaultBranches;
309 const defaults = branches.filter(
310 (branch) => branch.gitName === observed.defaultBranch && branch.isDefault === true,
311 );
312 if (defaults.length !== 1) {
313 return yield* new SourceRepositoryLinkNotReady({
314 message: `Prisma source repository link '${repo.id}' did not produce exactly one default branch named '${observed.defaultBranch}'.`,
315 });
316 }
317 const branchId = defaults[0]!.id;
318 yield* Effect.forEach(
319 expectedAppIds,
320 (appId) =>
321 getService({ serviceId: appId }).pipe(
322 Effect.map((response) => response.data),
323 Effect.flatMap((app) =>
324 app.branchId === branchId
325 ? Effect.void
326 : Effect.fail(
327 new SourceRepositoryLinkNotReady({
328 message: `Prisma App '${appId}' was not attached to repository branch '${branchId}'.`,
329 }),
330 ),
331 ),
332 ),
333 { concurrency: 8 },
334 );
335 yield* Effect.forEach(
336 expectedDatabaseIds,
337 (databaseId) =>
338 getDatabase({ databaseId }).pipe(
339 Effect.map((response) => response.data),
340 Effect.flatMap((database) =>
341 database.branchId === branchId
342 ? Effect.void
343 : Effect.fail(
344 new SourceRepositoryLinkNotReady({
345 message: `Prisma database '${databaseId}' was not attached to repository branch '${branchId}'.`,
346 }),
347 ),
348 ),
349 ),
350 { concurrency: 8 },
351 );
352 return observed;
353 });
354
355 const ProviderLive = () =>
356 Provider.effect(
357 SourceRepository,
358 Effect.gen(function* () {
359 return {
360 stables: ["sourceRepositoryId"],
361 list: Effect.fn(function* () {
362 const listProjects = Effect.gen(function* () {
363 const items: GetProjectsResponse["data"][number][] = [];
364 let cursor: string | undefined;
365 while (true) {
366 const page = yield* getProjects(cursor === undefined ? {} : { cursor });
367 items.push(...page.data);
368 const nextCursor = page.pagination.nextCursor;
369 if (!page.pagination.hasMore) break;
370 if (nextCursor === null) {
371 return yield* new PrismaPaginationError({
372 message:
373 "Invalid Prisma Management API pagination response from getProjects: hasMore was true without a non-empty nextCursor",
374 });
375 }
376 cursor = nextCursor;
377 }
378 return items;
379 });
380 const projects = yield* listProjects;
381 const repositories = yield* Effect.forEach(
382 projects,
383 (project) =>
384 listSourceRepositories(project.id).pipe(
385 Effect.catchTag("NotFound", () => Effect.succeed([])),
386 ),
387 { concurrency: 8 },
388 );
389 return repositories.flat().map(attrsFrom);
390 }),
391 diff: Effect.fn(function* ({ olds, news, output }) {
392 if (!isInputObject(news)) return undefined;
393 if (isPrismaDevId(output?.sourceRepositoryId)) {
394 return { action: "update" } as const;
395 }
396 const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project);
397 const newProjectId = isResolved(news.project)
398 ? unresolvedProjectIdOf(news.project)
399 : undefined;
400 const newRepositoryId = isResolved(news.providerRepositoryId)
401 ? news.providerRepositoryId
402 : undefined;
403 const observedMismatch =
404 output &&
405 ((newProjectId !== undefined && output.projectId !== newProjectId) ||
406 (newRepositoryId !== undefined && output.repoId !== newRepositoryId) ||
407 (isResolved(news.provider) && output.provider !== (news.provider ?? "github")) ||
408 (isResolved(news.installationId) &&
409 news.installationId !== undefined &&
410 output.installationId !== news.installationId) ||
411 output.status !== "active");
412 if (
413 concreteIdsChanged(oldProjectId, newProjectId) ||
414 (isResolved(news.provider) &&
415 (news.provider ?? "github") !== (olds.provider ?? "github")) ||
416 (isResolved(news.providerRepositoryId) &&
417 news.providerRepositoryId !== olds.providerRepositoryId) ||
418 (isResolved(news.installationId) && news.installationId !== olds.installationId) ||
419 observedMismatch
420 ) {
421 return yield* new SourceRepositoryInvalidProps({
422 message: `Prisma source repository links cannot be replaced atomically: unlinking mutates branch/resource attachments and a failed relink cannot restore them. Create a new project or explicitly unlink and relink in separate reviewed deployments.`,
423 });
424 }
425 return undefined;
426 }),
427 read: Effect.fn(function* ({ output, olds }) {
428 const sourceRepositoryId = isPrismaDevId(output?.sourceRepositoryId)
429 ? undefined
430 : output?.sourceRepositoryId;
431 const findRepositoryInProject = Effect.gen(function* () {
432 const projectId = unresolvedProjectIdOf(olds.project);
433 return projectId ? yield* findRepository(projectId) : undefined;
434 });
435 const repo = sourceRepositoryId
436 ? yield* getSourceRepository({
437 id: sourceRepositoryId,
438 }).pipe(
439 Effect.map((response) => response.data),
440 Effect.catchTag("NotFound", () => Effect.undefined),
441 )
442 : yield* findRepositoryInProject;
443 if (!repo) return undefined;
444 const attrs = attrsFrom(repo);
445 return sourceRepositoryId === undefined ? Unowned(attrs) : attrs;
446 }),
447 reconcile: Effect.fn(function* ({ news, output }) {
448 const projectId = yield* resolveProjectId(news.project);
449 const sourceRepositoryId = isPrismaDevId(output?.sourceRepositoryId)
450 ? undefined
451 : output?.sourceRepositoryId;
452 let repo = sourceRepositoryId
453 ? yield* getSourceRepository({
454 id: sourceRepositoryId,
455 }).pipe(
456 Effect.map((response) => response.data),
457 Effect.catchTag("NotFound", () => Effect.undefined),
458 )
459 : undefined;
460 if (repo && !matchesDesiredRepository(repo, projectId, news)) {
461 return yield* new SourceRepositoryConflict({
462 message: `Prisma project '${projectId}' is already linked to '${repo.repoFullName}'. The Management API has no atomic relink or rollback operation, so this provider will not delete the live link during reconcile. Explicitly unlink it in a separate reviewed deployment before linking repository '${news.providerRepositoryId}'.`,
463 });
464 }
465 if (!repo) {
466 const listUnassignedApps = Effect.gen(function* () {
467 const items: GetServicesResponse["data"][number][] = [];
468 let cursor: string | undefined;
469 while (true) {
470 const page = yield* getServices(
471 cursor === undefined
472 ? { projectId, branchId: "unassigned", limit: 100 }
473 : { projectId, branchId: "unassigned", limit: 100, cursor },
474 );
475 items.push(...page.data);
476 const nextCursor = page.pagination.nextCursor;
477 if (!page.pagination.hasMore) break;
478 if (nextCursor === null) {
479 return yield* new PrismaPaginationError({
480 message:
481 "Invalid Prisma Management API pagination response from getServices: hasMore was true without a non-empty nextCursor",
482 });
483 }
484 cursor = nextCursor;
485 }
486 return items;
487 });
488 const previouslyUnassignedApps = (yield* listUnassignedApps).map((app) => app.id);
489 const listProjectDatabases = Effect.gen(function* () {
490 const items: GetProjectDatabasesResponse["data"][number][] = [];
491 let cursor: string | undefined;
492 while (true) {
493 const page = yield* getProjectDatabases(
494 cursor === undefined
495 ? { projectId, limit: 100 }
496 : { projectId, limit: 100, cursor },
497 );
498 items.push(...page.data);
499 const nextCursor = page.pagination.nextCursor;
500 if (!page.pagination.hasMore) break;
501 if (nextCursor === null) {
502 return yield* new PrismaPaginationError({
503 message:
504 "Invalid Prisma Management API pagination response from getProjectDatabases: hasMore was true without a non-empty nextCursor",
505 });
506 }
507 cursor = nextCursor;
508 }
509 return items;
510 });
511 const previouslyUnassignedDatabases = (yield* listProjectDatabases)
512 .filter((database) => database.branchId === null)
513 .map((database) => database.id);
514 repo = yield* createSourceRepository({
515 projectId,
516 provider: news.provider ?? "github",
517 providerRepositoryId: news.providerRepositoryId,
518 ...(news.installationId === undefined ? {} : { installationId: news.installationId }),
519 }).pipe(
520 // A replayed create would link the repository twice; the retry
521 // policy cannot see the request, so opt out explicitly.
522 Retry.none,
523 Effect.map((response) => response.data),
524 Effect.catchTag("Conflict", () =>
525 Effect.fail(
526 new SourceRepositoryConflict({
527 message: `Prisma source repository '${news.providerRepositoryId}' appeared after the adoption check. Refusing to take over the project link; rerun with adoption enabled if it is the intended repository.`,
528 }),
529 ),
530 ),
531 );
532 repo = yield* verifyRepositoryLink(
533 repo,
534 previouslyUnassignedApps,
535 previouslyUnassignedDatabases,
536 ).pipe(
537 Effect.retry({
538 while: (error) => error instanceof SourceRepositoryLinkNotReady,
539 schedule: sourceRepositoryConsistencySchedule,
540 }),
541 Effect.mapError(
542 (error) =>
543 new SourceRepositoryOperationFailed({
544 message: `Prisma source repository link '${repo!.id}' was created but its branch/resource side effects did not converge. The link was not deleted because unlinking cannot roll back partial attachments; inspect it and adopt after repair.`,
545 cause: error,
546 }),
547 ),
548 );
549 } else {
550 repo = yield* verifyRepositoryLink(repo);
551 }
552 return attrsFrom(repo);
553 }),
554 delete: Effect.fn(function* ({ output }) {
555 if (isPrismaDevId(output.sourceRepositoryId)) return;
556 const repo = yield* getSourceRepository({
557 id: output.sourceRepositoryId,
558 }).pipe(
559 Effect.map((response) => response.data),
560 Effect.catchTag("NotFound", () => Effect.undefined),
561 );
562 if (!repo) return;
563 if (
564 repo.projectId !== output.projectId ||
565 repo.repoId !== output.repoId ||
566 repo.provider !== output.provider ||
567 repo.installationId !== output.installationId
568 ) {
569 return yield* new SourceRepositoryConflict({
570 message: `Prisma source repository '${repo.id}' no longer matches its persisted project/repository/installation identity. Refusing to delete a mismatched link.`,
571 });
572 }
573 yield* deleteSourceRepository({ id: repo.id }).pipe(
574 Effect.catchTag("NotFound", () => Effect.void),
575 );
576 }),
577 };
578 }),
579 );
580
581 const ProviderLocal = () =>
582 devProvider(SourceRepository, ["sourceRepositoryId"], ({ id, news }) => ({
583 sourceRepositoryId: devId("source-repository", id),
584 projectId: attrOrString(news.project, "projectId"),
585 repoId: news.providerRepositoryId,
586 provider: news.provider ?? "github",
587 repoFullName: `dev/${id}`,
588 defaultBranch: "main",
589 isPrivate: false,
590 status: "active",
591 installationId: devId("installation", id),
592 createdAt: DEV_TIMESTAMP,
593 updatedAt: DEV_TIMESTAMP,
594 }));
595
596 export const SourceRepositoryProvider = () =>
597 ProviderLayer.dual(SourceRepository, {
598 local: () => ProviderLocal(),
599 live: () => ProviderLive(),
600 });