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
| 1 | import type { CORSRule } from "@distilled.cloud/aws/s3"; |
| 2 | import * as Neon from "@distilled.cloud/neon"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import type { PropsInput } from "alchemy/Input"; |
| 6 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 7 | import * as Provider from "alchemy/Provider"; |
| 8 | import { Resource } from "alchemy/Resource"; |
| 9 | import { createInternalTags, diffTags, hasTags, tagRecord } from "alchemy/Tags"; |
| 10 | import * as Data from "effect/Data"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import { resolveBranchScope, type BranchScope, type ResolvedBranchScope } from "./BranchScope.ts"; |
| 14 | import { Credential, validateCredential, type CredentialAttributes } from "./Credential.ts"; |
| 15 | import type { Providers } from "./Providers.ts"; |
| 16 | import { emptyStorageBucket, makeStorageClient } from "./Storage.ts"; |
| 17 | |
| 18 | export type BucketProps = BranchScope & { |
| 19 | /** Bucket name, unique within this branch. Generated when omitted. */ |
| 20 | name?: string; |
| 21 | /** Anonymous object GET/HEAD access; never grants anonymous listing or writes. @default "private" */ |
| 22 | access?: "private" | "public_read"; |
| 23 | /** S3 CORS rules. Omission removes managed CORS rules. */ |
| 24 | cors?: CORSRule[]; |
| 25 | /** User tags, merged with Alchemy ownership tags. */ |
| 26 | tags?: Record<string, string>; |
| 27 | /** Empty objects and incomplete multipart uploads before deletion. @default false */ |
| 28 | forceDestroy?: boolean; |
| 29 | /** Optional management credential; requires storage:read and storage:write on this branch or an ancestor. */ |
| 30 | credential?: CredentialAttributes; |
| 31 | }; |
| 32 | |
| 33 | export interface BucketAttributes extends ResolvedBranchScope { |
| 34 | /** Bucket identity within the branch. */ |
| 35 | bucketName: string; |
| 36 | /** Current anonymous object read policy. */ |
| 37 | access: "private" | "public_read"; |
| 38 | /** Branch-specific path-style S3 endpoint. */ |
| 39 | endpoint: string; |
| 40 | /** S3 signing region. */ |
| 41 | region: string; |
| 42 | /** Observed bucket tags, including ownership markers. */ |
| 43 | tags: Record<string, string>; |
| 44 | /** Observed CORS rules. */ |
| 45 | cors: CORSRule[]; |
| 46 | /** Management credential for declarative objects and cleanup. Never bound into runtime readers. @internal */ |
| 47 | credential: CredentialAttributes; |
| 48 | } |
| 49 | |
| 50 | export interface Bucket extends Resource< |
| 51 | "Neon.Bucket", |
| 52 | BucketProps, |
| 53 | BucketAttributes, |
| 54 | never, |
| 55 | Providers |
| 56 | > {} |
| 57 | const BucketResource = Resource<Bucket>("Neon.Bucket"); |
| 58 | |
| 59 | /** |
| 60 | * Branch-local S3 object storage. Writes do not change an ancestor's data. |
| 61 | * The management credential is tracked separately and revoked after bucket cleanup. |
| 62 | * Neon does not expose a supported visibility update API; changing access fails |
| 63 | * explicitly instead of replacing a populated bucket. Policies and ACL writes are |
| 64 | * not supported. A private bucket has no anonymously readable object URL. |
| 65 | * Adopting an inherited bucket materializes its configuration on the child branch |
| 66 | * without changing ancestor tags, CORS, or object data. |
| 67 | * |
| 68 | * ### Creating a Bucket |
| 69 | * **Example:** Private uploads with browser CORS |
| 70 | * ```typescript |
| 71 | * const uploads = yield* Neon.Bucket("Uploads", { |
| 72 | * branch, |
| 73 | * cors: [{ AllowedOrigins: ["https://app.example.com"], AllowedMethods: ["PUT", "GET"] }], |
| 74 | * }); |
| 75 | * ``` |
| 76 | * |
| 77 | * @resource |
| 78 | * @product Bucket |
| 79 | */ |
| 80 | export const Bucket: typeof BucketResource = Object.assign( |
| 81 | ( |
| 82 | id: string, |
| 83 | props: PropsInput<BucketProps> | Effect.Effect<PropsInput<BucketProps>, never, Providers>, |
| 84 | ) => |
| 85 | BucketResource( |
| 86 | id, |
| 87 | Effect.gen(function* () { |
| 88 | const news = Effect.isEffect(props) ? yield* props : props; |
| 89 | const { |
| 90 | name: _name, |
| 91 | access: _access, |
| 92 | cors: _cors, |
| 93 | tags: _tags, |
| 94 | forceDestroy: _forceDestroy, |
| 95 | credential: suppliedCredential, |
| 96 | ...scope |
| 97 | } = news; |
| 98 | const credential = |
| 99 | suppliedCredential ?? |
| 100 | (yield* Credential(`${id}StorageCredential`, { |
| 101 | ...scope, |
| 102 | scopes: ["storage:read", "storage:write"], |
| 103 | })); |
| 104 | return { ...news, credential }; |
| 105 | }), |
| 106 | ), |
| 107 | BucketResource, |
| 108 | ); |
| 109 | |
| 110 | export class UnsupportedBucketAccessUpdate extends Data.TaggedError( |
| 111 | "UnsupportedBucketAccessUpdate", |
| 112 | )<{ |
| 113 | message: string; |
| 114 | }> {} |
| 115 | export class BucketNotEmpty extends Data.TaggedError("BucketNotEmpty")<{ |
| 116 | message: string; |
| 117 | }> {} |
| 118 | export class BucketConfigurationError extends Data.TaggedError("BucketConfigurationError")<{ |
| 119 | message: string; |
| 120 | }> {} |
| 121 | |
| 122 | const apiScope = (scope: ResolvedBranchScope) => ({ |
| 123 | project_id: scope.projectId, |
| 124 | branch_id: scope.branchId, |
| 125 | }); |
| 126 | const observe = Effect.fn(function* (scope: ResolvedBranchScope, name: string) { |
| 127 | const result = yield* Neon.listProjectBranchBuckets(apiScope(scope)); |
| 128 | return result.buckets.find((bucket) => bucket.name === name); |
| 129 | }); |
| 130 | |
| 131 | export const bucketStorageClient = (bucket: BucketAttributes) => |
| 132 | makeStorageClient( |
| 133 | { |
| 134 | endpoint: bucket.endpoint, |
| 135 | region: bucket.region, |
| 136 | accessKeyId: bucket.credential.tokenId, |
| 137 | secretAccessKey: bucket.credential.s3SecretAccessKey, |
| 138 | }, |
| 139 | bucket.bucketName, |
| 140 | ); |
| 141 | |
| 142 | const hydrate = Effect.fn(function* ( |
| 143 | scope: ResolvedBranchScope, |
| 144 | bucket: Neon.Bucket, |
| 145 | credential: CredentialAttributes, |
| 146 | ) { |
| 147 | const storage = yield* Neon.getProjectBranchStorage(apiScope(scope)); |
| 148 | const attrs = { |
| 149 | ...scope, |
| 150 | bucketName: bucket.name, |
| 151 | access: bucket.access_level, |
| 152 | endpoint: storage.s3_endpoint, |
| 153 | region: storage.region, |
| 154 | credential, |
| 155 | }; |
| 156 | const client = yield* makeStorageClient( |
| 157 | { |
| 158 | endpoint: attrs.endpoint, |
| 159 | region: attrs.region, |
| 160 | accessKeyId: credential.tokenId, |
| 161 | secretAccessKey: credential.s3SecretAccessKey, |
| 162 | }, |
| 163 | bucket.name, |
| 164 | ); |
| 165 | const tags = tagRecord( |
| 166 | (yield* client.getTags().pipe( |
| 167 | Effect.retry({ |
| 168 | while: (error) => error._tag === "NoSuchBucket", |
| 169 | schedule: Schedule.spaced("500 millis"), |
| 170 | times: 8, |
| 171 | }), |
| 172 | )).TagSet?.flatMap((tag) => |
| 173 | tag.Key !== undefined && tag.Value !== undefined ? [{ Key: tag.Key, Value: tag.Value }] : [], |
| 174 | ), |
| 175 | ); |
| 176 | const cors = |
| 177 | (yield* client.getCors().pipe( |
| 178 | Effect.retry({ |
| 179 | while: (error) => error._tag === "NoSuchBucket", |
| 180 | schedule: Schedule.spaced("500 millis"), |
| 181 | times: 8, |
| 182 | }), |
| 183 | )).CORSRules ?? []; |
| 184 | return { ...attrs, tags, cors }; |
| 185 | }); |
| 186 | |
| 187 | const credentialOf = Effect.fn(function* (props: BucketProps, output?: BucketAttributes) { |
| 188 | const credential = props.credential ?? output?.credential; |
| 189 | if (!credential) |
| 190 | return yield* new BucketConfigurationError({ |
| 191 | message: "Bucket management credential is missing", |
| 192 | }); |
| 193 | return credential; |
| 194 | }); |
| 195 | |
| 196 | export const BucketProvider = () => |
| 197 | Provider.succeed(Bucket, { |
| 198 | stables: ["projectId", "branchId", "bucketName", "endpoint", "region"], |
| 199 | diff: Effect.fn(function* ({ news, output }) { |
| 200 | if (!isResolved(news) || !output) return; |
| 201 | const scope = yield* resolveBranchScope(news); |
| 202 | if ( |
| 203 | scope.projectId !== output.projectId || |
| 204 | scope.branchId !== output.branchId || |
| 205 | (news.name !== undefined && news.name !== output.bucketName) |
| 206 | ) |
| 207 | return { action: "replace" }; |
| 208 | }), |
| 209 | read: Effect.fn(function* ({ id, fqn, olds, output }) { |
| 210 | if ( |
| 211 | !output && |
| 212 | !olds?.project?.projectId && |
| 213 | !(olds?.branch?.projectId && olds.branch.branchId) |
| 214 | ) |
| 215 | return undefined; |
| 216 | const scope = output ?? (yield* resolveBranchScope(olds)); |
| 217 | const name = |
| 218 | output?.bucketName ?? |
| 219 | olds?.name ?? |
| 220 | (yield* createPhysicalName({ id, maxLength: 63, lowercase: true })); |
| 221 | const bucket = yield* observe(scope, name); |
| 222 | if (!bucket) return undefined; |
| 223 | const credential = yield* credentialOf(olds, output); |
| 224 | const attrs = yield* hydrate(scope, bucket, credential); |
| 225 | const expected = { |
| 226 | ...(yield* createInternalTags(fqn)), |
| 227 | "alchemy::branch": scope.branchId, |
| 228 | }; |
| 229 | return hasTags(expected, attrs.tags) ? attrs : Unowned(attrs); |
| 230 | }), |
| 231 | reconcile: Effect.fn(function* ({ id, fqn, news, output }) { |
| 232 | const scope = yield* resolveBranchScope(news); |
| 233 | const credential = yield* credentialOf(news, output); |
| 234 | yield* validateCredential(credential, scope, "storage:write"); |
| 235 | yield* validateCredential(credential, scope, "storage:read"); |
| 236 | const name = |
| 237 | news.name ?? |
| 238 | output?.bucketName ?? |
| 239 | (yield* createPhysicalName({ id, maxLength: 63, lowercase: true })); |
| 240 | let bucket = yield* observe(scope, name); |
| 241 | if (!bucket) { |
| 242 | bucket = (yield* Neon.createProjectBranchBucket({ |
| 243 | ...apiScope(scope), |
| 244 | name, |
| 245 | access_level: news.access ?? "private", |
| 246 | })).bucket; |
| 247 | } |
| 248 | if (bucket.access_level !== (news.access ?? "private")) { |
| 249 | return yield* new UnsupportedBucketAccessUpdate({ |
| 250 | message: |
| 251 | "Neon has no supported bucket access update operation; change access in the console or retain the existing access level", |
| 252 | }); |
| 253 | } |
| 254 | const attrs = yield* hydrate(scope, bucket, credential); |
| 255 | const client = yield* bucketStorageClient(attrs); |
| 256 | const tags = { |
| 257 | ...news.tags, |
| 258 | ...(yield* createInternalTags(fqn)), |
| 259 | "alchemy::branch": scope.branchId, |
| 260 | }; |
| 261 | const delta = diffTags(attrs.tags, tags); |
| 262 | if (delta.removed.length || delta.upsert.length) |
| 263 | yield* client.putTags(tags).pipe( |
| 264 | Effect.catchTag("NoSuchBucket", () => |
| 265 | Effect.gen(function* () { |
| 266 | // Inherited buckets are readable before their branch-local configuration exists. |
| 267 | yield* Neon.createProjectBranchBucket({ |
| 268 | ...apiScope(scope), |
| 269 | name, |
| 270 | access_level: news.access ?? "private", |
| 271 | }); |
| 272 | yield* client.putTags(tags); |
| 273 | }), |
| 274 | ), |
| 275 | ); |
| 276 | const cors = news.cors ?? []; |
| 277 | if (JSON.stringify(attrs.cors) !== JSON.stringify(cors)) { |
| 278 | if (cors.length) yield* client.putCors(cors); |
| 279 | else yield* client.deleteCors(); |
| 280 | } |
| 281 | return yield* hydrate(scope, bucket, credential); |
| 282 | }), |
| 283 | delete: Effect.fn(function* ({ id, olds, output }) { |
| 284 | const scope = output ?? (yield* resolveBranchScope(olds)); |
| 285 | const bucketName = |
| 286 | output?.bucketName ?? |
| 287 | olds.name ?? |
| 288 | (yield* createPhysicalName({ id, maxLength: 63, lowercase: true })); |
| 289 | const bucket = yield* observe(scope, bucketName); |
| 290 | if (!bucket) return; |
| 291 | const credential = yield* credentialOf(olds, output); |
| 292 | const storage = yield* Neon.getProjectBranchStorage(apiScope(scope)); |
| 293 | const client = yield* makeStorageClient( |
| 294 | { |
| 295 | endpoint: storage.s3_endpoint, |
| 296 | region: storage.region, |
| 297 | accessKeyId: credential.tokenId, |
| 298 | secretAccessKey: credential.s3SecretAccessKey, |
| 299 | }, |
| 300 | bucketName, |
| 301 | ); |
| 302 | yield* client.deleteBucket().pipe( |
| 303 | Effect.catchTag("BucketNotEmpty", () => |
| 304 | Effect.gen(function* () { |
| 305 | if (!olds.forceDestroy) |
| 306 | return yield* new BucketNotEmpty({ |
| 307 | message: |
| 308 | "Bucket has objects or multipart uploads; set forceDestroy to explicitly empty it", |
| 309 | }); |
| 310 | yield* emptyStorageBucket(client); |
| 311 | const objects = yield* client.list({ limit: 1 }); |
| 312 | const uploads = yield* client.listMultipartUploads(); |
| 313 | if (objects.Contents?.length || uploads.Uploads?.length) { |
| 314 | return yield* new BucketNotEmpty({ |
| 315 | message: "Bucket changed while being emptied; refusing deletion", |
| 316 | }); |
| 317 | } |
| 318 | yield* client.deleteBucket(); |
| 319 | }), |
| 320 | ), |
| 321 | ); |
| 322 | }), |
| 323 | }); |