@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 276 lines 9.29 KB
Raw
1 import * as firestore from "@distilled.cloud/gcp/firestore_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 databaseIdOf,
13 databaseNameOf,
14 lastSegment,
15 parseDatabaseName,
16 toResourceId,
17 } from "./internal.ts";
18
19 export type DatabasesUserCredProps = {
20 /**
21 * Parent database. Full name `projects/{project}/databases/{database}`
22 * or the database id. User creds require an Enterprise edition
23 * database with MongoDB-compatible API access enabled. Immutable —
24 * changing it replaces the creds.
25 */
26 database: string;
27 /**
28 * User creds id (the `{user_creds}` segment of
29 * `.../databases/{database}/userCreds/{user_creds}`). If omitted, a
30 * unique name is generated. Must be 4-63 characters, match
31 * `[a-z][a-z0-9-]*[a-z0-9]`, and must not look like a UUID.
32 * Immutable — changing it replaces the creds.
33 */
34 userCredsId?: string;
35 /**
36 * Disable the creds. Enable/disable updates in place.
37 * @default false
38 */
39 disabled?: boolean;
40 };
41
42 export type DatabasesUserCred = Resource<
43 "GCP.Firestore.DatabasesUserCred",
44 DatabasesUserCredProps,
45 {
46 /** Full resource name `.../databases/{database}/userCreds/{user_creds}`. */
47 name: string;
48 /** User creds id (last path segment). */
49 userCredsId: string;
50 /** Parent database resource name. */
51 database: string;
52 /** Parent database id. */
53 databaseId: string;
54 /** Project id. */
55 project: string;
56 /** Whether the creds are disabled. */
57 disabled: boolean;
58 /** Server-reported state (`ENABLED`, `DISABLED`). */
59 state: string | undefined;
60 /**
61 * Plaintext server-generated password. Only populated on create and
62 * password reset; later reads preserve the last known value.
63 */
64 securePassword: string | undefined;
65 /** Resource Identity principal, if any. */
66 principal: string | undefined;
67 /** RFC3339 creation timestamp. */
68 createTime: string | undefined;
69 /** RFC3339 last-update timestamp. */
70 updateTime: string | undefined;
71 },
72 never,
73 Providers
74 >;
75
76 /**
77 * User credentials for a Cloud Firestore database with MongoDB
78 * compatibility.
79 *
80 * User creds are owned by the parent database and require Enterprise
81 * edition with the MongoDB-compatible API enabled. The plaintext
82 * password is returned only on create (and password reset); later
83 * reads keep the last known value from state. Enable/disable updates
84 * in place. Changing `userCredsId` or `database` replaces the creds.
85 *
86 * User creds have no labels field: `read` reports creds it finds without
87 * prior state as unowned (adopt them with `--adopt`).
88 *
89 * ### Creating User Creds
90 * **Example:** Enabled creds on an Enterprise database
91 * ```typescript
92 * const database = yield* GCP.Firestore.Database("App", {
93 * location: "us-central1",
94 * databaseEdition: "ENTERPRISE",
95 * mongodbCompatibleDataAccessMode: "DATA_ACCESS_MODE_ENABLED",
96 * });
97 * const creds = yield* GCP.Firestore.DatabasesUserCred("AppUser", {
98 * database: database.name,
99 * });
100 * ```
101 *
102 * **Example:** Disabled creds
103 * ```typescript
104 * const creds = yield* GCP.Firestore.DatabasesUserCred("AppUser", {
105 * database: database.name,
106 * disabled: true,
107 * });
108 * ```
109 *
110 * @resource
111 * @category Firestore
112 */
113 export const DatabasesUserCred = Resource<DatabasesUserCred>("GCP.Firestore.DatabasesUserCred");
114
115 export class UserCredNotResolved extends Data.TaggedError("GCP.Firestore.UserCredNotResolved")<{
116 resourceName: string;
117 }> {}
118
119 export class UserCredStillExists extends Data.TaggedError("GCP.Firestore.UserCredStillExists")<{
120 resourceName: string;
121 }> {}
122
123 const resourceName = (databaseName: string, userCredsId: string) =>
124 `${databaseName}/userCreds/${userCredsId}`;
125
126 const toAttrs = (
127 creds: firestore.GoogleFirestoreAdminV1UserCreds,
128 project: string,
129 securePassword?: string,
130 ): DatabasesUserCred["Attributes"] => {
131 const name = creds.name ?? "";
132 const parsed = parseDatabaseName(name);
133 const state = creds.state;
134 return {
135 name,
136 userCredsId: parsed.userCredsId || lastSegment(name),
137 database: databaseNameOf(parsed.project || project, parsed.databaseId),
138 databaseId: parsed.databaseId,
139 project: parsed.project || project,
140 disabled: state === "DISABLED",
141 state,
142 securePassword: creds.securePassword ?? securePassword,
143 principal: creds.resourceIdentity?.principal,
144 createTime: creds.createTime,
145 updateTime: creds.updateTime,
146 };
147 };
148
149 const getByName = (name: string) =>
150 firestore
151 .getProjectsDatabasesUserCreds({ name })
152 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
153
154 const listOnDatabase = (parent: string) =>
155 firestore.listProjectsDatabasesUserCreds({ parent }).pipe(
156 Effect.map((page) => page.userCreds ?? []),
157 Effect.catchTag("NotFound", () =>
158 Effect.succeed([] as firestore.GoogleFirestoreAdminV1UserCreds[]),
159 ),
160 );
161
162 const waitUntilGone = (name: string) =>
163 getByName(name).pipe(
164 Effect.filterOrFail(
165 (creds) => creds === undefined,
166 () => new UserCredStillExists({ resourceName: name }),
167 ),
168 Effect.retry({
169 while: (error) => error._tag === "GCP.Firestore.UserCredStillExists",
170 times: 8,
171 schedule: Schedule.spaced("2 seconds"),
172 }),
173 Effect.asVoid,
174 );
175
176 const syncEnabled = (
177 name: string,
178 disabled: boolean,
179 current: firestore.GoogleFirestoreAdminV1UserCreds,
180 ) => {
181 const isDisabled = current.state === "DISABLED";
182 if (isDisabled === disabled) return Effect.succeed(current);
183 return disabled
184 ? firestore.disableProjectsDatabasesUserCreds({ name, body: {} })
185 : firestore.enableProjectsDatabasesUserCreds({ name, body: {} });
186 };
187
188 export const DatabasesUserCredProvider = () =>
189 Provider.succeed(DatabasesUserCred, {
190 stables: ["name", "userCredsId", "database", "databaseId", "project", "createTime"],
191
192 diff: Effect.fn(function* ({ news, olds, output }) {
193 if (!isResolved(news)) return undefined;
194 const previousId = olds?.userCredsId ?? output?.userCredsId;
195 const nextId = news.userCredsId ?? previousId;
196 const previousDatabase = databaseIdOf(
197 olds?.database ?? output?.database ?? output?.databaseId ?? "",
198 );
199 const nextDatabase = databaseIdOf(news.database);
200 if (
201 (previousId !== undefined && nextId !== undefined && previousId !== nextId) ||
202 (previousDatabase.length > 0 && previousDatabase !== nextDatabase)
203 ) {
204 return { action: "replace" as const };
205 }
206 return undefined;
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const env = yield* GcpEnvironment.current;
211 const userCredsId = yield* toResourceId(id, olds?.userCredsId, output?.userCredsId);
212 const databaseRef = olds?.database ?? output?.database;
213 const name =
214 output?.name ??
215 (databaseRef !== undefined
216 ? resourceName(databaseNameOf(env.project, databaseRef), userCredsId)
217 : undefined);
218 if (name === undefined) return undefined;
219 const existing = yield* getByName(name);
220 if (existing === undefined) return undefined;
221 const attrs = toAttrs(existing, env.project, output?.securePassword);
222 // No labels field: without prior state they may not be ours.
223 return output !== undefined ? attrs : Unowned(attrs);
224 }),
225
226 reconcile: Effect.fn(function* ({ id, news, output }) {
227 const env = yield* GcpEnvironment.current;
228 const parent = databaseNameOf(env.project, news.database);
229 const userCredsId = yield* toResourceId(id, news.userCredsId, output?.userCredsId);
230 const name = resourceName(parent, userCredsId);
231 const disabled = news.disabled === true;
232
233 let current = yield* getByName(output?.name ?? name);
234 let createdPassword = output?.securePassword;
235
236 if (current === undefined) {
237 const created = yield* firestore
238 .createProjectsDatabasesUserCreds({
239 parent,
240 userCredsId,
241 body: {},
242 })
243 .pipe(
244 Effect.catchTag("Conflict", () =>
245 listOnDatabase(parent).pipe(
246 Effect.map(
247 (creds) =>
248 creds.find((item) => lastSegment(item.name ?? "") === userCredsId) ?? undefined,
249 ),
250 Effect.flatMap((found) =>
251 found !== undefined ? Effect.succeed(found) : getByName(name),
252 ),
253 ),
254 ),
255 );
256 current = created ?? undefined;
257 if (current?.securePassword !== undefined) {
258 createdPassword = current.securePassword;
259 }
260 }
261
262 if (current === undefined) {
263 return yield* new UserCredNotResolved({ resourceName: name });
264 }
265
266 current = yield* syncEnabled(current.name ?? name, disabled, current);
267 return toAttrs(current, env.project, createdPassword);
268 }),
269
270 delete: Effect.fn(function* ({ output }) {
271 yield* firestore
272 .deleteProjectsDatabasesUserCreds({ name: output.name })
273 .pipe(Effect.catchTag("NotFound", () => Effect.void));
274 yield* waitUntilGone(output.name);
275 }),
276 });