@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 178 lines 7.12 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import * as Output from "alchemy/Output";
3 import { defaultProviderMode } from "alchemy/ProviderMode";
4 import type { ResourceLike } from "alchemy/Resource";
5 import { CurrentRuntimeContext, type RuntimeContext } from "alchemy/RuntimeContext";
6 import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import type { Branch } from "./Branch.ts";
10 import { resolveBranchScope } from "./BranchScope.ts";
11 import { branchScopeOf, type Function } from "./Function.ts";
12 import type { Project } from "./Project.ts";
13
14 /** Postgres connection accessors. Resolving these Effects does not acquire a socket or pool. */
15 export interface ConnectClient {
16 /** Pooled URL for ordinary application queries. */
17 connectionString: Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>;
18 /** Pooled URL, including Neon's pooler hostname. */
19 pooledConnectionString: Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>;
20 /** Direct URL for migrations, notifications, and session-oriented clients. */
21 directConnectionString: Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>;
22 }
23
24 /**
25 * Connect to a Branch or a Project's default database from a Function, Worker,
26 * Lambda, or another Platform host. Same-branch Neon Functions use the injected
27 * `DATABASE_URL` and `DATABASE_URL_UNPOOLED`; local Functions and other hosts
28 * receive namespaced database secrets, never the deployment account API key.
29 *
30 * Accessors are lazy and redacted. `SQL.Postgres` and `Drizzle.Postgres` create
31 * their connections in request scope, not when this binding is initialized.
32 *
33 * ### Querying Postgres
34 * **Example:** Bind a database to an Effect host
35 * ```typescript
36 * Effect.gen(function* () {
37 * const db = yield* Neon.Connect(branch);
38 * const sql = yield* SQL.Postgres({ url: db.connectionString });
39 * return { fetch: Effect.gen(function* () {
40 * return yield* HttpServerResponse.json(yield* sql`SELECT 1 AS value`);
41 * }) };
42 * }).pipe(Effect.provide(Neon.ConnectHttp));
43 * ```
44 *
45 * ### Native applications
46 * **Example:** Explicit environment for a native cross-branch Function
47 * ```typescript
48 * const api = yield* Neon.Function("Api", {
49 * branch: applicationBranch,
50 * main: "./api.ts",
51 * env: Neon.connectEnv(databaseBranch),
52 * });
53 * ```
54 *
55 * Native same-branch Neon Functions already have `DATABASE_URL` and
56 * `DATABASE_URL_UNPOOLED` and need no binding. `connectEnvKeys` gives native
57 * applications the names used by `connectEnv` for cross-host connections.
58 *
59 * @binding
60 * @product Branch
61 */
62 export interface Connect extends Binding.Service<
63 Connect,
64 "Neon.Connect",
65 (database: Branch | Project) => Effect.Effect<ConnectClient>
66 > {}
67
68 export const Connect = Binding.Service<Connect>("Neon.Connect");
69
70 /** Stable, collision-free environment names for native cross-host consumers. */
71 export const connectEnvKeys = (database: Pick<Branch | Project, "FQN">) => {
72 const name = Array.from(database.FQN, (character) => character.codePointAt(0)!.toString(16)).join(
73 "_",
74 );
75 const prefix = `NEON_${name}`;
76 return {
77 injected: `${prefix}_INJECTED`,
78 pooledConnectionString: `${prefix}_DATABASE_URL`,
79 directConnectionString: `${prefix}_DATABASE_URL_UNPOOLED`,
80 };
81 };
82
83 /** Redacted environment outputs for native hosts. No deployment credentials are included. */
84 export const connectEnv = (database: Branch | Project) => {
85 const keys = connectEnvKeys(database);
86 return {
87 [keys.pooledConnectionString]: database.pooledConnectionUri.pipe(Output.map(Redacted.make)),
88 [keys.directConnectionString]: database.connectionUri.pipe(Output.map(Redacted.make)),
89 };
90 };
91
92 const isFunction = (host: ResourceLike | undefined): host is Function =>
93 host?.Type === "Neon.Function";
94 const stringOutput = (value: string | Output.Output<string>) =>
95 typeof value === "string" ? Output.literal(value) : value;
96
97 const injectedScope = (host: ResourceLike | undefined, database: Branch | Project) => {
98 if (!isFunction(host)) return Output.literal(false);
99 const scope = branchScopeOf(host.Props);
100 const targetBranch =
101 database.Type === "Neon.Branch" ? database.branchId : database.defaultBranchId;
102 if (scope.branch) {
103 return Output.all(
104 stringOutput(scope.branch.projectId),
105 stringOutput(scope.branch.branchId),
106 database.projectId,
107 targetBranch,
108 ).pipe(
109 Output.map(
110 ([project, branch, targetProject, target]) =>
111 project === targetProject && branch === target,
112 ),
113 );
114 }
115 if (scope.project) {
116 const resolved = stringOutput(scope.project.projectId).pipe(
117 Output.mapEffect((projectId: string) =>
118 resolveBranchScope({ project: { projectId } }).pipe(Effect.orDie),
119 ),
120 );
121 return Output.all(resolved.projectId, resolved.branchId, database.projectId, targetBranch).pipe(
122 Output.map(
123 ([project, branch, targetProject, target]) =>
124 project === targetProject && branch === target,
125 ),
126 );
127 }
128 return Output.literal(false);
129 };
130
131 /** Host-independent implementation using Platform's common environment channel. */
132 export const ConnectHttp = Layer.effect(
133 Connect,
134 Effect.gen(function* () {
135 const context = yield* CurrentRuntimeContext;
136 if (!context) return yield* Effect.die(new Error("Neon.Connect requires a Platform host"));
137 return Effect.fn(function* (database: Branch | Project) {
138 const keys = connectEnvKeys(database);
139 if (!globalThis.__ALCHEMY_RUNTIME__) {
140 const host = yield* Binding.Host;
141 const mode = host?.Mode ?? (yield* defaultProviderMode);
142 const injected = mode === "local" ? Output.literal(false) : injectedScope(host, database);
143 yield* context.set(keys.injected, injected);
144 yield* context.set(
145 keys.pooledConnectionString,
146 Output.all(injected, database.pooledConnectionUri).pipe(
147 Output.map(([sameBranch, uri]) => (sameBranch ? "" : Redacted.make(uri))),
148 ),
149 );
150 yield* context.set(
151 keys.directConnectionString,
152 Output.all(injected, database.connectionUri).pipe(
153 Output.map(([sameBranch, uri]) => (sameBranch ? "" : Redacted.make(uri))),
154 ),
155 );
156 }
157 const connection = (key: string, injectedKey: string) =>
158 Effect.gen(function* () {
159 const injected = yield* context.get<boolean>(keys.injected);
160 const value = yield* context.get<string | Redacted.Redacted<string>>(
161 injected ? injectedKey : key,
162 );
163 if (value === undefined || value === "") {
164 return yield* Effect.die(
165 new Error(`Missing Neon database environment value: ${injected ? injectedKey : key}`),
166 );
167 }
168 return Redacted.isRedacted(value) ? value : Redacted.make(value);
169 });
170 const pooledConnectionString = connection(keys.pooledConnectionString, "DATABASE_URL");
171 return {
172 connectionString: pooledConnectionString,
173 pooledConnectionString,
174 directConnectionString: connection(keys.directConnectionString, "DATABASE_URL_UNPOOLED"),
175 } satisfies ConnectClient;
176 });
177 }),
178 );