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

main
ts 189 lines 6.77 KB
Raw
1 import * as firestore from "@distilled.cloud/gcp/firestore_v1";
2 import * as Effect from "effect/Effect";
3 import * as GCPBindings from "../GCPBindings.ts";
4 import { type BindingIam, grantFor } from "../HttpBinding.ts";
5 import type { Database } from "./Database.ts";
6 import type { DocumentSnapshot, ReadDatabaseClient } from "./ReadDatabase.ts";
7 import { decodeFields, encodeFields, fieldPath } from "./Values.ts";
8 import { DocumentAlreadyExists, type WriteDatabaseClient } from "./WriteDatabase.ts";
9
10 // Firestore databases have no resource-level IAM policy: each grant is on
11 // the project under an IAM Condition naming the bound database.
12 export const readDatabaseIam: BindingIam = {
13 role: "roles/datastore.viewer",
14 scopeByCondition: true,
15 };
16 export const writeDatabaseIam: BindingIam = {
17 role: "roles/datastore.user",
18 scopeByCondition: true,
19 };
20 export const readWriteDatabaseIam: BindingIam = {
21 role: "roles/datastore.user",
22 scopeByCondition: true,
23 };
24
25 const trimPath = (path: string) => path.replace(/^\/+|\/+$/g, "");
26
27 /** `"a/b/c"` → `{ parent: "a/b", last: "c" }`. */
28 const splitLast = (path: string) => {
29 const trimmed = trimPath(path);
30 const at = trimmed.lastIndexOf("/");
31 return at < 0
32 ? { parent: "", last: trimmed }
33 : { parent: trimmed.slice(0, at), last: trimmed.slice(at + 1) };
34 };
35
36 const snapshot = (document: firestore.Document): DocumentSnapshot => ({
37 name: document.name ?? "",
38 fields: decodeFields(document.fields),
39 createTime: document.createTime,
40 updateTime: document.updateTime,
41 });
42
43 /**
44 * Shared HTTP scaffolding for the Firestore Read/Write/ReadWrite bindings:
45 * resolves the distilled operations once at Layer construction and grants
46 * the level's role at deploy time.
47 *
48 * NOT exported from `index.ts`.
49 */
50 export const makeFirestoreDatabaseHelpers = Effect.gen(function* () {
51 const getDocument = yield* GCPBindings.withCredentials(firestore.getProjectsDatabasesDocuments);
52 const listDocuments = yield* GCPBindings.withCredentials(
53 firestore.listProjectsDatabasesDocuments,
54 );
55 const runQuery = yield* GCPBindings.withCredentials(firestore.runQueryProjectsDatabasesDocuments);
56 const patchDocument = yield* GCPBindings.withCredentials(
57 firestore.patchProjectsDatabasesDocuments,
58 );
59 const createDocument = yield* GCPBindings.withCredentials(
60 firestore.createDocumentProjectsDatabasesDocuments,
61 );
62 const deleteDocument = yield* GCPBindings.withCredentials(
63 firestore.deleteProjectsDatabasesDocuments,
64 );
65
66 const makeRead = (databaseName: Effect.Effect<string>): ReadDatabaseClient => {
67 const documentsRoot = Effect.map(databaseName, (db) => `${db}/documents`);
68 const parentOf = (path: string) =>
69 Effect.map(documentsRoot, (root) => (path.length > 0 ? `${root}/${path}` : root));
70 return {
71 get: (path) =>
72 parentOf(trimPath(path)).pipe(
73 Effect.flatMap((name) => getDocument({ name })),
74 Effect.map(snapshot),
75 Effect.catchTag("NotFound", () => Effect.undefined),
76 ),
77 list: (collection, options) => {
78 const { parent, last } = splitLast(collection);
79 return parentOf(parent).pipe(
80 Effect.flatMap((parent) =>
81 listDocuments({
82 parent,
83 collectionId: last,
84 pageSize: options?.pageSize,
85 pageToken: options?.pageToken,
86 }),
87 ),
88 Effect.map((page) => ({
89 documents: (page.documents ?? []).map(snapshot),
90 nextPageToken: page.nextPageToken || undefined,
91 })),
92 );
93 },
94 query: (structuredQuery) =>
95 documentsRoot.pipe(
96 Effect.flatMap((parent) => runQuery({ parent, body: { structuredQuery } })),
97 // The REST endpoint streams a JSON array of RunQueryResponse
98 // messages; the generated output type models a single message.
99 Effect.map((response): ReadonlyArray<firestore.RunQueryResponse> =>
100 Array.isArray(response) ? response : [response],
101 ),
102 Effect.map((responses) =>
103 responses.flatMap((r) => (r.document === undefined ? [] : [snapshot(r.document)])),
104 ),
105 ),
106 };
107 };
108
109 const makeWrite = (databaseName: Effect.Effect<string>): WriteDatabaseClient => {
110 const documentName = (path: string) =>
111 Effect.map(databaseName, (db) => `${db}/documents/${trimPath(path)}`);
112 return {
113 set: (path, fields) =>
114 documentName(path).pipe(
115 Effect.flatMap((name) => patchDocument({ name, body: { fields: encodeFields(fields) } })),
116 Effect.map(snapshot),
117 ),
118 update: (path, fields) =>
119 documentName(path).pipe(
120 Effect.flatMap((name) =>
121 patchDocument({
122 name,
123 "updateMask.fieldPaths": Object.keys(fields).map(fieldPath),
124 "currentDocument.exists": true,
125 body: { fields: encodeFields(fields) },
126 }),
127 ),
128 Effect.map(snapshot),
129 ),
130 delete: (path) =>
131 documentName(path).pipe(
132 Effect.flatMap((name) => deleteDocument({ name })),
133 Effect.asVoid,
134 Effect.catchTag("NotFound", () => Effect.void),
135 ),
136 create: (path, fields) => {
137 const { parent, last } = splitLast(path);
138 const collection = splitLast(parent);
139 return databaseName.pipe(
140 Effect.flatMap((db) =>
141 createDocument({
142 parent:
143 collection.parent.length > 0
144 ? `${db}/documents/${collection.parent}`
145 : `${db}/documents`,
146 collectionId: collection.last,
147 documentId: last,
148 body: { fields: encodeFields(fields) },
149 }),
150 ),
151 Effect.map(snapshot),
152 Effect.catchTag("Conflict", (error) =>
153 Effect.fail(
154 new DocumentAlreadyExists({
155 path: trimPath(path),
156 message: error.message,
157 }),
158 ),
159 ),
160 );
161 },
162 };
163 };
164
165 return { makeRead, makeWrite };
166 });
167
168 /** Build a database binding that grants `iam` and returns `makeClient`'s client. */
169 export const makeFirestoreDatabaseBinding = <Client>(options: {
170 tag: string;
171 iam: BindingIam;
172 makeClient: (
173 helpers: Effect.Success<typeof makeFirestoreDatabaseHelpers>,
174 databaseName: Effect.Effect<string>,
175 ) => Client;
176 }) =>
177 Effect.gen(function* () {
178 const bind = yield* GCPBindings.Bind;
179 const helpers = yield* makeFirestoreDatabaseHelpers;
180 return Effect.fn(function* (database: Database) {
181 if (!globalThis.__ALCHEMY_RUNTIME__) {
182 yield* bind`${options.tag}(${database})`({
183 iam: [grantFor(options.iam, database.name)],
184 });
185 }
186 const databaseName = yield* database.name;
187 return options.makeClient(helpers, databaseName);
188 });
189 });