@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 374 lines 13.8 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetBucketsResponse,
4 deleteBucket,
5 getBuckets,
6 getBucket,
7 createBucket,
8 updateBucket,
9 } from "@distilled.cloud/prisma/management";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import { desiredBranchId } from "./internal/Branches.ts";
18 import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
19 import type { ObservedBucket } from "./internal/Observed.ts";
20 import { PrismaPaginationError } from "./internal/Pagination.ts";
21 import {
22 concreteIdsChanged,
23 isInputObject,
24 isPrismaDevId,
25 resolveProjectId,
26 unresolvedProjectIdOf,
27 } from "./internal/Refs.ts";
28 import type { Project } from "./Project.ts";
29 import type { Providers } from "./Providers.ts";
30
31 export interface BucketProps {
32 /**
33 * Project ID or `project.projectId` output that owns this bucket.
34 */
35 project: string | Project;
36 /**
37 * Bucket display name. Prisma generates a name when omitted. The display
38 * name is not the provider-side S3 bucket name — S3 clients must use the
39 * `bucketName` attribute of `Prisma.BucketAccessKey`.
40 */
41 name?: string;
42 /**
43 * Branch ID to scope the bucket to, e.g. for per-branch preview storage.
44 * Every bucket belongs to a branch: omit it to let the Management API attach
45 * the bucket to the project's default branch, which Alchemy then leaves
46 * unmanaged.
47 */
48 branchId?: string;
49 /**
50 * Stable identity of this declaration on the Prisma platform, unique per
51 * branch. A rename in the Console does not change it. After lost state, the
52 * provider finds the bucket by it instead of creating a second one, and
53 * `--adopt` (or `adopt(true)`) takes it back over, because a logical ID alone
54 * does not prove which stack owns it. Changing it updates the bucket in place.
55 * @default the resource's fully qualified logical ID, e.g. `"uploads"` or `"App/Uploads"`
56 */
57 logicalId?: string;
58 }
59
60 export interface Bucket extends Resource<
61 "Prisma.Bucket",
62 BucketProps,
63 {
64 /**
65 * Prisma bucket ID.
66 */
67 bucketId: string;
68 /**
69 * Bucket display name. Not the provider-side S3 bucket name; S3 clients
70 * must use the `bucketName` attribute of `Prisma.BucketAccessKey`.
71 */
72 name: string;
73 /**
74 * Project ID that owns the bucket.
75 */
76 projectId: string;
77 /**
78 * ISO timestamp when the bucket was created.
79 */
80 createdAt: string;
81 /**
82 * Logical ID recorded on the bucket, or null when none is set.
83 */
84 logicalId: string | null;
85 },
86 never,
87 Providers
88 > {}
89
90 /**
91 * A Prisma Object Store bucket inside a Prisma project.
92 *
93 * A project change replaces the bucket. Display name, branch, and logical ID
94 * changes update it in place; the display name is a label only, so the
95 * provider-side bucket name, its objects, and its access keys stay the same.
96 * Destroying this resource deletes the bucket, its objects, and any remaining
97 * access keys — the Management API cascades the deletion server-side.
98 *
99 * ### Creating a Bucket
100 * **Example:** Bucket in a project
101 * ```typescript
102 * const bucket = yield* Prisma.Bucket("uploads", {
103 * project,
104 * name: "uploads",
105 * });
106 * ```
107 *
108 * ### Accessing a Bucket
109 * **Example:** S3 credentials for a bucket
110 * ```typescript
111 * const key = yield* Prisma.BucketAccessKey("uploads-key", {
112 * bucket,
113 * role: "read_write",
114 * });
115 * ```
116 *
117 * @resource
118 * @product Bucket
119 */
120 export const Bucket = Resource<Bucket>("Prisma.Bucket");
121
122 /**
123 * The bucket the provider observed belongs to a different project than the
124 * one requested or persisted. Convergence and deletion both refuse rather
125 * than acting on a bucket that is not the one this resource manages.
126 */
127 export class BucketProjectMismatchError extends Data.TaggedError("BucketProjectMismatchError")<{
128 bucketId: string;
129 actualProjectId: string;
130 expectedProjectId: string;
131 message: string;
132 }> {}
133
134 const logicalIdTaken = (
135 logicalId: string,
136 branchId: string | null | undefined,
137 projectId: string,
138 cause: unknown,
139 ) =>
140 new Error(
141 `Prisma bucket logical ID '${logicalId}' is already used by another bucket on ${branchId ? `branch '${branchId}'` : "the project's default branch"} in project '${projectId}'. Logical IDs are unique per branch; choose a different logicalId or remove it from the other bucket.`,
142 { cause },
143 );
144
145 const attrsFrom = (bucket: ObservedBucket): Bucket["Attributes"] => ({
146 bucketId: bucket.id,
147 name: bucket.name,
148 projectId: bucket.project.id,
149 createdAt: bucket.createdAt,
150 logicalId: bucket.logicalId ?? null,
151 });
152
153 // Distilled emits the cursor-paginated list operations as plain ops, so
154 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
155 const listBuckets = (filter: { projectId?: string; logicalId?: string; branchId?: string } = {}) =>
156 Effect.gen(function* () {
157 const buckets: GetBucketsResponse["data"][number][] = [];
158 let cursor: string | undefined;
159 while (true) {
160 const page = yield* getBuckets(cursor === undefined ? filter : { ...filter, cursor });
161 buckets.push(...page.data);
162 const nextCursor = page.pagination.nextCursor;
163 if (!page.pagination.hasMore) break;
164 if (nextCursor === null) {
165 return yield* new PrismaPaginationError({
166 message:
167 "Invalid Prisma Management API pagination response from getBuckets: hasMore was true without a non-empty nextCursor",
168 });
169 }
170 cursor = nextCursor;
171 }
172 return buckets;
173 });
174
175 const findBucketByLogicalId = Effect.fn(function* (
176 projectId: string,
177 logicalId: string,
178 branchId: string | undefined,
179 ) {
180 const branch = yield* desiredBranchId(projectId, { branchId });
181 if (!branch.resolved) return undefined;
182 const buckets = yield* listBuckets({
183 projectId,
184 logicalId,
185 branchId: branch.id,
186 });
187 return buckets.find((bucket) => bucket.logicalId === logicalId && bucket.branchId === branch.id);
188 });
189
190 const ProviderLive = () =>
191 Provider.effect(
192 Bucket,
193 Effect.gen(function* () {
194 return {
195 stables: ["bucketId"],
196 list: () => listBuckets().pipe(Effect.map((buckets) => buckets.map(attrsFrom))),
197 diff: Effect.fn(function* ({ fqn, olds, news, output }) {
198 if (!isInputObject(news)) return undefined;
199 if (isPrismaDevId(output?.bucketId)) {
200 return { action: "update" } as const;
201 }
202 const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project);
203 const newProjectId = isResolved(news.project)
204 ? unresolvedProjectIdOf(news.project)
205 : undefined;
206 if (concreteIdsChanged(oldProjectId, newProjectId)) {
207 return { action: "replace" } as const;
208 }
209 if (
210 isResolved(news.branchId) &&
211 news.branchId !== undefined &&
212 news.branchId !== olds.branchId
213 ) {
214 return { action: "update" } as const;
215 }
216 if (
217 isResolved(news.name) &&
218 news.name !== undefined &&
219 news.name !== (output?.name ?? olds.name)
220 ) {
221 return { action: "update" } as const;
222 }
223 if (
224 isResolved(news.logicalId) &&
225 (news.logicalId ?? fqn) !== (output ? output.logicalId : (olds.logicalId ?? fqn))
226 ) {
227 return { action: "update" } as const;
228 }
229 return undefined;
230 }),
231 read: Effect.fn(function* ({ fqn, output, olds }) {
232 const bucketId = isPrismaDevId(output?.bucketId) ? undefined : output?.bucketId;
233 if (!bucketId) {
234 const projectId = unresolvedProjectIdOf(olds.project);
235 if (!projectId) return undefined;
236 // A logical ID alone does not prove ownership: another
237 // declaration, stage, or stack on the branch can hold it, and a
238 // bucket has no Alchemy-generated name to confirm it.
239 const bucket = yield* findBucketByLogicalId(
240 projectId,
241 olds.logicalId ?? fqn,
242 olds.branchId,
243 );
244 return bucket ? Unowned(attrsFrom(bucket)) : undefined;
245 }
246 const bucket = yield* getBucket({ bucketId }).pipe(
247 Effect.map((response) => response.data),
248 Effect.catchTag("NotFound", () => Effect.undefined),
249 );
250 return bucket ? attrsFrom(bucket) : undefined;
251 }),
252 reconcile: Effect.fn(function* ({ fqn, news, output }) {
253 const projectId = yield* resolveProjectId(news.project);
254 const logicalId = news.logicalId ?? fqn;
255 const bucketId = isPrismaDevId(output?.bucketId) ? undefined : output?.bucketId;
256 let observed: ObservedBucket | undefined = bucketId
257 ? yield* getBucket({ bucketId }).pipe(
258 Effect.map((response) => response.data),
259 Effect.catchTag("NotFound", () => Effect.undefined),
260 )
261 : undefined;
262 if (!observed) {
263 observed = yield* findBucketByLogicalId(projectId, logicalId, news.branchId);
264 }
265 if (!observed) {
266 observed = yield* createBucket({
267 projectId,
268 ...(news.name === undefined ? {} : { name: news.name }),
269 ...(news.branchId === undefined || news.branchId === null
270 ? {}
271 : { branchId: news.branchId }),
272 logicalId,
273 }).pipe(
274 // A replayed create would make a second bucket; the retry policy
275 // cannot see the request, so opt out explicitly.
276 Retry.none,
277 Effect.map((response) => response.data),
278 Effect.catchTag("Conflict", (conflict) =>
279 Effect.fail(logicalIdTaken(logicalId, news.branchId, projectId, conflict)),
280 ),
281 );
282 }
283 if (observed.project.id !== projectId) {
284 return yield* new BucketProjectMismatchError({
285 bucketId: observed.id,
286 actualProjectId: observed.project.id,
287 expectedProjectId: projectId,
288 message: `Prisma bucket '${observed.id}' belongs to project '${observed.project.id}', not requested project '${projectId}'. Refusing to claim convergence; replace the bucket.`,
289 });
290 }
291 const rename = news.name !== undefined && observed.name !== news.name;
292 const move = news.branchId !== undefined && observed.branchId !== news.branchId;
293 if (rename || move) {
294 const current = observed;
295 observed = yield* updateBucket({
296 bucketId: current.id,
297 ...(rename ? { displayName: news.name } : {}),
298 ...(move ? { branchId: news.branchId } : {}),
299 }).pipe(
300 Effect.map((response) => response.data),
301 // A move is refused when the bucket's logical ID is taken on
302 // the target branch.
303 Effect.catchTag("Conflict", (conflict) =>
304 Effect.fail(
305 current.logicalId
306 ? logicalIdTaken(current.logicalId, news.branchId, projectId, conflict)
307 : conflict,
308 ),
309 ),
310 );
311 }
312 if (observed.logicalId !== logicalId) {
313 const { branchId } = observed;
314 // The API refuses to rebind a logical ID; it must be cleared first.
315 if (observed.logicalId) {
316 observed = yield* updateBucket({ bucketId: observed.id, logicalId: null }).pipe(
317 Effect.map((response) => response.data),
318 );
319 }
320 // The API refuses logicalId in the same request as a branch
321 // move, so it is set only after the move above.
322 observed = yield* updateBucket({
323 bucketId: observed.id,
324 logicalId,
325 }).pipe(
326 Effect.map((response) => response.data),
327 Effect.catchTag("Conflict", (conflict) =>
328 Effect.fail(logicalIdTaken(logicalId, branchId, projectId, conflict)),
329 ),
330 );
331 }
332 return attrsFrom(observed);
333 }),
334 delete: Effect.fn(function* ({ output }) {
335 if (isPrismaDevId(output.bucketId)) return;
336 const bucket = yield* getBucket({
337 bucketId: output.bucketId,
338 }).pipe(
339 Effect.map((response) => response.data),
340 Effect.catchTag("NotFound", () => Effect.undefined),
341 );
342 if (!bucket) return;
343 if (bucket.project.id !== output.projectId) {
344 return yield* new BucketProjectMismatchError({
345 bucketId: bucket.id,
346 actualProjectId: bucket.project.id,
347 expectedProjectId: output.projectId,
348 message: `Prisma bucket '${bucket.id}' no longer matches persisted project '${output.projectId}'. Refusing to delete a mismatched bucket.`,
349 });
350 }
351 // Deletion cascades server-side: the Management API removes the
352 // bucket together with its objects and any remaining keys.
353 yield* deleteBucket({
354 bucketId: output.bucketId,
355 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
356 }),
357 };
358 }),
359 );
360
361 const ProviderLocal = () =>
362 devProvider(Bucket, ["bucketId"], ({ id, fqn, news }) => ({
363 bucketId: devId("bucket", id),
364 name: news.name ?? id,
365 projectId: attrOrString(news.project, "projectId") ?? devId("project", id),
366 createdAt: DEV_TIMESTAMP,
367 logicalId: news.logicalId ?? fqn,
368 }));
369
370 export const BucketProvider = () =>
371 ProviderLayer.dual(Bucket, {
372 local: () => ProviderLocal(),
373 live: () => ProviderLive(),
374 });