import * as Drizzle from "@alchemy.run/drizzle/Postgres";
import * as Fly from "@alchemy.run/fly";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as Result from "effect/Result";
export const POSTGRES_PORT = 3000;
export const MpgSite = Fly.App("MpgSite", {
enableSubdomains: true,
});
export const Db = Fly.Postgres("Db", {
region: "iad",
plan: "basic",
volumeSizeGb: 10,
});
export const MpgIp = Fly.IpAssignment("Shared", {
app: MpgSite,
type: "shared_v4",
});
/**
* HTTP Service that binds Managed Postgres via {@link Fly.ConnectPostgres}
* and answers SELECT 1. Never returns the connection string.
*/
export default class PostgresApi extends Fly.Service<PostgresApi>()(
"PostgresApi",
{
app: MpgSite,
main: import.meta.url,
region: "iad",
port: POSTGRES_PORT,
guest: { cpuKind: "shared", cpus: 1, memoryMb: 512 },
},
Effect.gen(function* () {
const conn = yield* Fly.ConnectPostgres(Db);
const db = yield* Drizzle.Postgres(conn.connectionString);
const direct = yield* Drizzle.Postgres(conn.directConnectionString);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const path = new URL(request.url, "http://service").pathname;
if (path === "/ping") {
return yield* HttpServerResponse.json({ ok: true });
}
const client = path === "/direct" ? direct : db;
const result = yield* Effect.result(client.execute("select 1 as ok"));
if (Result.isFailure(result)) {
const error = result.failure;
return yield* HttpServerResponse.json(
{
ok: false,
error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
},
{ status: 500 },
);
}
const rows = result.success;
if (path === "/health" || path === "/direct" || path === "/") {
return yield* HttpServerResponse.json({ rows });
}
return yield* HttpServerResponse.json({ rows }, { status: 404 });
}),
};
}).pipe(Effect.provide(Fly.ConnectPostgresHttp)),
) {}