Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c01e4acf0a | |||
| 10b78d810d | |||
| cdeebec021 | |||
| 1d6b906202 | |||
| 277f459237 | |||
| ef18ed7376 | |||
| d61607f4c5 | |||
| 2853ce73a5 | |||
| 1e0747324d | |||
| b4b48f7b50 | |||
| fe412933ea | |||
| cd2f60e282 | |||
| 6702086c7b | |||
| 27e6674b9a |
@@ -108,6 +108,8 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
|||||||
| TC-API-1.24 | Complete setup creates super user | POST /api/setup with business name (after TC-API-1.23) | First user becomes super user, setup completes | Setup errors, 403 on admin endpoints |
|
| TC-API-1.24 | Complete setup creates super user | POST /api/setup with business name (after TC-API-1.23) | First user becomes super user, setup completes | Setup errors, 403 on admin endpoints |
|
||||||
| TC-API-1.25 | Super user accesses admin features | After TC-API-1.24, GET /api/staff/me and verify isSuperUser: true | isSuperUser: true, admin endpoints accessible | 403 on admin, isSuperUser: false |
|
| TC-API-1.25 | Super user accesses admin features | After TC-API-1.24, GET /api/staff/me and verify isSuperUser: true | isSuperUser: true, admin endpoints accessible | 403 on admin, isSuperUser: false |
|
||||||
| TC-API-1.26 | Auto-provision skipped during OOBE | During fresh setup (needsSetup: true), complete OIDC login — verify no duplicate staff record created before setup completes | No duplicate staff, OOBE completes successfully | Duplicate staff record, 403 before setup, auto-provision interferes with OOBE |
|
| TC-API-1.26 | Auto-provision skipped during OOBE | During fresh setup (needsSetup: true), complete OIDC login — verify no duplicate staff record created before setup completes | No duplicate staff, OOBE completes successfully | Duplicate staff record, 403 before setup, auto-provision interferes with OOBE |
|
||||||
|
| TC-API-1.27 | Multi-origin CORS — demo host sign-in | `POST /api/auth/sign-in/social` with `callbackURL=https://demo.groombook.dev` | 200 OK, no origin-mismatch error | 400/403 "Origin mismatch" |
|
||||||
|
| TC-API-1.28 | Multi-origin CORS — farh.net host sign-in | `POST /api/auth/sign-in/social` with `callbackURL=https://groombook.farh.net` | 200 OK, no origin-mismatch error | 400/403 "Origin mismatch" |
|
||||||
|
|
||||||
### 4.2 Client Management
|
### 4.2 Client Management
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
"wait-for-db": "node ./scripts/wait-for-db.mjs",
|
"wait-for-db": "node ./scripts/wait-for-db.mjs",
|
||||||
"migrate": "node ./scripts/wait-for-db.mjs && drizzle-kit migrate",
|
"migrate": "node ./scripts/wait-for-db.mjs && drizzle-kit migrate",
|
||||||
"seed": "node ./scripts/wait-for-db.mjs && tsx src/seed.ts",
|
"seed": "node ./scripts/wait-for-db.mjs && tsx src/seed.ts",
|
||||||
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts && drizzle-kit migrate && tsx src/seed.ts",
|
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts",
|
||||||
"studio": "drizzle-kit studio",
|
"studio": "drizzle-kit studio",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,13 +1,52 @@
|
|||||||
/**
|
/**
|
||||||
* reset.ts — Drop all application tables and re-run migrations + seed.
|
* reset.ts — Drop all application tables, re-run migrations, and re-seed.
|
||||||
*
|
*
|
||||||
* Intended for local development only. Never run against production.
|
* Intended for local development only. Never run against production.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
||||||
|
*
|
||||||
|
* GRO-2139: the entire drop→migrate→seed chain runs inside a single
|
||||||
|
* Postgres advisory lock (SEED_ADVISORY_LOCK_KEY) so a concurrent
|
||||||
|
* `seed.ts` (e.g. the dev `seed-test-data-*` Job being recreated at
|
||||||
|
* the top of the hour) cannot interleave between `reset.ts` (DROP)
|
||||||
|
* and `seed.ts` (TRUNCATE+insert) and collide on `invoices_pkey`.
|
||||||
|
*
|
||||||
|
* Why this matters: `seed.ts` derives every primary key from a single
|
||||||
|
* shared Mulberry32 PRNG seeded with 42 (see `createPrng(42)` and
|
||||||
|
* `uuid()` in seed.ts). Two concurrent same-profile seeders therefore
|
||||||
|
* emit *identical* ids for the same logical row, and any moment
|
||||||
|
* between a concurrent `seed.ts` TRUNCATE and INSERT is exactly the
|
||||||
|
* window in which the second seeder's INSERT can hit a pkey already
|
||||||
|
* taken by the first. Pre-GRO-2123 this raced unconditionally;
|
||||||
|
* GRO-2123 added the advisory lock around `runSeedBody` but left
|
||||||
|
* `reset.ts` and `drizzle-kit migrate` outside the lock. This script
|
||||||
|
* now wraps the *whole* chain in the same lock: `withSeedAdvisoryLock`
|
||||||
|
* pins the lock to one reserved session and the DROP → migrate → seed
|
||||||
|
* work runs on the rest of the pool, so the lock guarantees mutual
|
||||||
|
* exclusion against any concurrent seeder for the entire chain.
|
||||||
|
*
|
||||||
|
* See: groombook/infra `apps/base/reset-cronjob.yaml` (CronJob) and
|
||||||
|
* `apps/base/seed-job.yaml` (one-shot Job) — both invoke the same
|
||||||
|
* `seed.ts` code path on the same database in `groombook-dev`.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import postgres from "postgres";
|
import postgres from "postgres";
|
||||||
|
import { drizzle } from "drizzle-orm/postgres-js";
|
||||||
|
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { dirname, resolve } from "node:path";
|
||||||
|
import * as schema from "./schema.js";
|
||||||
|
import {
|
||||||
|
SEED_ADVISORY_LOCK_KEY,
|
||||||
|
withSeedAdvisoryLock,
|
||||||
|
getProfile,
|
||||||
|
runSeedBody,
|
||||||
|
profiles,
|
||||||
|
} from "./seed.js";
|
||||||
|
|
||||||
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = dirname(__filename);
|
||||||
|
const MIGRATIONS_FOLDER = resolve(__dirname, "../migrations");
|
||||||
|
|
||||||
async function reset() {
|
async function reset() {
|
||||||
const url = process.env.DATABASE_URL;
|
const url = process.env.DATABASE_URL;
|
||||||
@@ -16,16 +55,37 @@ async function reset() {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.NODE_ENV === "production" && process.env.ALLOW_RESET !== "true") {
|
if (
|
||||||
console.error("[FATAL] db:reset must not be run in production without ALLOW_RESET=true.");
|
process.env.NODE_ENV === "production" &&
|
||||||
|
process.env.ALLOW_RESET !== "true"
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
"[FATAL] db:reset must not be run in production without ALLOW_RESET=true.",
|
||||||
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const client = postgres(url, { max: 1 });
|
// Pool sizing is load-bearing here. `withSeedAdvisoryLock` does
|
||||||
|
// `pool.reserve()` to pin the advisory lock to one dedicated session
|
||||||
|
// (a session-level lock released on a *different* pooled connection is
|
||||||
|
// a no-op), and the DROP / migrate / seed work then runs on the
|
||||||
|
// *remaining* pooled connections. The lock provides mutual exclusion
|
||||||
|
// across processes regardless of how many connections the work uses —
|
||||||
|
// it does NOT require the work to share the lock's session.
|
||||||
|
//
|
||||||
|
// Therefore `max` must be ≥ 2: 1 reserved for the lock + ≥1 free for
|
||||||
|
// the work. `max: 1` would let `reserve()` consume the only connection
|
||||||
|
// and every query inside the callback would block forever waiting for
|
||||||
|
// a connection that never frees (connection-starvation deadlock). We
|
||||||
|
// use `max: 6` to match `seed()`'s headroom (1 reserved + 5 work).
|
||||||
|
const client = postgres(url, { max: 6 });
|
||||||
|
const db = drizzle(client, { schema });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await withSeedAdvisoryLock(client, async () => {
|
||||||
console.log("Dropping all application tables...\n");
|
console.log("Dropping all application tables...\n");
|
||||||
|
|
||||||
// Drop in dependency order (children before parents)
|
// Drop dependencies (tables) first
|
||||||
await client`
|
await client`
|
||||||
DO $$ DECLARE
|
DO $$ DECLARE
|
||||||
r RECORD;
|
r RECORD;
|
||||||
@@ -61,7 +121,22 @@ async function reset() {
|
|||||||
|
|
||||||
console.log("✓ All tables and enums dropped\n");
|
console.log("✓ All tables and enums dropped\n");
|
||||||
|
|
||||||
|
console.log("Running migrations...");
|
||||||
|
await migrate(db, { migrationsFolder: MIGRATIONS_FOLDER });
|
||||||
|
console.log("✓ Migrations applied\n");
|
||||||
|
|
||||||
|
console.log("Seeding database...");
|
||||||
|
const profile = getProfile();
|
||||||
|
const cfg = profiles[profile];
|
||||||
|
await runSeedBody(client, db, profile, cfg);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`\n✓ Reset complete (advisory lock key=0x${SEED_ADVISORY_LOCK_KEY.toString(16)})`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
await client.end();
|
await client.end();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reset().catch((err) => {
|
reset().catch((err) => {
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ import type { MedicalAlert } from "@groombook/types";
|
|||||||
|
|
||||||
// ── Seed profile configuration ─────────────────────────────────────────────
|
// ── Seed profile configuration ─────────────────────────────────────────────
|
||||||
|
|
||||||
type SeedProfile = "dev" | "uat" | "demo";
|
export type SeedProfile = "dev" | "uat" | "demo";
|
||||||
|
|
||||||
interface ProfileConfig {
|
export interface ProfileConfig {
|
||||||
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
||||||
clientCount: number;
|
clientCount: number;
|
||||||
appointmentsBackDays: number;
|
appointmentsBackDays: number;
|
||||||
@@ -35,7 +35,7 @@ interface ProfileConfig {
|
|||||||
includeUatClients: boolean;
|
includeUatClients: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const profiles: Record<SeedProfile, ProfileConfig> = {
|
export const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||||
dev: {
|
dev: {
|
||||||
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
||||||
clientCount: 100,
|
clientCount: 100,
|
||||||
@@ -70,6 +70,8 @@ function getProfile(): SeedProfile {
|
|||||||
return "uat";
|
return "uat";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { getProfile };
|
||||||
|
|
||||||
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1400,7 +1402,7 @@ async function seedKnownUsers() {
|
|||||||
// from runbooks without ambiguity and binds to the single-argument
|
// from runbooks without ambiguity and binds to the single-argument
|
||||||
// `pg_advisory_lock(int)` form, which postgres-js serializes as a plain
|
// `pg_advisory_lock(int)` form, which postgres-js serializes as a plain
|
||||||
// number (no bigint type plumbing required).
|
// number (no bigint type plumbing required).
|
||||||
const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
export const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
||||||
@@ -1413,7 +1415,7 @@ const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, sta
|
|||||||
* for the lock and release it from the same reserved connection. The
|
* for the lock and release it from the same reserved connection. The
|
||||||
* seed work itself still runs on the pooled connections.
|
* seed work itself still runs on the pooled connections.
|
||||||
*/
|
*/
|
||||||
async function withSeedAdvisoryLock<T>(
|
export async function withSeedAdvisoryLock<T>(
|
||||||
pool: ReturnType<typeof postgres>,
|
pool: ReturnType<typeof postgres>,
|
||||||
fn: () => Promise<T>,
|
fn: () => Promise<T>,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
@@ -1471,7 +1473,7 @@ async function seed() {
|
|||||||
await client.end();
|
await client.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runSeedBody(
|
export async function runSeedBody(
|
||||||
client: ReturnType<typeof postgres>,
|
client: ReturnType<typeof postgres>,
|
||||||
db: ReturnType<typeof drizzle>,
|
db: ReturnType<typeof drizzle>,
|
||||||
profile: SeedProfile,
|
profile: SeedProfile,
|
||||||
|
|||||||
+4
-2
@@ -118,7 +118,8 @@ export async function initAuth(): Promise<void> {
|
|||||||
updateAge: 60 * 60 * 24,
|
updateAge: 60 * 60 * 24,
|
||||||
cookieCache: { enabled: false },
|
cookieCache: { enabled: false },
|
||||||
},
|
},
|
||||||
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
trustedOrigins: (process.env.CORS_ORIGIN ?? "http://localhost:5173")
|
||||||
|
.split(",").map((s) => s.trim()).filter(Boolean),
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -308,7 +309,8 @@ export async function initAuth(): Promise<void> {
|
|||||||
maxAge: 5 * 60, // 5 minutes
|
maxAge: 5 * 60, // 5 minutes
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
trustedOrigins: (process.env.CORS_ORIGIN ?? "http://localhost:5173")
|
||||||
|
.split(",").map((s) => s.trim()).filter(Boolean),
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user