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

main
ts 278 lines 9.94 KB
Raw
1 import * as Neon from "@distilled.cloud/neon";
2 import { OwnedBySomeoneElse, unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { authPlanScope, authRequest, authSettingsMatch, removedAuthSettings } from "./Auth.ts";
10 import { resolveBranchScope, type ResolvedBranchScope } from "./BranchScope.ts";
11 import type { Providers } from "./Providers.ts";
12
13 export type DataApiProps = (
14 | {
15 /** Branch resource or explicit identity, optionally carrying its selected database. */
16 branch: { projectId: string; branchId: string; databaseName?: string };
17 project?: never;
18 }
19 | {
20 /** Project resource or explicit identity; selects the observed default branch. */
21 project: { projectId: string; databaseName?: string };
22 branch?: never;
23 }
24 ) & {
25 /** Database served by PostgREST. Infers the referenced resource's selected database, or the branch's only database; required when ambiguous. */
26 database?: string;
27 /** Authentication mechanism. Changes replace the Data API. */
28 authProvider?: "neon_auth" | "external";
29 /** HTTPS JWKS endpoint required for external authentication. */
30 jwksUrl?: string;
31 /** Display name for an external authentication provider. */
32 providerName?: string;
33 /** Expected JWT audience. Neon still accepts tokens without an audience. */
34 jwtAudience?: string;
35 /** Opt in to public-schema table grants. Defaults to false. */
36 addDefaultGrants?: boolean;
37 /** Skip creating the auth schema and RLS helpers. */
38 skipAuthSchema?: boolean;
39 /** Explicitly owned PostgREST settings. Removing previously managed fields requires an explicit reset value. */
40 settings?: Neon.DataAPISettings;
41 };
42
43 export interface DataApiAttributes {
44 /** Neon project identity. */
45 projectId: string;
46 /** Branch identity. */
47 branchId: string;
48 /** Database served by this endpoint. */
49 database: string;
50 /** Public PostgREST base URL. Requests must carry end-user authorization. */
51 url: string;
52 /** Observed deployment status. */
53 status: string;
54 /** Observed PostgREST settings, if exposed by the backend. */
55 settings: Neon.DataAPISettings | undefined;
56 }
57
58 export interface DataApi extends Resource<
59 "Neon.DataApi",
60 DataApiProps,
61 DataApiAttributes,
62 never,
63 Providers
64 > {}
65
66 /**
67 * Own a branch/database Data API singleton. This resource never grants an
68 * application the account deployment key. Configure RLS and forward the user's
69 * token through QueryDataApi. Authentication inputs are creation-only because
70 * the API only supports updating PostgREST settings.
71 *
72 * ### Expose a database through managed authentication
73 * **Example:** Managed Auth and PostgREST
74 * ```typescript
75 * const dataApi = yield* Neon.DataApi("Data", {
76 * branch, authProvider: "neon_auth", settings: { db_max_rows: 100 },
77 * });
78 * ```
79 *
80 * @resource
81 * @product Data API
82 */
83 export const DataApi = Resource<DataApi>("Neon.DataApi");
84
85 export class InvalidDataApiConfiguration extends Data.TaggedError("InvalidDataApiConfiguration")<{
86 message: string;
87 }> {}
88
89 const observe = (scope: { projectId: string; branchId: string; database: string }) =>
90 Neon.getProjectBranchDataAPI({
91 ...authRequest(scope),
92 database_name: scope.database,
93 }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
94
95 const attributes = (
96 scope: { projectId: string; branchId: string; database: string },
97 observed: Neon.DataAPIReponse,
98 ): DataApiAttributes => ({
99 projectId: scope.projectId,
100 branchId: scope.branchId,
101 database: scope.database,
102 url: observed.url,
103 status: observed.status,
104 settings: observed.settings ?? undefined,
105 });
106
107 const immutable = [
108 "authProvider",
109 "jwksUrl",
110 "providerName",
111 "jwtAudience",
112 "addDefaultGrants",
113 "skipAuthSchema",
114 ] as const;
115
116 const validateDataApi = (news: DataApiProps) =>
117 news.authProvider === "external" && !news.jwksUrl
118 ? Effect.fail(
119 new InvalidDataApiConfiguration({
120 message: "External authentication requires jwksUrl",
121 }),
122 )
123 : Effect.void;
124
125 const validateDataApiRemoval = (olds: DataApiProps | undefined, news: Input<DataApiProps>) => {
126 const removed = removedAuthSettings(olds, news, [...immutable, "settings"]);
127 return removed.length === 0
128 ? Effect.void
129 : Effect.fail(
130 new InvalidDataApiConfiguration({
131 message: `Cannot remove managed Data API settings: ${removed.join(", ")}; set explicit reset values instead`,
132 }),
133 );
134 };
135
136 const resolveDatabase = Effect.fn(function* (news: DataApiProps, scope: ResolvedBranchScope) {
137 const database = news.database ?? (news.branch ?? news.project)?.databaseName;
138 if (database !== undefined) {
139 if (!database)
140 return yield* new InvalidDataApiConfiguration({
141 message: "database must not be empty",
142 });
143 return database;
144 }
145 const { databases } = yield* Neon.listProjectBranchDatabases(authRequest(scope));
146 if (databases.length !== 1) {
147 return yield* new InvalidDataApiConfiguration({
148 message: "Set database explicitly when the branch has no unambiguous selected database",
149 });
150 }
151 return databases[0]!.name;
152 });
153
154 export const DataApiProvider = () =>
155 Provider.succeed(DataApi, {
156 stables: ["projectId", "branchId", "database"],
157 diff: Effect.fn(function* ({ olds, news, output }) {
158 yield* validateDataApiRemoval(olds, news);
159 if (isResolved(news)) yield* validateDataApi(news);
160 const scope = yield* authPlanScope(news);
161 if (
162 output &&
163 (!scope || scope.projectId !== output.projectId || scope.branchId !== output.branchId)
164 ) {
165 return { action: "replace", deleteFirst: true } as const;
166 }
167 if (!isResolved(news)) return;
168 const resolved = scope ?? (yield* resolveBranchScope(news));
169 const database = yield* resolveDatabase(news, resolved);
170 const previous = output ?? (yield* resolveBranchScope(olds));
171 if (
172 resolved.projectId !== previous.projectId ||
173 resolved.branchId !== previous.branchId ||
174 database !== (output?.database ?? (yield* resolveDatabase(olds, previous))) ||
175 immutable.some((key) => news[key] !== olds[key])
176 ) {
177 return { action: "replace", deleteFirst: true } as const;
178 }
179 if (output) {
180 const current = yield* observe({ ...resolved, database });
181 if (
182 !current ||
183 (news.settings !== undefined && !authSettingsMatch(current.settings ?? {}, news.settings))
184 )
185 return { action: "update" } as const;
186 }
187 }),
188 read: Effect.fn(function* ({ olds, output, previous }) {
189 if (
190 !output &&
191 !(olds?.branch?.projectId && olds.branch.branchId) &&
192 !olds?.project?.projectId
193 )
194 return undefined;
195 const branch = output ?? (yield* resolveBranchScope(olds));
196 const scope = output ?? {
197 ...branch,
198 database: yield* resolveDatabase(olds, branch),
199 };
200 const current = yield* observe(scope);
201 if (!current) return undefined;
202 const attrs = attributes(scope, current);
203 return output ? attrs : unownedUnlessPrevious(attrs, previous, "database");
204 }),
205 reconcile: Effect.fn(function* ({ news, output, olds }) {
206 yield* validateDataApiRemoval(olds, news);
207 yield* validateDataApi(news);
208 const branch = yield* resolveBranchScope(news);
209 const scope = {
210 ...branch,
211 database: yield* resolveDatabase(news, branch),
212 };
213 if (
214 output &&
215 (scope.projectId !== output.projectId ||
216 scope.branchId !== output.branchId ||
217 scope.database !== output.database)
218 ) {
219 return yield* new InvalidDataApiConfiguration({
220 message:
221 "Data API identity changed without replacement; refusing to mutate either endpoint",
222 });
223 }
224 const request = { ...authRequest(scope), database_name: scope.database };
225 let current = yield* observe(scope);
226 if (current && !output)
227 return yield* new OwnedBySomeoneElse({
228 message: "Existing Data API requires explicit adoption",
229 resourceType: "Neon.DataApi",
230 });
231 if (current && olds === undefined && immutable.some((key) => news[key] !== undefined)) {
232 return yield* new InvalidDataApiConfiguration({
233 message:
234 "Neon does not expose existing Data API authentication settings; adopt without creation-only settings, then replace to configure authentication",
235 });
236 }
237 if (!current) {
238 yield* Neon.createProjectBranchDataAPI({
239 ...request,
240 auth_provider: news.authProvider,
241 jwks_url: news.jwksUrl,
242 provider_name: news.providerName,
243 jwt_audience: news.jwtAudience,
244 add_default_grants: news.addDefaultGrants ?? false,
245 skip_auth_schema: news.skipAuthSchema,
246 settings: news.settings,
247 }).pipe(
248 Effect.catchTag("Conflict", () =>
249 Effect.fail(
250 new OwnedBySomeoneElse({
251 message: "Data API appeared during creation; explicit adoption is required",
252 resourceType: "Neon.DataApi",
253 }),
254 ),
255 ),
256 );
257 current = yield* Neon.getProjectBranchDataAPI(request);
258 }
259 if (
260 news.settings !== undefined &&
261 !authSettingsMatch(current.settings ?? {}, news.settings)
262 ) {
263 yield* Neon.updateProjectBranchDataAPI({
264 ...request,
265 settings: news.settings,
266 });
267 }
268 return attributes(scope, yield* Neon.getProjectBranchDataAPI(request));
269 }),
270 delete: Effect.fn(function* ({ output }) {
271 if (yield* observe(output)) {
272 yield* Neon.deleteProjectBranchDataAPI({
273 ...authRequest(output),
274 database_name: output.database,
275 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
276 }
277 }),
278 });