@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, 06:00 UTC

main
ts 124 lines 4.75 KB
Raw
1 import type { Url } from "@alchemy.run/redis";
2 import { UrlMissing as RedisUrlMissing } from "@alchemy.run/redis";
3 import * as redis from "@distilled.cloud/gcp/redis_v1";
4 import * as Output from "alchemy/Output";
5 import * as Config from "effect/Config";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as GCPBindings from "../GCPBindings.ts";
9 import { type GcpIamGrant } from "../Host.ts";
10 import type { Instance } from "./Instance.ts";
11
12 export const REDIS_URL_ENV = "REDIS_URL";
13
14 /**
15 * Shared scaffolding for Memorystore Redis RESP bindings.
16 *
17 * Deploy time transports only the instance's endpoint (`redis[s]://host:port`)
18 * and, when AUTH is enabled, its resource name through the host's
19 * RuntimeContext. The AUTH string itself never enters the host's
20 * configuration: the runtime fetches it once per instance with
21 * `instances.getAuthString`. That permission only exists in
22 * `roles/redis.admin`, so the host is granted `roles/redis.admin` on the
23 * project under an IAM Condition matching the one instance (only when AUTH
24 * is enabled; otherwise `roles/redis.viewer` under the same condition).
25 * `REDIS_URL` in the environment is only a fallback.
26 *
27 * NOT exported from `index.ts`.
28 */
29
30 const redisUrlFromEnv = Config.Redacted(REDIS_URL_ENV).pipe(
31 Effect.map((value) => Redacted.value(value)),
32 );
33
34 const endpointOf = (instance: Instance) =>
35 Output.map(
36 Output.all(instance.host, instance.port, instance.transitEncryptionMode),
37 ([host, port, mode]) =>
38 host === undefined || host.length === 0
39 ? ""
40 : `${mode === "SERVER_AUTHENTICATION" ? "rediss" : "redis"}://${host}:${port ?? 6379}`,
41 );
42
43 /** The instance name when AUTH is enabled, else `""`. */
44 const authInstanceOf = (instance: Instance) =>
45 Output.map(Output.all(instance.name, instance.authEnabled), ([name, authEnabled]) =>
46 authEnabled ? name : "",
47 );
48
49 const scopedCondition = (name: string) => ({
50 title: "alchemy-scoped",
51 expression: `resource.name == "${name}" || resource.name.startsWith("${name}/")`,
52 });
53
54 const authGrantOf = (instance: Instance) =>
55 Output.map(
56 Output.all(instance.name, instance.authEnabled),
57 ([name, authEnabled]): GcpIamGrant => ({
58 role: authEnabled ? "roles/redis.admin" : "roles/redis.viewer",
59 condition: scopedCondition(name),
60 }),
61 );
62
63 const withPassword = (endpoint: string, password: string) =>
64 password.length === 0
65 ? endpoint
66 : endpoint.replace("://", `://:${encodeURIComponent(password)}@`);
67
68 export const makeRedisBinding = <Client>(options: {
69 tag: string;
70 makeClient: (url: Url) => Client;
71 }) =>
72 Effect.gen(function* () {
73 const bind = yield* GCPBindings.Bind;
74 const getAuthString = yield* GCPBindings.withCredentials(
75 redis.getAuthStringProjectsLocationsInstances,
76 );
77 return Effect.fn(function* (instance: Instance) {
78 if (!globalThis.__ALCHEMY_RUNTIME__) {
79 yield* bind`${options.tag}(${instance})`({ iam: [authGrantOf(instance)] });
80 }
81 // A composed Output's binding key is its inspect string, which embeds
82 // the mapping functions' source — and that differs between the
83 // deploy-time source and the bundled runtime. Name it per instance.
84 const endpoint = yield* Output.named(
85 endpointOf(instance),
86 `GCP_REDIS_ENDPOINT_${instance.FQN}`,
87 );
88 const authInstance = yield* Output.named(
89 authInstanceOf(instance),
90 `GCP_REDIS_AUTH_INSTANCE_${instance.FQN}`,
91 );
92 const missing = new RedisUrlMissing({ resourceName: instance.LogicalId });
93 // One AUTH lookup per instance for the life of the runtime; a failed
94 // lookup is not cached, so the next command retries it.
95 let cachedPassword: string | undefined;
96 const password = Effect.suspend(() =>
97 cachedPassword !== undefined
98 ? Effect.succeed(cachedPassword)
99 : Effect.gen(function* () {
100 const name = yield* authInstance;
101 const auth =
102 typeof name === "string" && name.length > 0
103 ? yield* getAuthString({ name })
104 : undefined;
105 cachedPassword = auth?.authString ?? "";
106 return cachedPassword;
107 }),
108 );
109 const url: Url = Effect.gen(function* () {
110 const value = yield* endpoint;
111 if (typeof value !== "string" || value.length === 0) {
112 return yield* redisUrlFromEnv.pipe(Effect.mapError(() => missing));
113 }
114 const secret = yield* password.pipe(
115 Effect.tapError((cause) =>
116 Effect.logError(`Memorystore AUTH lookup failed for ${instance.LogicalId}`, cause),
117 ),
118 Effect.mapError(() => missing),
119 );
120 return withPassword(value, secret);
121 });
122 return options.makeClient(url);
123 });
124 });