Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectPostgresHttp.ts

77 lines2.5 KB

1import * as Binding from "alchemy/Binding";
2import type { Resource } from "alchemy/Resource";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Redacted from "effect/Redacted";
6import {
7 ConnectPostgres,
8 PostgresUrlMissing,
9 type ConnectPostgresClient,
10} from "./ConnectPostgres.ts";
11import type { ServiceBinding } from "./MountVolume.ts";
12import { type Postgres } from "./Postgres.ts";
13​
14const isFlyHost = (value: unknown): value is Resource<string, any, any, ServiceBinding> =>
15 typeof value === "object" &&
16 value !== null &&
17 ((value as { Type?: string }).Type === "Fly.Service" ||
18 (value as { Type?: string }).Type === "Fly.Machine");
19​
20const asRedactedUrl = (
21 value: unknown,
22 name: string,
23): Effect.Effect<Redacted.Redacted<string>, PostgresUrlMissing> => {
24 const plain =
25 typeof value === "string" ? value : Redacted.isRedacted(value) ? Redacted.value(value) : "";
26 const url = typeof plain === "string" ? plain : "";
27 return url.length > 0
28 ? Effect.succeed(Redacted.make(url))
29 : Effect.fail(new PostgresUrlMissing({ resourceName: name }));
30};
31​
32/**
33 * Implementation of {@link ConnectPostgres}. Provide it on the
34 * {@link Service} Effect.
35 *
36 * Registers the cluster attachment for Fly's private network. Alchemy
37 * transports each cluster's connection URIs through resource Outputs,
38 * so callers do not configure connection-string environment variables.
39 *
40 *
41 * ### Provide the layer
42 * **Example:** On a Service
43 * ```typescript
44 * Effect.gen(function* () {
45 * const conn = yield* Fly.ConnectPostgres(Db);
46 * const db = yield* Drizzle.Postgres(conn.connectionString);
47 * }).pipe(Effect.provide(Fly.ConnectPostgresHttp))
48 * ```
49 *
50 * @layer
51 * @product Postgres
52 * @provides Fly.ConnectPostgres
53 */
54export const ConnectPostgresHttp = Layer.effect(
55 ConnectPostgres,
56 Effect.succeed(
57 Effect.fn(function* (postgres: Postgres) {
58 const name = postgres.LogicalId;
59 if (!globalThis.__ALCHEMY_RUNTIME__) {
60 const host = yield* Binding.Host;
61 if (isFlyHost(host)) {
62 yield* host.bind`${postgres}`({
63 postgres: { clusterId: postgres.clusterId },
64 });
65 }
66 }
67​
68 const pooled = yield* postgres.pooledConnectionUri;
69 const direct = yield* postgres.connectionUri;
70​
71 return {
72 connectionString: pooled.pipe(Effect.flatMap((value) => asRedactedUrl(value, name))),
73 directConnectionString: direct.pipe(Effect.flatMap((value) => asRedactedUrl(value, name))),
74 } satisfies ConnectPostgresClient;
75 }),
76 ),
77);