fix(db): protege conexoes e migrations de homologacao
This commit is contained in:
1 parent
4779d6b2a3
commit
8c22597420
21 files changed
+839
-45
No files matched your search
+19
-9
@@ -1,8 +1,10 @@
|
||||
import path from "node:path";
|
||||
import { adapterEnv, identityShimEnabled, isDeployedEnv, requireDatabaseUrl } from "../src/config/env";
|
||||
import { adapterEnv, identityShimEnabled, isDeployedEnv } from "../src/config/env";
|
||||
import { exitOnInvalidConfig } from "../src/config/fail-fast";
|
||||
import { buildPostgresOptions, databaseUrlFor, scrubDbError, type DbPurpose } from "../src/infra/db/connection-policy";
|
||||
import { createFileDb } from "../src/infra/db/pglite";
|
||||
import { createPostgresDb } from "../src/infra/db/postgres";
|
||||
import { assertDatabaseGuard } from "../src/infra/db/target-guard";
|
||||
import type { Db } from "../src/infra/db/types";
|
||||
|
||||
/**
|
||||
@@ -10,11 +12,20 @@ import type { Db } from "../src/infra/db/types";
|
||||
* obrigatória: cair em PGlite com um segredo ausente faria uma migração
|
||||
* silenciosa num arquivo local parecer sucesso.
|
||||
*/
|
||||
export async function openOperationalDb(): Promise<Db> {
|
||||
const databaseUrl = requireDatabaseUrl();
|
||||
if (databaseUrl) return createPostgresDb(databaseUrl);
|
||||
export async function openOperationalDb(purpose: DbPurpose): Promise<Db> {
|
||||
const databaseUrl = databaseUrlFor(purpose);
|
||||
if (databaseUrl) {
|
||||
const db = createPostgresDb(databaseUrl, buildPostgresOptions(databaseUrl, purpose));
|
||||
try {
|
||||
await assertDatabaseGuard(db, purpose, databaseUrl);
|
||||
return db;
|
||||
} catch (error) {
|
||||
await db.close().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (isDeployedEnv()) {
|
||||
throw new Error("DATABASE_URL é obrigatória fora de development.");
|
||||
throw new Error("DATABASE_URL é obrigatória fora do PGlite de development.");
|
||||
}
|
||||
const dataDir = path.join(process.cwd(), ".data", "pglite");
|
||||
const { mkdir } = await import("node:fs/promises");
|
||||
@@ -47,17 +58,16 @@ export function runScript(name: string, body: () => Promise<void>): void {
|
||||
process.exitCode ??= 0;
|
||||
},
|
||||
(error: unknown) => {
|
||||
const label = error instanceof Error ? `${error.name}: ${error.message}` : "erro";
|
||||
console.error(`[${name}] ${label}`);
|
||||
console.error(`[${name}] ${scrubDbError(error)}`);
|
||||
process.exit(1);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Abre o banco, executa e fecha, mesmo em caso de falha. */
|
||||
export function runWithDb(name: string, body: (db: Db) => Promise<void>): void {
|
||||
export function runWithDb(name: string, purpose: DbPurpose, body: (db: Db) => Promise<void>): void {
|
||||
runScript(name, async () => {
|
||||
const db = await openOperationalDb();
|
||||
const db = await openOperationalDb(purpose);
|
||||
try {
|
||||
await body(db);
|
||||
} finally {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { bootstrapScript, runWithDb } from "./_bootstrap";
|
||||
|
||||
bootstrapScript("cleanup-temp");
|
||||
|
||||
runWithDb("cleanup-temp", async (db) => {
|
||||
runWithDb("cleanup-temp", "worker", async (db) => {
|
||||
const removed = await cleanupExpired({ db, storage: createStorage(), coordinator: createCoordinator() });
|
||||
console.log(`temporários expirados: ${removed}`);
|
||||
});
|
||||
+1
-1
@@ -11,7 +11,7 @@ const dryRun = process.argv.includes("--dry-run");
|
||||
|
||||
bootstrapScript("migrate");
|
||||
|
||||
runWithDb("migrate", async (db) => {
|
||||
runWithDb("migrate", "admin", async (db) => {
|
||||
const pending = await pendingMigrations(db);
|
||||
console.log(`alvo: ${describeTarget()}`);
|
||||
console.log(`shim de identidade: ${identityShimEnabled() ? "SERÁ aplicado" : "NÃO será aplicado"}`);
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ if (adapterEnv() !== "development") {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
runWithDb("seed-dev", async (db) => {
|
||||
runWithDb("seed-dev", "local", async (db) => {
|
||||
await migrate(db);
|
||||
await ensureDevFixtures(db);
|
||||
console.log("fixtures de desenvolvimento conferidas");
|
||||
|
||||
@@ -120,7 +120,7 @@ runScript("seed-staging", async () => {
|
||||
seed.members ??= [];
|
||||
assertSeed(seed);
|
||||
|
||||
const db = await openOperationalDb();
|
||||
const db = await openOperationalDb("admin");
|
||||
try {
|
||||
const ran = await migrate(db);
|
||||
if (ran.length > 0) console.log(`migrations aplicadas antes do seed: ${ran.join(", ")}`);
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ const enabled = action === "on";
|
||||
|
||||
bootstrapScript("set-flag");
|
||||
|
||||
runWithDb("set-flag", async (db) => {
|
||||
runWithDb("set-flag", "admin", async (db) => {
|
||||
const existing = await db.withService((query) =>
|
||||
query.query<{ name: string }>(`select name from public.workspaces where id = $1`, [workspaceId]),
|
||||
);
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ if (jobRunsInline()) {
|
||||
}
|
||||
|
||||
runScript("worker", async () => {
|
||||
const db = await openOperationalDb();
|
||||
const db = await openOperationalDb("worker");
|
||||
|
||||
// O worker não aplica migrations: isso é passo explícito e aprovado do deploy.
|
||||
const pending = await pendingMigrations(db);
|
||||
|
||||
Reference in new issue
Block a user