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

main
ts 97 lines 2.95 KB
Raw
1 import * as Output from "alchemy/Output";
2 import * as Effect from "effect/Effect";
3 import * as GCPBindings from "../GCPBindings.ts";
4 import { type BindingIam, type GcpHttpOp, grantFor } from "../HttpBinding.ts";
5 import type { Instance } from "./Instance.ts";
6 import type { User } from "./User.ts";
7
8 /**
9 * Shared HTTP scaffolding for Cloud SQL instance and user bindings.
10 * Distilled ops are OperationMethods: yield them once at Layer
11 * construction so the inner
12 * runtime Effect is `Effect<A, E>` and does not leak `GcpOpContext`.
13 * NOT exported from index.ts.
14 */
15 export const makeSqlInstanceHttpBinding = <
16 I extends { instance?: string; project?: string },
17 A,
18 E,
19 >(options: {
20 tag: string;
21 iam: BindingIam;
22 operation: GcpHttpOp<I, A, E>;
23 }) =>
24 Effect.gen(function* () {
25 const bind = yield* GCPBindings.Bind;
26 const run = yield* GCPBindings.withCredentials(options.operation);
27 return Effect.fn(function* (instance: Instance) {
28 if (!globalThis.__ALCHEMY_RUNTIME__) {
29 yield* bind`${options.tag}(${instance})`({
30 iam: [
31 grantFor(
32 options.iam,
33 Output.interpolate`projects/${instance.project}/instances/${instance.instanceName}`,
34 ),
35 ],
36 });
37 }
38 const instanceName = yield* instance.instanceName;
39 const project = yield* instance.project;
40 return Effect.fn(`${options.tag}(${instance.LogicalId})`)(function* (
41 request?: Omit<I, "instance" | "project">,
42 ) {
43 return yield* run({
44 ...request,
45 instance: yield* instanceName,
46 project: yield* project,
47 } as I);
48 });
49 });
50 });
51
52 export const makeSqlUserHttpBinding = <
53 I extends {
54 name?: string;
55 instance?: string;
56 project?: string;
57 host?: string;
58 },
59 A,
60 E,
61 >(options: {
62 tag: string;
63 iam: BindingIam;
64 operation: GcpHttpOp<I, A, E>;
65 }) =>
66 Effect.gen(function* () {
67 const bind = yield* GCPBindings.Bind;
68 const run = yield* GCPBindings.withCredentials(options.operation);
69 return Effect.fn(function* (user: User) {
70 if (!globalThis.__ALCHEMY_RUNTIME__) {
71 yield* bind`${options.tag}(${user})`({
72 iam: [
73 grantFor(
74 options.iam,
75 Output.interpolate`projects/${user.project}/instances/${user.instance}`,
76 ),
77 ],
78 });
79 }
80 const userName = yield* user.userName;
81 const instance = yield* user.instance;
82 const project = yield* user.project;
83 const host = yield* user.host;
84 return Effect.fn(`${options.tag}(${user.LogicalId})`)(function* (
85 request?: Omit<I, "name" | "instance" | "project">,
86 ) {
87 const resolvedHost = request?.host ?? (yield* host);
88 return yield* run({
89 ...request,
90 name: yield* userName,
91 instance: yield* instance,
92 project: yield* project,
93 ...(resolvedHost ? { host: resolvedHost } : {}),
94 } as I);
95 });
96 });
97 });