diff --git a/AGENTS.md b/AGENTS.md index 87e6a0602d..69a0ae66b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,8 @@ never seeds data on a client's behalf. - **Parse at every trust boundary.** arktype schemas for env, request bodies, and external data; never `as T` untrusted input. - **Custom DB tables live on their own Postgres schema**, with foreign keys - back to Interchange's tenant/principal tables. + back to Interchange's tenant/principal tables. Each package ships one + idempotent migration, which the hub applies itself at boot. - **Ancestor-walkable except grants.** Credentials, tools, and definitions inherit down the tenant tree; grants never do. - **This repo is public.** No secrets or credentials, ever — `.env.example` @@ -107,5 +108,3 @@ passing; rebuilding coverage for the area it covered happens under CL-8150. disagrees with it is wrong until a review changes the doc - [docs/GLOSSARY.md](docs/GLOSSARY.md) — product-term to platform-term mapping - [docs/local-dev.md](docs/local-dev.md) — running fully local with Ollama -- [docs/package-migrations.md](docs/package-migrations.md) — how a - package's own database migrations are written and applied diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7bdfac8f98..d9a2ed48b9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -50,10 +50,10 @@ stock workflow-deploy route. `tools/*` and `skills/*` are ordinary Custom tables — `webhook-triggers`, `agent-directory`, and so on — live on their own Postgres schema, each with foreign keys back to -Interchange's `tenant`/`principal` tables in `public`. See -[docs/package-migrations.md](docs/package-migrations.md) for how a -package's own migrations are written and applied. Anything Interchange -already does natively is deleted rather than kept as a parallel path. +Interchange's `tenant`/`principal` tables in `public`. Each package ships +one idempotent migration, which the hub applies itself at boot. Anything +Interchange already does natively is deleted rather than kept as a +parallel path. ## Vendoring diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 906ff86372..77b4fff867 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,9 +34,8 @@ Thanks for your interest in Corbits Workbench. 5. Never commit secrets. `.env.example` is the only tracked env file. 6. Never vendor code without a ledger row and kill date in [VENDORED.md](VENDORED.md). -7. A package that owns its own product tables follows - [docs/package-migrations.md](docs/package-migrations.md): literal SQL, - a package-owned ledger table, applied transactionally. +7. A package that owns its own product tables ships one idempotent, + literal-SQL migration, applied by the hub itself at boot. 8. Security issues go through [SECURITY.md](SECURITY.md), never a public issue. 9. Changed a publishable `workflows/*` or `packages/*-tools` package's diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md index da5334f8cd..678f77da72 100644 --- a/IMPLEMENTATION.md +++ b/IMPLEMENTATION.md @@ -12,12 +12,12 @@ check` (typecheck, lint, fmt check, test) is the one gate CI runs. The platform schema (`public`) comes entirely from `@intx/db`'s own migrations — this repo authors no SQL for it. Every package that owns -product tables gets its own Postgres schema, its own literal-SQL migration -list, and its own ledger table tracking which of its migrations have run; -`scripts/db-setup.ts` applies the platform's migrations and then each -installed package's, in an explicit order. See -[docs/package-migrations.md](docs/package-migrations.md) for the exact -rules and shapes. Custom tables are hard-removed when retired — no drop +product tables gets its own Postgres schema and one literal-SQL migration, +every statement `IF NOT EXISTS` so it needs no ledger table; the hub +applies the platform's migrations and then each mounted package's own, +in an explicit order, once at boot (`apps/hub/src/migrate.ts`). +`scripts/db-setup.ts` just creates the database if missing and calls the +same function. Custom tables are hard-removed when retired — no drop migrations, no dead columns kept around; a schema cutover means resetting the local database, not writing a data migration. diff --git a/apps/hub/package.json b/apps/hub/package.json index bf4765fc66..cbd6f47de0 100644 --- a/apps/hub/package.json +++ b/apps/hub/package.json @@ -20,7 +20,6 @@ "@corbits/codex-provider": "github:corbitsdev/corbits-codex-provider#a1f475f341261c05fa8dade0c82f1246c175b5b3", "@corbits/cron": "workspace:*", "@corbits/error-sink": "workspace:*", - "@corbits/hub-api-client": "workspace:*", "@corbits/inference-catalog": "workspace:*", "@corbits/mailbox": "github:corbitsdev/corbits-mailbox#e85b81e4a2e0cc318dd33a4f0f92337b6fac7f38", "@corbits/memory": "github:corbitsdev/corbits-memory#e74da20f148a302dff5400915fe504ee2395e913", diff --git a/apps/hub/src/migrate.ts b/apps/hub/src/migrate.ts new file mode 100644 index 0000000000..53af3cdeb5 --- /dev/null +++ b/apps/hub/src/migrate.ts @@ -0,0 +1,59 @@ +// Boot-time migrations for the hub, run once before `createHubServer` +// mounts anything. Interchange's own platform schema is authored and +// applied by `@intx/db`'s `runMigrations`; every mounted Corbits +// library that owns its own product tables applies its own single, +// idempotent migration right after, exactly the way upstream +// Interchange applies its schema — no separate migration-runner +// service, no ledger table, just the hub doing the work itself. +import { runMigrations } from "@intx/db"; +import { applyCronMigrations } from "@corbits/cron"; +import { applyWebhookTriggersMigrations } from "@corbits/webhook-triggers"; +import { createMailboxDb, runMailboxMigrations } from "@corbits/mailbox"; +import { runArtifactMigrations } from "@corbits/artifacts"; +import { runMemoryMigrations } from "@corbits/memory"; + +export interface HubMigrateConfig { + host: string; + port: number; + user: string; + password: string; + database: string; + schema?: string; +} + +function databaseUrlFrom(config: HubMigrateConfig): string { + return ( + `postgres://${encodeURIComponent(config.user)}:${encodeURIComponent(config.password)}` + + `@${config.host}:${String(config.port)}/${config.database}` + ); +} + +/** + * Apply the platform schema plus every mounted Corbits package's own + * migration, in the order the hub mounts them: cron, webhook-triggers, + * mailbox, artifacts, memory. `db` is the same drizzle handle the rest + * of the hub uses, so `runArtifactMigrations` (which takes a drizzle + * db, not a URL) shares the one connection pool rather than opening + * its own. + */ +export async function migrateHub( + config: HubMigrateConfig, + db: Parameters[0], +): Promise { + const databaseUrl = databaseUrlFrom(config); + const schema = config.schema ?? "public"; + + await runMigrations(config, { schema }); + await applyCronMigrations(databaseUrl, { tenantSchema: schema }); + await applyWebhookTriggersMigrations(databaseUrl); + + const mailboxDb = createMailboxDb(databaseUrl); + try { + await runMailboxMigrations(mailboxDb.db); + } finally { + await mailboxDb.close(); + } + + await runArtifactMigrations(db); + await runMemoryMigrations(databaseUrl); +} diff --git a/apps/hub/src/server.ts b/apps/hub/src/server.ts index 656175b684..15d43059c4 100644 --- a/apps/hub/src/server.ts +++ b/apps/hub/src/server.ts @@ -64,7 +64,7 @@ import { mountMailbox, } from "@corbits/mailbox"; import { createMemory, loadMemoryConfig } from "@corbits/memory"; -import { applyCronMigrations, createCronTicker, mountCron } from "@corbits/cron"; +import { createCronTicker, mountCron } from "@corbits/cron"; import { createHubMailboxAuthorizeSender, createHubPersistMailWithSessionEnsure, @@ -86,7 +86,6 @@ import { InlineContentStore, mountArtifacts, mountWorkflowArtifacts, - runArtifactMigrations, type WorkflowArtifactEnv, } from "@corbits/artifacts"; import { @@ -96,6 +95,7 @@ import { import type { DB } from "@intx/db"; import { sidecar, workflowRun } from "@intx/db/schema"; import path from "node:path"; +import { migrateHub } from "./migrate"; // The same condition registry `mountHubRoutes` builds by default when no // registry is supplied -- kept as one local constant so every Corbits @@ -184,14 +184,20 @@ export async function createHubServer({ // dedicated, droppable schema. Production deployments leave it // unset and run against postgres' default search_path. const pgSchema = process.env["PG_SCHEMA"]; - const { db } = createDB({ + const dbConfig = { host: process.env["DB_HOST"] ?? "localhost", port: Number(process.env["DB_PORT"] ?? 5432), user: process.env["DB_USER"] ?? "postgres", password: process.env["DB_PASSWORD"] ?? "postgres", database: process.env["DB_NAME"] ?? "interchange", ...(pgSchema !== undefined && { schema: pgSchema }), - }); + }; + const { db } = createDB(dbConfig); + + // Platform schema plus every mounted Corbits package's own migration, + // applied once at boot before anything below reads or writes the + // database. + await migrateHub(dbConfig, db); const auth = createAuth(db); @@ -493,8 +499,6 @@ export async function createHubServer({ }), }; - await runArtifactMigrations(db); - await applyCronMigrations(corbitsDatabaseUrl); const artifactContentStore = InlineContentStore; { diff --git a/bun.lock b/bun.lock index c41b2cc9ee..bebc30531c 100644 --- a/bun.lock +++ b/bun.lock @@ -59,7 +59,6 @@ "@corbits/codex-provider": "github:corbitsdev/corbits-codex-provider#a1f475f341261c05fa8dade0c82f1246c175b5b3", "@corbits/cron": "workspace:*", "@corbits/error-sink": "workspace:*", - "@corbits/hub-api-client": "workspace:*", "@corbits/inference-catalog": "workspace:*", "@corbits/mailbox": "github:corbitsdev/corbits-mailbox#e85b81e4a2e0cc318dd33a4f0f92337b6fac7f38", "@corbits/memory": "github:corbitsdev/corbits-memory#e74da20f148a302dff5400915fe504ee2395e913", @@ -288,17 +287,6 @@ "@intx/log": "0.3.0", }, }, - "packages/hub-api-client": { - "name": "@corbits/hub-api-client", - "version": "0.0.1", - "dependencies": { - "arktype": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - }, "packages/inference-catalog": { "name": "@corbits/inference-catalog", "version": "0.1.0", @@ -315,18 +303,6 @@ "@intx/types": "0.3.0", }, }, - "packages/migration-runner": { - "name": "@corbits/migration-runner", - "version": "0.0.1", - "dependencies": { - "@intx/log": "0.3.0", - "postgres": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - }, "packages/tool-registry-publish": { "name": "@corbits/tool-registry-publish", "version": "0.0.1", @@ -356,7 +332,6 @@ "dependencies": { "@corbits/collections": "workspace:*", "@corbits/error-sink": "workspace:*", - "@corbits/migration-runner": "workspace:*", "@corbits/workflows": "workspace:*", "@intx/crypto": "0.3.0", "@intx/db": "workspace:*", @@ -1043,8 +1018,6 @@ "@corbits/granola-tools": ["@corbits/granola-tools@workspace:tools/granola"], - "@corbits/hub-api-client": ["@corbits/hub-api-client@workspace:packages/hub-api-client"], - "@corbits/inference-catalog": ["@corbits/inference-catalog@workspace:packages/inference-catalog"], "@corbits/interaction-tools": ["@corbits/interaction-tools@workspace:tools/interaction"], @@ -1055,8 +1028,6 @@ "@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], - "@corbits/migration-runner": ["@corbits/migration-runner@workspace:packages/migration-runner"], - "@corbits/myra": ["@corbits/myra@workspace:agents/myra"], "@corbits/oauth-core": ["@corbits/oauth-core@github:corbitsdev/corbits-oauth-core#1b7f9fb", { "dependencies": { "arktype": "2.2.3" } }, "corbitsdev-corbits-oauth-core-1b7f9fb", "sha512-PscyiDAl46umTM44NQPN1q5+PsGUV53Rxr4Wz/Ofz+k9LOOz6FBKamRFtWR8YWdKJt9I8sPOLOyEcMNNN2i+YQ=="], diff --git a/docs/package-migrations.md b/docs/package-migrations.md deleted file mode 100644 index d188b9a734..0000000000 --- a/docs/package-migrations.md +++ /dev/null @@ -1,57 +0,0 @@ -# Package migrations - -Convention for any package under `packages/` that owns its own product -tables. - -## The rules - -- **Literal SQL, not codegen.** Every migration is a plain string in a - `{ name, sql }[]` array, hand-written and reviewed as-is — never a - schema diff generated by `drizzle-kit` at apply time. What a reviewer - reads in the PR is exactly what runs against the database. -- **A ledger table the package owns.** Each package tracks which of its - own migrations have run in a table named for itself (e.g. - `webhook_triggers_migrations`) — never the platform's own `@intx/db` - drizzle journal, and never `scripts/db-setup.ts`'s own migration - tracking, which only covers the platform. If the package is ever - extracted into its own repo, its migration history goes with it. -- **Every package owns a schema named for itself.** No package table - lives in `public` — that belongs to `@intx/db` alone. A package's - tenant/principal columns are plain text ids, not foreign keys, so - which schema a table lives in is never load-bearing for that - reference; it only matters for keeping the package extractable. -- **Every migration is transactional.** A migration's SQL and its ledger - `INSERT` run inside one `sql.begin(...)` transaction, so a failure - partway through never leaves a half-applied table with no ledger row - to explain it. -- **A session-level advisory lock guards the whole run**, so two hub - replicas booting at once don't race the same ledger insert. - -Mechanics — schema/ledger bootstrap, the transactional apply loop, and -the advisory lock — live once in `@corbits/migration-runner`'s -`applyPackageMigrations`; a package's own `migrations.ts` supplies only -its schema name, ledger table name, and literal migration array. See -`packages/webhook-triggers/src/migrations.ts` for the reference shape. - -## Wiring a new package in - -`scripts/db-setup.ts` imports each installed package's -`applyXMigrations(databaseUrl)` and calls it, in an explicit literal -list, right after the platform's own migrations — no discovery magic, -no globbing. Add the new package's entry to that list. - -A package that ships its own independently-owned migration runner as -part of a larger engine (its own schema, its own connection handling — -`@corbits/mailbox` is the example) can instead be wired as a thin -delegate: `scripts/db-setup.ts` opens a connection and calls the -package's own exported runner, with no opinion on what SQL it runs. -Reach for this only when the package already has such a runner, never as -a shortcut to skip writing a ledger table. - -## Why not `drizzle-kit` codegen - -Drizzle is used as a query builder and for type definitions, but package -migrations are never generated by pointing `drizzle-kit` at a schema and -diffing. A generated migration reviewed as a schema diff, with the -actual SQL produced later by codegen, lets the reviewed artifact and the -applied artifact drift. Literal SQL closes that gap. diff --git a/package.json b/package.json index 51707a044c..157497aab5 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,6 @@ "build": "bun run scripts/run-all.ts build", "test": "bun run scripts/run-all.ts test", "dev": "bun run scripts/dev.ts", - "publish-tools": "bun scripts/publish-tools.ts", "setup": "bun scripts/db-setup.ts", "setup:memory": "bun run scripts/setup-memory.ts", "reset": "bun scripts/reset.ts" diff --git a/packages/cron/src/index.ts b/packages/cron/src/index.ts index 2c3556bb08..23615e03ee 100644 --- a/packages/cron/src/index.ts +++ b/packages/cron/src/index.ts @@ -9,13 +9,7 @@ export { type CronField, type ZonedParts, } from "./cron"; -export { - cronScheduleTable, - cronMigrations, - applyCronMigrations, - type CronMigration, - type ApplyCronMigrationsReport, -} from "./schema"; +export { cronScheduleTable, applyCronMigrations } from "./schema"; export { createCronTicker, cronSenderAddress, diff --git a/packages/cron/src/migrations.ts b/packages/cron/src/migrations.ts index 0fec612e01..721956f637 100644 --- a/packages/cron/src/migrations.ts +++ b/packages/cron/src/migrations.ts @@ -1 +1 @@ -export { applyCronMigrations, type ApplyCronMigrationsReport } from "./schema"; +export { applyCronMigrations } from "./schema"; diff --git a/packages/cron/src/schema.ts b/packages/cron/src/schema.ts index bf4b5ee763..bbd1242941 100644 --- a/packages/cron/src/schema.ts +++ b/packages/cron/src/schema.ts @@ -21,101 +21,56 @@ export const cronScheduleTable = cronSchema.table("schedule", { createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }); -const LEDGER_TABLE = "cron_migrations"; - -export interface CronMigration { - name: string; - sql: string; -} - function quoteIdentifier(name: string): string { return `"${name.replace(/"/g, '""')}"`; } /** - * Migration list building the FK against `tenantSchema.tenant` — - * `"public"` in every real deployment; a test harness that runs the - * platform migrations into a scratch schema passes that schema instead so - * the FK targets its own `tenant` row, not the real one. + * The package's one idempotent migration, built against + * `tenantSchema.tenant` — `"public"` in every real deployment; a test + * harness that runs the platform migrations into a scratch schema + * passes that schema instead so the FK targets its own `tenant` row, + * not the real one. Every statement is `IF NOT EXISTS`, so no ledger + * table is needed to know what has already run. */ -function buildCronMigrations(tenantSchema: string): readonly CronMigration[] { +function cronMigrationSql(tenantSchema: string): string { const tenantTable = `${quoteIdentifier(tenantSchema)}."tenant"`; - return [ - { - name: "0001_schedule", - sql: ` - CREATE SCHEMA IF NOT EXISTS "cron"; - CREATE TABLE IF NOT EXISTS "cron"."schedule" ( - "id" text PRIMARY KEY, - "tenant_id" text NOT NULL REFERENCES ${tenantTable}("id") ON DELETE CASCADE, - "expression" text NOT NULL, - "to_address" text NOT NULL, - "subject" text NOT NULL, - "body" text NOT NULL, - "last_fired_at" timestamptz, - "created_at" timestamptz NOT NULL DEFAULT now() - ); - CREATE INDEX IF NOT EXISTS "cron_schedule_tenant_id_idx" ON "cron"."schedule" ("tenant_id"); - `, - }, - ]; -} - -export const cronMigrations: readonly CronMigration[] = buildCronMigrations("public"); - -export interface ApplyCronMigrationsReport { - applied: string[]; - alreadyApplied: string[]; + return ` + CREATE SCHEMA IF NOT EXISTS "cron"; + CREATE TABLE IF NOT EXISTS "cron"."schedule" ( + "id" text PRIMARY KEY, + "tenant_id" text NOT NULL REFERENCES ${tenantTable}("id") ON DELETE CASCADE, + "expression" text NOT NULL, + "to_address" text NOT NULL, + "subject" text NOT NULL, + "body" text NOT NULL, + "last_fired_at" timestamptz, + "created_at" timestamptz NOT NULL DEFAULT now() + ); + CREATE INDEX IF NOT EXISTS "cron_schedule_tenant_id_idx" ON "cron"."schedule" ("tenant_id"); + `; } /** - * Apply `cronMigrations` against `databaseUrl`, idempotently: a migration - * already recorded in this package's own ledger is skipped, never re-run. - * Package-owned ledger, transactional apply. + * Apply the package's migration against `databaseUrl`, idempotently + * (every statement is `IF NOT EXISTS`) and inside one advisory-locked + * transaction so concurrent hub replicas cannot race the same DDL. */ export async function applyCronMigrations( databaseUrl: string, options?: { tenantSchema?: string }, -): Promise { +): Promise { const client = postgres(databaseUrl, { max: 1, onnotice: () => undefined }); try { - await client.unsafe(`CREATE SCHEMA IF NOT EXISTS "cron"`); - await client.unsafe( - `CREATE TABLE IF NOT EXISTS "cron"."${LEDGER_TABLE}" (` + - `name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`, + await client.begin(async (tx) => { + await tx.unsafe(`SELECT pg_advisory_xact_lock(hashtext('corbits_cron'))`); + await tx.unsafe(cronMigrationSql(options?.tenantSchema ?? "public")); + }); + } catch (error) { + throw new Error( + `@corbits/cron migration failed: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, ); - - const applied: string[] = []; - const alreadyApplied: string[] = []; - const migrations = buildCronMigrations(options?.tenantSchema ?? "public"); - - for (const migration of migrations) { - const existing = await client.unsafe( - `SELECT 1 FROM "cron"."${LEDGER_TABLE}" WHERE name = $1`, - [migration.name], - ); - if (existing.length > 0) { - alreadyApplied.push(migration.name); - continue; - } - try { - await client.begin(async (tx) => { - await tx.unsafe(migration.sql); - await tx.unsafe(`INSERT INTO "cron"."${LEDGER_TABLE}" (name) VALUES ($1)`, [ - migration.name, - ]); - }); - applied.push(migration.name); - } catch (error) { - throw new Error( - `@corbits/cron migration ${JSON.stringify(migration.name)} failed: ` + - `${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); - } - } - - return { applied, alreadyApplied }; } finally { await client.end({ timeout: 5 }); } diff --git a/packages/hub-api-client/LICENSE b/packages/hub-api-client/LICENSE deleted file mode 100644 index 173c3a21d0..0000000000 --- a/packages/hub-api-client/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - one line to give the library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 of the License. - - This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/hub-api-client/package.json b/packages/hub-api-client/package.json deleted file mode 100644 index 4e1e780513..0000000000 --- a/packages/hub-api-client/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "@corbits/hub-api-client", - "version": "0.0.1", - "private": true, - "description": "The hub's native HTTP API as a typed client: authenticate, sign in, and call any route with a validated response", - "license": "LGPL-2.1-only", - "type": "module", - "exports": { - ".": "./src/index.ts" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "arktype": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - } -} diff --git a/packages/hub-api-client/src/cookies.test.ts b/packages/hub-api-client/src/cookies.test.ts deleted file mode 100644 index 224beed50c..0000000000 --- a/packages/hub-api-client/src/cookies.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { cookiesFromHeader } from "./cookies"; - -describe("cookiesFromHeader", () => { - test("returns an empty array for an absent header", () => { - expect(cookiesFromHeader(undefined)).toEqual([]); - }); - - test("splits a multi-pair Cookie header on ';' and trims whitespace", () => { - expect(cookiesFromHeader("a=1; b=2 ;c=3")).toEqual(["a=1", "b=2", "c=3"]); - }); - - test("drops empty segments from a trailing or doubled separator", () => { - expect(cookiesFromHeader("a=1;; ;b=2;")).toEqual(["a=1", "b=2"]); - }); -}); diff --git a/packages/hub-api-client/src/cookies.ts b/packages/hub-api-client/src/cookies.ts deleted file mode 100644 index f3776f953e..0000000000 --- a/packages/hub-api-client/src/cookies.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Inbound cookie-header parsing, shared by every route package that -// forwards a caller's session cookie into a self-HTTP call against the -// hub's native API. Sibling to `hub.ts`'s outbound cookie-jar logic -// (`createHubAPI`'s `Cookie` header join) but the other direction: a raw -// `Cookie` request header in, one string per `name=value` pair out. -export function cookiesFromHeader(header: string | undefined): string[] { - if (!header) return []; - return header - .split(";") - .map((pair) => pair.trim()) - .filter((pair) => pair.length > 0); -} diff --git a/packages/hub-api-client/src/errors.test.ts b/packages/hub-api-client/src/errors.test.ts deleted file mode 100644 index 6c9e4cc722..0000000000 --- a/packages/hub-api-client/src/errors.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { - HubApiError, - isHubApiError, - isSidecarUnavailableError, - SidecarUnavailableError, -} from "./errors"; - -describe("HubApiError", () => { - test("carries the problem as its message and the fix separately", () => { - const error = new HubApiError("the hub is unreachable", "start it first"); - expect(error.message).toBe("the hub is unreachable"); - expect(error.fix).toBe("start it first"); - expect(error.name).toBe("HubApiError"); - }); - - test("isHubApiError narrows only actual HubApiError instances", () => { - expect(isHubApiError(new HubApiError("x", "y"))).toBe(true); - expect(isHubApiError(new Error("plain"))).toBe(false); - expect(isHubApiError("not an error")).toBe(false); - }); -}); - -describe("SidecarUnavailableError", () => { - test("is a HubApiError with its own distinct name", () => { - const error = new SidecarUnavailableError("sidecar down", "wait and retry"); - expect(error).toBeInstanceOf(HubApiError); - expect(error.name).toBe("SidecarUnavailableError"); - expect(isHubApiError(error)).toBe(true); - }); - - test("isSidecarUnavailableError rejects a generic HubApiError", () => { - expect(isSidecarUnavailableError(new SidecarUnavailableError("x", "y"))).toBe(true); - expect(isSidecarUnavailableError(new HubApiError("x", "y"))).toBe(false); - }); -}); diff --git a/packages/hub-api-client/src/errors.ts b/packages/hub-api-client/src/errors.ts deleted file mode 100644 index 488dfc2755..0000000000 --- a/packages/hub-api-client/src/errors.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * A failure the operator can act on. Every error the hub client raises - * names the exact problem and carries the command or change that fixes - * it, so a fresh user is never left guessing. - */ -export class HubApiError extends Error { - readonly fix: string; - - constructor(problem: string, fix: string, options?: ErrorOptions) { - super(problem, options); - this.name = "HubApiError"; - this.fix = fix; - } -} - -export function isHubApiError(value: unknown): value is HubApiError { - return value instanceof HubApiError; -} - -/** - * The specific `HubApiError` `ensureDeployment` raises when the hub answers - * a workflow-deployment create with 502 `sidecar_unavailable`: the - * sidecar that hosts workflow execution is down, but every durable step - * ahead of it (tenant, grants, credential, catalog, workflow assets) - * already succeeded. A caller deploying several workflows in sequence - * can parse this exact class to finish successfully with an honest - * "agents pending" report, instead of failing the whole flow the way - * any other `HubApiError` still does. - */ -export class SidecarUnavailableError extends HubApiError { - constructor(problem: string, fix: string, options?: ErrorOptions) { - super(problem, fix, options); - this.name = "SidecarUnavailableError"; - } -} - -export function isSidecarUnavailableError(value: unknown): value is SidecarUnavailableError { - return value instanceof SidecarUnavailableError; -} diff --git a/packages/hub-api-client/src/hub.test.ts b/packages/hub-api-client/src/hub.test.ts deleted file mode 100644 index de3d4613b3..0000000000 --- a/packages/hub-api-client/src/hub.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -// `authenticate`/`signIn` against a stub hub: signup is ungated in stock -// composition, so no failure path may prescribe a signup env key. -import { describe, expect, test } from "bun:test"; - -import { HubApiError } from "./errors"; -import { authenticate, signIn, type ApiCall, type ApiResult } from "./hub"; - -function stubApi(handler: (method: string, path: string) => ApiResult): ApiCall { - return (method, path) => Promise.resolve(handler(method, path)); -} - -const signInOk: ApiResult = { - status: 200, - data: { user: { id: "user_1" } }, - cookies: ["session=abc"], -}; - -describe("authenticate", () => { - test("an existing account signs in without a sign-up call", async () => { - let signUpCalls = 0; - const api = stubApi((_, path) => { - if (path === "/api/auth/sign-up/email") signUpCalls += 1; - return signInOk; - }); - const session = await authenticate(api, { - email: "admin@acme.example", - password: "secret", - }); - expect(session).toEqual({ - cookies: ["session=abc"], - userId: "user_1", - signedUp: false, - }); - expect(signUpCalls).toBe(0); - }); - - test("a missing account signs up after sign-in fails", async () => { - const api = stubApi((_, path) => { - if (path === "/api/auth/sign-in/email") return { status: 401, data: null, cookies: [] }; - return { - status: 200, - data: { user: { id: "user_2" } }, - cookies: ["session=def"], - }; - }); - const session = await authenticate(api, { - email: "new@acme.example", - password: "secret", - }); - expect(session.signedUp).toBe(true); - expect(session.userId).toBe("user_2"); - }); - - test("a 422 sign-up means the address exists with a different password", async () => { - const api = stubApi((_, path) => { - if (path === "/api/auth/sign-in/email") return { status: 401, data: null, cookies: [] }; - return { status: 422, data: null, cookies: [] }; - }); - const error = await authenticate(api, { - email: "admin@acme.example", - password: "wrong", - }).catch((cause: unknown) => cause); - expect(error).toBeInstanceOf(HubApiError); - expect((error as HubApiError).fix).toMatch(/HUB_ADMIN_PASSWORD/); - }); - - test("a rejected sign-up never prescribes a signup env key", async () => { - const api = stubApi((_, path) => { - if (path === "/api/auth/sign-in/email") return { status: 401, data: null, cookies: [] }; - return { - status: 403, - data: { error: "signup_closed" }, - cookies: [], - }; - }); - const error = await authenticate(api, { - email: "new@acme.example", - password: "secret", - }).catch((cause: unknown) => cause); - expect(error).toBeInstanceOf(HubApiError); - expect((error as HubApiError).message).not.toMatch(/WORKBENCH_SIGNUP/); - expect((error as HubApiError).fix).not.toMatch(/WORKBENCH_SIGNUP/); - }); -}); - -describe("signIn", () => { - test("sign-in only, never signs up", async () => { - let signUpCalls = 0; - const api = stubApi((_, path) => { - if (path === "/api/auth/sign-up/email") signUpCalls += 1; - return signInOk; - }); - const session = await signIn(api, { - email: "admin@acme.example", - password: "secret", - }); - expect(session.signedUp).toBe(false); - expect(signUpCalls).toBe(0); - }); - - test("a failed sign-in names the admin credential to check", async () => { - const api = stubApi(() => ({ status: 401, data: null, cookies: [] })); - const error = await signIn(api, { - email: "admin@acme.example", - password: "wrong", - }).catch((cause: unknown) => cause); - expect(error).toBeInstanceOf(HubApiError); - expect((error as HubApiError).fix).toMatch(/HUB_ADMIN/); - }); -}); diff --git a/packages/hub-api-client/src/hub.ts b/packages/hub-api-client/src/hub.ts deleted file mode 100644 index 077d0068a2..0000000000 --- a/packages/hub-api-client/src/hub.ts +++ /dev/null @@ -1,174 +0,0 @@ -// Thin fetch boundary against the hub's native HTTP API, plus the -// response-validation and authentication helpers both verbs share. -// Everything network-shaped funnels through `ApiCall` so tests can -// substitute the whole hub with a function. - -import { type, type Type } from "arktype"; -import { HubApiError } from "./errors"; - -export type ApiResult = { - status: number; - data: unknown; - cookies: string[]; -}; - -export type ApiCall = ( - method: string, - path: string, - body?: unknown, - cookies?: string[], -) => Promise; - -/** - * Build the real hub API caller: JSON in, JSON out, with a cookie jar - * threaded through so better-auth sessions survive across calls. A - * network-level failure is a fresh-user failure, so it is reported as - * one: the hub is not running, and the fix is to start it. - */ -export function createHubAPI(baseUrl: string, fetchImpl: typeof fetch = fetch): ApiCall { - return async (method, path, body, cookies = []) => { - const headers: Record = { - "Content-Type": "application/json", - }; - if (cookies.length > 0) headers["Cookie"] = cookies.join("; "); - - let response: Response; - try { - response = await fetchImpl(`${baseUrl}${path}`, { - method, - headers, - ...(body !== undefined ? { body: JSON.stringify(body) } : {}), - redirect: "manual", - }); - } catch (cause) { - throw new HubApiError( - `the hub at ${baseUrl} is not reachable (${cause instanceof Error ? cause.message : String(cause)})`, - "start the stack first — `bun run dev` from the repository root — wait for the hub to report it is serving, then re-run this command", - { cause }, - ); - } - - const jar = [...cookies]; - for (const setCookie of response.headers.getSetCookie()) { - const pair = setCookie.split(";")[0]; - if (pair === undefined || !pair.includes("=")) continue; - const name = pair.split("=")[0]; - const existing = jar.findIndex((c) => c.startsWith(`${name}=`)); - if (existing >= 0) jar[existing] = pair; - else jar.push(pair); - } - - let data: unknown = null; - const contentType = response.headers.get("content-type") ?? ""; - if (contentType.includes("json")) data = await response.json(); - - return { status: response.status, data, cookies: jar }; - }; -} - -/** - * Validate a hub response body against its published schema. A - * mismatch means the hub and this checkout disagree about the API, and - * the fix is to bring them back in sync — never to limp on with data - * of an unknown shape. - */ -export function parseAs(schema: T, data: unknown, label: string): T["infer"] { - const result = schema(data); - if (result instanceof type.errors) { - throw new HubApiError( - `the hub returned an unexpected ${label}: ${result.summary}`, - "the running hub does not match this checkout; restart it from this checkout (`bun run dev`) and re-run the command", - ); - } - return result; -} - -const AuthResponse = type({ "user?": { id: "string" } }); - -export type Session = { - cookies: string[]; - userId: string; - signedUp: boolean; -}; - -async function trySignIn( - api: ApiCall, - args: { email: string; password: string }, -): Promise { - const signIn = await api("POST", "/api/auth/sign-in/email", { - email: args.email, - password: args.password, - }); - if (signIn.status === 200) { - const parsed = parseAs(AuthResponse, signIn.data, "sign-in response"); - return { - cookies: signIn.cookies, - userId: parsed.user?.id ?? "", - signedUp: false, - }; - } - return { failedStatus: signIn.status }; -} - -/** - * Sign the administrator in — sign-in only, never sign-up. For callers - * that must never mint an account (e.g. automated setup, which runs - * unattended and must not self-provision the default admin credential - * on a fresh database), this is the only safe entry point. - */ -export async function signIn( - api: ApiCall, - args: { email: string; password: string }, -): Promise { - const result = await trySignIn(api, args); - if (!("failedStatus" in result)) return result; - throw new HubApiError( - `sign-in failed for ${args.email} (status ${result.failedStatus})`, - "verify HUB_ADMIN_EMAIL/HUB_ADMIN_PASSWORD match an existing admin account", - ); -} - -/** - * Sign the administrator in, or sign up when the account does not exist - * yet. Sign-in is tried first so an existing admin never mints a - * duplicate account. Signup is ungated in stock composition, so a - * rejected sign-up is reported with the hub logs as the fix — never - * with an env key. - */ -export async function authenticate( - api: ApiCall, - args: { email: string; password: string }, -): Promise { - const name = args.email.split("@")[0] ?? args.email; - - const signInAttempt = await trySignIn(api, args); - if (!("failedStatus" in signInAttempt)) return signInAttempt; - - const signUp = await api("POST", "/api/auth/sign-up/email", { - name, - email: args.email, - password: args.password, - }); - if (signUp.status === 200) { - const parsed = parseAs(AuthResponse, signUp.data, "sign-up response"); - return { - cookies: signUp.cookies, - userId: parsed.user?.id ?? "", - signedUp: true, - }; - } - - // better-auth answers 422 when the address is already registered — - // that means the password did not match on sign-in above. - if (signUp.status === 422) { - throw new HubApiError( - `${args.email} already exists on the hub but HUB_ADMIN_PASSWORD does not match it (sign-in returned ${signInAttempt.failedStatus})`, - "set HUB_ADMIN_PASSWORD to the password this account was created with, or use a fresh HUB_ADMIN_EMAIL, then re-run the command", - ); - } - - throw new HubApiError( - `the hub rejected sign-up for ${args.email} with status ${signUp.status}: ${JSON.stringify(signUp.data)}`, - "check the hub logs for the underlying failure, fix it, then re-run the command", - ); -} diff --git a/packages/hub-api-client/src/index.ts b/packages/hub-api-client/src/index.ts deleted file mode 100644 index 7b386d89b8..0000000000 --- a/packages/hub-api-client/src/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -// The hub's native HTTP API as a typed client: authenticate, sign in, -// and call any route with a validated response. - -export type { ApiCall, ApiResult, Session } from "./hub"; -export { authenticate, createHubAPI, parseAs, signIn } from "./hub"; -export { - HubApiError, - isHubApiError, - isSidecarUnavailableError, - SidecarUnavailableError, -} from "./errors"; -export { cookiesFromHeader } from "./cookies"; diff --git a/packages/hub-api-client/tsconfig.json b/packages/hub-api-client/tsconfig.json deleted file mode 100644 index e125e90614..0000000000 --- a/packages/hub-api-client/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./tsconfig.src.json", - "compilerOptions": { - "composite": false, - "noEmit": true, - "disableSourceOfProjectReferenceRedirect": true, - "declaration": false, - "declarationMap": false, - "emitDeclarationOnly": false, - "tsBuildInfoFile": "tsconfig.tsbuildinfo", - "rootDir": "../.." - }, - "include": ["src"], - "exclude": [] -} diff --git a/packages/hub-api-client/tsconfig.src.json b/packages/hub-api-client/tsconfig.src.json deleted file mode 100644 index fc8724305f..0000000000 --- a/packages/hub-api-client/tsconfig.src.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src", "package.json", "src/**/*.json"], - "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], - "compilerOptions": { - "types": ["bun"], - "composite": true, - "emitDeclarationOnly": true, - "outDir": "dist", - "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - } -} diff --git a/packages/migration-runner/LICENSE b/packages/migration-runner/LICENSE deleted file mode 100644 index 173c3a21d0..0000000000 --- a/packages/migration-runner/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - - one line to give the library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 of the License. - - This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/migration-runner/README.md b/packages/migration-runner/README.md deleted file mode 100644 index 7dcb41ab60..0000000000 --- a/packages/migration-runner/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# @corbits/migration-runner - -Shared mechanics for the "transactional, self-contained" package migration -shape documented in [docs/package-migrations.md](../../docs/package-migrations.md): -schema and ledger bootstrap, a per-migration `sql.begin` transaction, and a -session-level Postgres advisory lock held around the whole run. - -## Why the lock - -Every caller opens its own single-connection (`max: 1`) client and calls -`applyPackageMigrations` at hub boot. With two hub replicas booting at once, -both would otherwise `SELECT` the ledger before either had inserted a row, -both would see "not yet applied," and the loser's ledger `INSERT` would -violate the ledger table's primary key and crash that replica's boot. -`applyPackageMigrations` takes `pg_advisory_lock(hashtext(ledgerTable))` -immediately after connecting and holds it — across every migration's own -transaction — until the run finishes, releasing it in a `finally` before the -connection closes. The loser blocks until the winner finishes, then re-checks -the ledger and finds every migration already applied. Postgres also releases -a session-level advisory lock automatically if the holding connection dies, -so a crashed replica never wedges the lock for the next boot. - -The lock key is `hashtext(ledgerTable)`, a 32-bit hash of the ledger table -name rather than the name itself, so two distinct table names could in -principle hash to the same key — two packages would then serialize their -boot-time migrations against each other instead of running in parallel, a -liveness cost (one waits its turn) and never a correctness one (each still -applies to its own schema and ledger). The eight current ledger tables -(`access_policy_migrations`, `bench_migrations`, -`inference_catalog_migrations`, `insights_migrations`, -`preferences_migrations`, `webhook_triggers_migrations`, -`routine_migrations`, `workflow_deploy_source_migrations`) do not collide — -verified pairwise against a live PostgreSQL 17.11 `hashtext()`. Confirm the -same before naming a ninth. - -## What it does not change - -Each migration still applies and records itself in its own transaction, and -a failure still wraps and rethrows as `` `${packageLabel} migration ${name} -failed: ...` `` with the original error as `cause` — this package only closes -the race around the check-and-insert, not the per-migration failure -semantics packages already relied on. - -## Usage - -```ts -import { applyPackageMigrations } from "@corbits/migration-runner"; - -export async function applyBenchMigrations(databaseUrl: string) { - return applyPackageMigrations({ - databaseUrl, - schema: "bench", - ledgerTable: "bench_migrations", - migrations: benchMigrations, - packageLabel: "bench", - }); -} -``` diff --git a/packages/migration-runner/package.json b/packages/migration-runner/package.json deleted file mode 100644 index f3a29994c9..0000000000 --- a/packages/migration-runner/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@corbits/migration-runner", - "version": "0.0.1", - "private": true, - "description": "Shared runner for package-owned Postgres migrations: schema/ledger bootstrap, per-migration transactional apply, and a session-level advisory lock around the whole run so concurrent hub replicas race-check the ledger safely instead of crashing on a duplicate insert.", - "license": "LGPL-2.1-only", - "type": "module", - "exports": { - ".": "./src/index.ts" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "@intx/log": "0.3.0", - "postgres": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - } -} diff --git a/packages/migration-runner/src/index.ts b/packages/migration-runner/src/index.ts deleted file mode 100644 index 91f4782c4e..0000000000 --- a/packages/migration-runner/src/index.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Shared mechanics for the "transactional, self-contained" package -// migration shape in docs/package-migrations.md: schema/ledger bootstrap, -// per-migration transactional apply, and a session-level advisory lock -// held around the whole run so concurrent hub replicas can't both see a -// migration as unapplied and race its ledger insert. See README.md for -// why the lock is session-level rather than per-transaction. -import { getLogger } from "@intx/log"; -import postgres from "postgres"; - -const log = getLogger(["migration-runner"]); - -export interface PackageMigration { - name: string; - sql: string; -} - -export interface ApplyPackageMigrationsReport { - applied: string[]; - alreadyApplied: string[]; -} - -export interface ApplyPackageMigrationsOptions { - databaseUrl: string; - schema: string; - ledgerTable: string; - migrations: readonly PackageMigration[]; - packageLabel: string; -} - -function quoteIdentifier(name: string): string { - return `"${name.replace(/"/g, '""')}"`; -} - -function quoteQualified(schema: string, name: string): string { - return `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`; -} - -export async function applyPackageMigrations( - options: ApplyPackageMigrationsOptions, -): Promise { - const { databaseUrl, schema, ledgerTable, migrations, packageLabel } = options; - const sql = postgres(databaseUrl, { max: 1, onnotice: () => undefined }); - let holdsLock = false; - try { - log.info`waiting for the ${packageLabel} migration lock (${ledgerTable})`; - await sql.unsafe(`SELECT pg_advisory_lock(hashtext($1)::bigint)`, [ledgerTable]); - holdsLock = true; - - await sql.unsafe(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(schema)}`); - await sql.unsafe( - `CREATE TABLE IF NOT EXISTS ${quoteQualified(schema, ledgerTable)} (` + - `name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`, - ); - - const applied: string[] = []; - const alreadyApplied: string[] = []; - - for (const migration of migrations) { - const existing = await sql.unsafe( - `SELECT 1 FROM ${quoteQualified(schema, ledgerTable)} WHERE name = $1`, - [migration.name], - ); - if (existing.length > 0) { - alreadyApplied.push(migration.name); - continue; - } - try { - await sql.begin(async (tx) => { - await tx.unsafe(migration.sql); - await tx.unsafe(`INSERT INTO ${quoteQualified(schema, ledgerTable)} (name) VALUES ($1)`, [ - migration.name, - ]); - }); - applied.push(migration.name); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - throw new Error(`${packageLabel} migration ${migration.name} failed: ${message}`, { - cause: err, - }); - } - } - - return { applied, alreadyApplied }; - } finally { - try { - if (holdsLock) { - await sql.unsafe(`SELECT pg_advisory_unlock(hashtext($1)::bigint)`, [ledgerTable]); - } - } finally { - await sql.end({ timeout: 5 }); - } - } -} diff --git a/packages/migration-runner/test/migration-runner.test.ts b/packages/migration-runner/test/migration-runner.test.ts deleted file mode 100644 index f61bb67c18..0000000000 --- a/packages/migration-runner/test/migration-runner.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -// DB-gated: skipped when no DATABASE_URL is reachable (a fresh checkout -// still runs the unit gates), mirroring the six package migration test -// suites this runner replaces the mechanics of. Runs against its own -// scratch database, never the developer's or the walking-skeleton suite's. -import { afterAll, beforeAll, expect, test } from "bun:test"; -import postgres from "postgres"; - -import { e2eDatabaseUrl } from "../../../test/database-url"; -import { applyPackageMigrations, type PackageMigration } from "../src/index"; -import { dbGate } from "../../../test/db-gate"; - -function scratchUrlFor(e2eUrl: string): string { - const url = new URL(e2eUrl); - const database = url.pathname.replace(/^\//, ""); - url.pathname = `/${database}_migration_runner_test`; - return url.toString(); -} - -const databaseUrl = e2eDatabaseUrl(); -const describeIfDb = dbGate(databaseUrl, import.meta.path); - -const SCHEMA = "migration_runner_test"; -const LEDGER_TABLE = "migration_runner_test_migrations"; - -const migrations: readonly PackageMigration[] = [ - { - name: "0001_widget", - sql: ` - CREATE TABLE IF NOT EXISTS "${SCHEMA}"."widget" ( - "id" text PRIMARY KEY - ); - `, - }, - { - name: "0002_widget_label", - sql: ` - ALTER TABLE "${SCHEMA}"."widget" - ADD COLUMN IF NOT EXISTS "label" text; - `, - }, -]; - -describeIfDb("applyPackageMigrations", () => { - const scratchUrl = scratchUrlFor(databaseUrl ?? "postgres://localhost:5432/unused"); - const scratchDatabase = new URL(scratchUrl).pathname.replace(/^\//, ""); - - async function withMaintenanceConnection(run: (sql: postgres.Sql) => Promise): Promise { - const maintenanceUrl = new URL(scratchUrl); - maintenanceUrl.pathname = "/postgres"; - const maintenance = postgres(maintenanceUrl.toString(), { - max: 1, - onnotice: () => undefined, - }); - try { - return await run(maintenance); - } finally { - await maintenance.end(); - } - } - - beforeAll(async () => { - await withMaintenanceConnection(async (maintenance) => { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - await maintenance.unsafe(`CREATE DATABASE "${scratchDatabase}"`); - }); - }, 20000); - - afterAll(async () => { - await withMaintenanceConnection(async (maintenance) => { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - }); - }, 20000); - - test("applies migrations into the package schema and is idempotent on a second run", async () => { - const first = await applyPackageMigrations({ - databaseUrl: scratchUrl, - schema: SCHEMA, - ledgerTable: LEDGER_TABLE, - migrations, - packageLabel: "migration-runner-test", - }); - expect(first.applied).toEqual(["0001_widget", "0002_widget_label"]); - expect(first.alreadyApplied).toEqual([]); - - const second = await applyPackageMigrations({ - databaseUrl: scratchUrl, - schema: SCHEMA, - ledgerTable: LEDGER_TABLE, - migrations, - packageLabel: "migration-runner-test", - }); - expect(second.applied).toEqual([]); - expect(second.alreadyApplied.sort()).toEqual(["0001_widget", "0002_widget_label"].sort()); - }); - - test("two replicas booting concurrently both complete without either crashing on a duplicate ledger insert", async () => { - const concurrentSchema = `${SCHEMA}_concurrent`; - const concurrentLedger = `${LEDGER_TABLE}_concurrent`; - const options = { - databaseUrl: scratchUrl, - schema: concurrentSchema, - ledgerTable: concurrentLedger, - migrations, - packageLabel: "migration-runner-concurrent-test", - }; - - const [first, second] = await Promise.all([ - applyPackageMigrations(options), - applyPackageMigrations(options), - ]); - - const appliedNames = [...first.applied, ...second.applied].sort(); - const alreadyAppliedNames = [...first.alreadyApplied, ...second.alreadyApplied].sort(); - - expect(new Set(appliedNames).size).toBe(appliedNames.length); - expect([...appliedNames, ...alreadyAppliedNames].sort()).toEqual( - [...migrations, ...migrations].map((migration) => migration.name).sort(), - ); - - const sql = postgres(scratchUrl, { max: 1, onnotice: () => undefined }); - try { - const ledgerRows = await sql.unsafe( - `SELECT name FROM "${concurrentSchema}"."${concurrentLedger}" ORDER BY name`, - ); - expect(ledgerRows.map((row) => String(row["name"]))).toEqual([ - "0001_widget", - "0002_widget_label", - ]); - } finally { - await sql.end(); - } - }); - - test("recovers the lock after the holding connection dies without releasing it", async () => { - const crashSchema = `${SCHEMA}_crash`; - const crashLedger = `${LEDGER_TABLE}_crash`; - - const holder = postgres(scratchUrl, { max: 1, onnotice: () => undefined }); - await holder.unsafe(`SELECT pg_advisory_lock(hashtext($1)::bigint)`, [crashLedger]); - await holder.end({ timeout: 0 }); - - const result = await applyPackageMigrations({ - databaseUrl: scratchUrl, - schema: crashSchema, - ledgerTable: crashLedger, - migrations, - packageLabel: "migration-runner-crash-test", - }); - - expect(result.applied).toEqual(["0001_widget", "0002_widget_label"]); - }, 10000); - - test("releases the lock when a migration fails, so the next run isn't blocked behind it", async () => { - const failSchema = `${SCHEMA}_fail`; - const failLedger = `${LEDGER_TABLE}_fail`; - const brokenMigrations: readonly PackageMigration[] = [ - { name: "0001_broken", sql: "SELECT this_column_does_not_exist" }, - ]; - - await expect( - applyPackageMigrations({ - databaseUrl: scratchUrl, - schema: failSchema, - ledgerTable: failLedger, - migrations: brokenMigrations, - packageLabel: "migration-runner-fail-test", - }), - ).rejects.toThrow(/migration-runner-fail-test migration 0001_broken failed/); - - // A second run reaching the same lock immediately (rather than hanging - // behind the first run's connection) proves the failed run's `finally` - // released it instead of leaving it held until the connection closed. - const result = await applyPackageMigrations({ - databaseUrl: scratchUrl, - schema: failSchema, - ledgerTable: failLedger, - migrations, - packageLabel: "migration-runner-fail-test", - }); - expect(result.applied).toEqual(["0001_widget", "0002_widget_label"]); - }, 10000); -}); diff --git a/packages/migration-runner/tsconfig.json b/packages/migration-runner/tsconfig.json deleted file mode 100644 index a8c2b9966d..0000000000 --- a/packages/migration-runner/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./tsconfig.src.json", - "compilerOptions": { - "composite": false, - "noEmit": true, - "disableSourceOfProjectReferenceRedirect": true, - "declaration": false, - "declarationMap": false, - "emitDeclarationOnly": false, - "tsBuildInfoFile": "tsconfig.tsbuildinfo", - "rootDir": "../.." - }, - "include": ["src", "test"], - "exclude": [] -} diff --git a/packages/migration-runner/tsconfig.src.json b/packages/migration-runner/tsconfig.src.json deleted file mode 100644 index fc8724305f..0000000000 --- a/packages/migration-runner/tsconfig.src.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src", "package.json", "src/**/*.json"], - "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], - "compilerOptions": { - "types": ["bun"], - "composite": true, - "emitDeclarationOnly": true, - "outDir": "dist", - "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - } -} diff --git a/packages/tool-registry-publish/README.md b/packages/tool-registry-publish/README.md index 8011b90d90..ac9cc70d49 100644 --- a/packages/tool-registry-publish/README.md +++ b/packages/tool-registry-publish/README.md @@ -59,11 +59,9 @@ for how a pin resolves through it). **Never imports:** -- `@corbits/hub-api-client` — the dependency direction runs the other - way (`@corbits/onboarding` calls `publishCorbitsToolsRegistry` via this - package's re-export), so - this package declares its own structurally-compatible `ApiCall` type - rather than importing `@corbits/hub-api-client`'s. +- Any hub API client package — a caller supplies its own `fetch`-shaped + `ApiCall`, so this package declares that type structurally rather than + importing it from anywhere. - `HubApiError` or any operator-facing error-wrapping convention — every failure here is a plain `Error`; wrapping it as an actionable `HubApiError` (problem + fix) is the calling setup step's job, not this diff --git a/packages/tool-registry-publish/src/publish.ts b/packages/tool-registry-publish/src/publish.ts index 74f8a95ace..130663454f 100644 --- a/packages/tool-registry-publish/src/publish.ts +++ b/packages/tool-registry-publish/src/publish.ts @@ -33,7 +33,7 @@ export function sha512Integrity(bytes: Uint8Array): string { return `sha512-${createHash("sha512").update(bytes).digest("base64")}`; } -/** Structurally compatible with `@corbits/hub-api-client`'s `ApiCall` — declared locally so this package never depends on it, which depends on this one. */ +/** A `fetch`-shaped call the caller supplies, declared locally so this package never depends on a hub API client package. */ export type ApiCall = ( method: string, path: string, diff --git a/packages/webhook-triggers/package.json b/packages/webhook-triggers/package.json index 291276b4d0..7631b376a6 100644 --- a/packages/webhook-triggers/package.json +++ b/packages/webhook-triggers/package.json @@ -16,7 +16,6 @@ "dependencies": { "@corbits/collections": "workspace:*", "@corbits/error-sink": "workspace:*", - "@corbits/migration-runner": "workspace:*", "@corbits/workflows": "workspace:*", "@intx/crypto": "0.3.0", "@intx/db": "workspace:*", diff --git a/packages/webhook-triggers/src/index.ts b/packages/webhook-triggers/src/index.ts index 7b5d40e90b..7b3138816d 100644 --- a/packages/webhook-triggers/src/index.ts +++ b/packages/webhook-triggers/src/index.ts @@ -1,9 +1,4 @@ -export { - applyWebhookTriggersMigrations, - webhookTriggersMigrations, - type ApplyWebhookTriggersMigrationsReport, - type WebhookTriggersMigration, -} from "./migrations"; +export { applyWebhookTriggersMigrations, webhookTriggersMigrationSql } from "./migrations"; export { webhookTrigger, type WebhookTriggerRow } from "./schema"; export { createDrizzleWebhookTriggerStore, diff --git a/packages/webhook-triggers/src/migrations.ts b/packages/webhook-triggers/src/migrations.ts index 7aa0498d10..0c4ac174e0 100644 --- a/packages/webhook-triggers/src/migrations.ts +++ b/packages/webhook-triggers/src/migrations.ts @@ -1,80 +1,59 @@ -// Package-owned migrations for @corbits/webhook-triggers's one -// product table. The platform's own schema is authored and applied by -// @intx/db (see scripts/db-setup.ts); this module is the package's -// half of the install story — mount + migrations is the entire -// install story, mirroring `@corbits/chat`'s `migrations.ts`. -// Bookkeeping is deliberately its own table, never the platform's -// drizzle journal, so this package's migration history stays -// extractable on its own. Mechanics (schema/ledger bootstrap, -// transactional apply, the advisory lock across concurrent hub -// replicas) live in @corbits/migration-runner — this file owns only -// the domain SQL. -import { - applyPackageMigrations, - type ApplyPackageMigrationsReport, - type PackageMigration, -} from "@corbits/migration-runner"; +// Package-owned migration for @corbits/webhook-triggers's product +// tables. The platform's own schema is authored and applied by +// @intx/db (see apps/hub/src/migrate.ts); this module is the +// package's half of the install story — mount + migration is the +// entire install story, mirroring `@corbits/cron`'s `schema.ts`. +// +// One idempotent SQL block, `CREATE SCHEMA IF NOT EXISTS` plus +// `CREATE TABLE IF NOT EXISTS`/`CREATE INDEX IF NOT EXISTS` +// throughout, so no ledger table is needed to know what has run. A +// session-level advisory lock (`pg_advisory_xact_lock`, released +// automatically at transaction end) held around the whole statement +// block keeps two hub replicas booting at once from racing each +// other's DDL. +import postgres from "postgres"; -export type WebhookTriggersMigration = PackageMigration; +export const webhookTriggersMigrationSql = ` + CREATE SCHEMA IF NOT EXISTS "webhook_triggers"; -/** - * Ordered, explicit migration set for the table declared in - * `./schema.ts`. Kept as literal SQL (rather than generated by - * drizzle at apply-time) so the applied statements are exactly what - * is reviewed here — no hidden codegen step between this file and the - * database. - */ -export const webhookTriggersMigrations: readonly WebhookTriggersMigration[] = [ - { - name: "0001_webhook_trigger", - sql: ` - CREATE TABLE IF NOT EXISTS "webhook_triggers"."webhook_trigger" ( - "id" text PRIMARY KEY, - "tenant_id" text NOT NULL REFERENCES "public"."tenant" ("id") ON DELETE CASCADE, - "name" text NOT NULL, - "workflow_definition_id" text NOT NULL, - "input_template" text NOT NULL, - "secret" text NOT NULL, - "enabled" boolean NOT NULL DEFAULT true, - "created_by" text NOT NULL REFERENCES "public"."principal" ("id") ON DELETE CASCADE, - "created_at" timestamptz NOT NULL DEFAULT now(), - "last_fired_at" timestamptz - ); - - CREATE INDEX IF NOT EXISTS "webhook_trigger_tenant_id_idx" - ON "webhook_triggers"."webhook_trigger" ("tenant_id"); - - CREATE UNIQUE INDEX IF NOT EXISTS "webhook_trigger_tenant_definition_name_unique" - ON "webhook_triggers"."webhook_trigger" ("tenant_id", "workflow_definition_id", "name"); - `, - }, -]; + CREATE TABLE IF NOT EXISTS "webhook_triggers"."webhook_trigger" ( + "id" text PRIMARY KEY, + "tenant_id" text NOT NULL REFERENCES "public"."tenant" ("id") ON DELETE CASCADE, + "name" text NOT NULL, + "workflow_definition_id" text NOT NULL, + "input_template" text NOT NULL, + "secret" text NOT NULL, + "enabled" boolean NOT NULL DEFAULT true, + "created_by" text NOT NULL REFERENCES "public"."principal" ("id") ON DELETE CASCADE, + "created_at" timestamptz NOT NULL DEFAULT now(), + "last_fired_at" timestamptz + ); -// Named distinctly from the platform's setup ledger and from any -// drizzle journal, so extracting `@corbits/webhook-triggers` out of -// this repo never has to disentangle its history from the platform's. -// Lives in the package's own `webhook_triggers` schema, like the -// table it owns. -const SCHEMA = "webhook_triggers"; -const LEDGER_TABLE = "webhook_triggers_migrations"; + CREATE INDEX IF NOT EXISTS "webhook_trigger_tenant_id_idx" + ON "webhook_triggers"."webhook_trigger" ("tenant_id"); -export type ApplyWebhookTriggersMigrationsReport = ApplyPackageMigrationsReport; + CREATE UNIQUE INDEX IF NOT EXISTS "webhook_trigger_tenant_definition_name_unique" + ON "webhook_triggers"."webhook_trigger" ("tenant_id", "workflow_definition_id", "name"); +`; /** - * Apply `webhookTriggersMigrations` against `databaseUrl`, - * idempotently: a migration already recorded in the ledger is - * skipped, never re-run. Failures are loud — the migration name and - * the underlying error are both surfaced, since a partial apply here - * would otherwise fail silently at the next `workbench setup`. + * Apply `webhookTriggersMigrationSql` against `databaseUrl`, idempotently + * (every statement is `IF NOT EXISTS`) and inside one advisory-locked + * transaction so concurrent hub replicas cannot race the same DDL. */ -export async function applyWebhookTriggersMigrations( - databaseUrl: string, -): Promise { - return applyPackageMigrations({ - databaseUrl, - schema: SCHEMA, - ledgerTable: LEDGER_TABLE, - migrations: webhookTriggersMigrations, - packageLabel: "@corbits/webhook-triggers", - }); +export async function applyWebhookTriggersMigrations(databaseUrl: string): Promise { + const sql = postgres(databaseUrl, { max: 1, onnotice: () => undefined }); + try { + await sql.begin(async (tx) => { + await tx.unsafe(`SELECT pg_advisory_xact_lock(hashtext('corbits_webhook_triggers'))`); + await tx.unsafe(webhookTriggersMigrationSql); + }); + } catch (error) { + throw new Error( + `@corbits/webhook-triggers migration failed: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } finally { + await sql.end({ timeout: 5 }); + } } diff --git a/packages/webhook-triggers/src/schema.ts b/packages/webhook-triggers/src/schema.ts index 5c18852314..7640ca2caf 100644 --- a/packages/webhook-triggers/src/schema.ts +++ b/packages/webhook-triggers/src/schema.ts @@ -1,7 +1,7 @@ // The product table `@corbits/webhook-triggers` owns: a trigger row // per external-webhook-to-workflow binding, living in this package's // own `webhook_triggers` Postgres schema, fully siloed from the -// platform's `public` schema — see docs/package-migrations.md. +// platform's `public` schema (see `./migrations.ts`). // // `tenant_id` and `created_by` (a real Interchange principal id — see // `management-routes.ts`'s `createdBy: principal.id`) are hard foreign diff --git a/packages/webhook-triggers/test/migrations.test.ts b/packages/webhook-triggers/test/migrations.test.ts index 20158d0beb..33dde881ea 100644 --- a/packages/webhook-triggers/test/migrations.test.ts +++ b/packages/webhook-triggers/test/migrations.test.ts @@ -1,9 +1,8 @@ // DB-gated: skipped when no DATABASE_URL is reachable (a fresh // checkout still runs the unit gates), and turned into a loud failure -// by CI=true so the suite can never silently vanish from CI — -// mirroring `@corbits/chat`'s own migrations test. Runs against its -// own scratch database, never the developer's or the walking-skeleton -// suite's, so a failure here can never corrupt either. +// by CI=true so the suite can never silently vanish from CI. +// Runs against its own scratch database, never the developer's or the +// walking-skeleton suite's, so a failure here can never corrupt either. import { afterAll, beforeAll, expect, test } from "bun:test"; import postgres from "postgres"; @@ -21,8 +20,6 @@ function scratchUrlFor(e2eUrl: string): string { const databaseUrl = e2eDatabaseUrl(); const describeIfDb = dbGate(databaseUrl, import.meta.path); -const migrationNames = ["0001_webhook_trigger"]; - describeIfDb("applyWebhookTriggersMigrations", () => { const scratchUrl = scratchUrlFor(databaseUrl ?? "postgres://localhost:5432/unused"); const scratchTarget = new URL(scratchUrl); @@ -57,13 +54,12 @@ describeIfDb("applyWebhookTriggersMigrations", () => { } }, 20000); - test("applies the trigger table into its own schema and is idempotent on a second run", async () => { - const first = await applyWebhookTriggersMigrations(scratchUrl); - expect(first.applied).toEqual(migrationNames); - - const second = await applyWebhookTriggersMigrations(scratchUrl); - expect(second.applied).toEqual([]); - expect(second.alreadyApplied.sort()).toEqual([...migrationNames].sort()); + test("applies the trigger table into its own schema and is idempotent on a second run, even concurrently", async () => { + await applyWebhookTriggersMigrations(scratchUrl); + await Promise.all([ + applyWebhookTriggersMigrations(scratchUrl), + applyWebhookTriggersMigrations(scratchUrl), + ]); const sql = postgres(scratchUrl, { max: 1, onnotice: () => undefined }); try { @@ -81,69 +77,5 @@ describeIfDb("applyWebhookTriggersMigrations", () => { } finally { await sql.end(); } - }); -}); - -// Separate database from the suite above: two replicas racing the same -// ledger must not collide with the idempotency test's own already-applied -// rows, and must start from a schema that has never seen this migration -// set before. -describeIfDb("applyWebhookTriggersMigrations concurrency", () => { - const scratchUrl = scratchUrlFor(databaseUrl ?? "postgres://localhost:5432/unused").replace( - "_webhook_triggers_migrations_test", - "_webhook_triggers_migrations_concurrent_test", - ); - const scratchDatabase = new URL(scratchUrl).pathname.replace(/^\//, ""); - - beforeAll(async () => { - const maintenanceUrl = new URL(scratchUrl); - maintenanceUrl.pathname = "/postgres"; - const maintenance = postgres(maintenanceUrl.toString(), { - max: 1, - onnotice: () => undefined, - }); - try { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - await maintenance.unsafe(`CREATE DATABASE "${scratchDatabase}"`); - } finally { - await maintenance.end(); - } }, 20000); - - afterAll(async () => { - const maintenanceUrl = new URL(scratchUrl); - maintenanceUrl.pathname = "/postgres"; - const maintenance = postgres(maintenanceUrl.toString(), { - max: 1, - onnotice: () => undefined, - }); - try { - await maintenance.unsafe(`DROP DATABASE IF EXISTS "${scratchDatabase}"`); - } finally { - await maintenance.end(); - } - }, 20000); - - test("two replicas booting concurrently both complete without either crashing on a duplicate ledger insert", async () => { - const [first, second] = await Promise.all([ - applyWebhookTriggersMigrations(scratchUrl), - applyWebhookTriggersMigrations(scratchUrl), - ]); - - const appliedNames = [...first.applied, ...second.applied].sort(); - expect(new Set(appliedNames).size).toBe(appliedNames.length); - expect([...appliedNames, ...first.alreadyApplied, ...second.alreadyApplied].sort()).toEqual( - migrationNames.flatMap((name) => [name, name]).sort(), - ); - - const sql = postgres(scratchUrl, { max: 1, onnotice: () => undefined }); - try { - const ledgerRows = await sql.unsafe( - `SELECT name FROM "webhook_triggers"."webhook_triggers_migrations" ORDER BY name`, - ); - expect(ledgerRows.map((row) => String(row["name"]))).toEqual(migrationNames); - } finally { - await sql.end(); - } - }, 10000); }); diff --git a/scripts/db-setup.ts b/scripts/db-setup.ts index 794e87c70b..754219185b 100644 --- a/scripts/db-setup.ts +++ b/scripts/db-setup.ts @@ -1,121 +1,24 @@ -// Database bootstrap for the platform schema plus any installed -// package's own migrations. The hub's schema is defined entirely by -// @intx/db's shipped migrations; this repository authors no SQL for -// the platform itself. Installed packages may ship their own product -// tables, though, and this script -// applies each installed package's migration set right after the -// platform's, as an explicit literal list below. This script makes -// the database in DATABASE_URL runnable: it creates the database if -// it is missing, applies the platform migrations (which include the -// better-auth tables) into the target schema, records exactly which -// migration files it applied so a re-run can tell "already done" from -// "done by something else", then applies the installed packages' -// migrations on top — and says so out loud either way. +// Database bootstrap: makes the database in DATABASE_URL runnable by +// creating it if it does not exist, then handing off to the hub's own +// `migrateHub` (apps/hub/src/migrate.ts) to apply the platform schema +// plus every mounted Corbits package's migration — the hub is the one +// process that knows what it mounts, so it is the one place that +// migrates. This script makes an empty Postgres server usable; it +// authors no SQL of its own. // -// The platform dependencies are resolved through apps/hub on purpose: -// the schema this script creates is the hub's schema, so it must be -// built with exactly the @intx/db version the hub runs, not a -// separately-declared copy that could drift. -// -// Exported surface (consumed by the dev bootstrap, the CLI's setup -// verb, and the test harnesses): +// Exported surface (consumed by the CLI's setup verb and the test +// harnesses): // // setupDatabase(databaseUrl, { schema? }) -> DbSetupReport // resetSchema(databaseUrl, { schema? }) -> void // // Run directly: `bun scripts/db-setup.ts [--reset]` (reads DATABASE_URL). -import path from "node:path"; -import { readdir } from "node:fs/promises"; - -import { applyWebhookTriggersMigrations } from "../packages/webhook-triggers/src/migrations"; -import { applyCronMigrations } from "../packages/cron/src/migrations"; -import { createMailboxDb, runMailboxMigrations } from "@corbits/mailbox"; - -/** - * Apply `@corbits/mailbox`'s own migrations against `databaseUrl`. The - * package keeps its own ledger inside the `mailbox` schema; this wrapper - * only opens a short-lived handle, runs the migrator, and closes it. - */ -async function applyMailboxMigrations(databaseUrl: string): Promise<{ applied: string[] }> { - const { db, close } = createMailboxDb(databaseUrl); - try { - await runMailboxMigrations(db); - return { applied: ["mailbox"] }; - } finally { - await close(); - } -} - -const repoRoot = path.resolve(import.meta.dir, ".."); -const HUB_DIR = path.join(repoRoot, "apps", "hub"); - -/** - * Installed packages that ship their own product-table migrations, - * applied after the platform's. Explicit and literal on purpose: no - * discovery magic, no globbing for migrations. See - * docs/package-migrations.md for the convention each package's - * migration runner follows (literal SQL, package-owned ledger, - * transactional apply) and which shape to pick for a new package. - */ -const INSTALLED_PACKAGE_MIGRATIONS: readonly { - name: string; - apply: (databaseUrl: string) => Promise<{ applied: string[] }>; -}[] = [ - { name: "@corbits/webhook-triggers", apply: applyWebhookTriggersMigrations }, - { name: "@corbits/mailbox", apply: applyMailboxMigrations }, - { name: "@corbits/cron", apply: applyCronMigrations }, -]; - -/** - * Apply every installed package's migration set, in the explicit - * order listed above, right after the platform's own migrations. Each - * package owns its own idempotence and bookkeeping (see - * each package's own runner); this only sequences them and reports what ran. - */ -async function applyInstalledPackageMigrations(databaseUrl: string): Promise { - for (const { name, apply } of INSTALLED_PACKAGE_MIGRATIONS) { - try { - const { applied } = await apply(databaseUrl); - if (applied.length > 0) { - console.log( - `db-setup: applied ${applied.length} migration(s) for ${name}: ` + applied.join(", "), - ); - } - } catch (error) { - throw new Error( - `db-setup: failed applying migrations for installed package ${name}: ` + - `${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); - } - } - - // the one-time duplicate-grant cleanup ran its era - // (the repo_review_lease now prevents new duplicates at write time), - // so db-setup no longer performs it: setup applies migrations only, - // and grant state stays on the native grant routes. - - await dropRoutinesSchemaAfterDigestHandoff(databaseUrl); - await dropSchemaIfPresent(databaseUrl, "run_key_history"); - await dropSchemaIfPresent(databaseUrl, "preferences"); - await dropSchemaIfPresent(databaseUrl, "bench"); - await dropSchemaIfPresent(databaseUrl, "insights"); -} - -// --- hub-resolved platform dependencies ------------------------------ - -// Minimal local views of the two hub dependencies this script uses. -// They are resolved out of the hub's dependency tree at runtime, so -// the shapes are pinned here instead of imported. -interface IntxDbMigrate { - runMigrations(config: unknown, options: { schema: string }): Promise; - dropSchema(config: unknown, options: { schema: string }): Promise; -} +import { createDB, dropSchema as dropIntxSchema } from "@intx/db"; interface SqlClient { unsafe(query: string, params?: unknown[]): Promise[]>; - end(): Promise; + end(options?: { timeout: number }): Promise; } type PostgresFactory = (options: { @@ -128,84 +31,35 @@ type PostgresFactory = (options: { onnotice: () => undefined; }) => SqlClient; -function resolveHubDependency(specifier: string): string { - try { - return Bun.resolveSync(specifier, HUB_DIR); - } catch { - throw new Error( - [ - `Cannot resolve ${specifier} from ${HUB_DIR}.`, - "The hub's dependencies are not installed. Run:", - "", - " bun install", - ].join("\n"), - ); - } -} - -async function loadIntxDb(): Promise { - const resolved = resolveHubDependency("@intx/db"); - const loaded = (await import(resolved)) as Partial; - if (typeof loaded.runMigrations !== "function" || typeof loaded.dropSchema !== "function") { - throw new Error( - [ - `@intx/db at ${resolved} does not export runMigrations/dropSchema;`, - "the installed version does not match what scripts/db-setup.ts", - "expects. Reinstall dependencies and re-run:", - "", - " bun install", - ].join("\n"), - ); - } - return { runMigrations: loaded.runMigrations, dropSchema: loaded.dropSchema }; -} - -export async function loadPostgres(): Promise { - const resolved = resolveHubDependency("postgres"); +// Resolved dynamically rather than imported statically: this script's +// own tsconfig has no "bun" condition, which is what lets `postgres` +// and apps/hub's own source resolve under the hub's tsconfig. Loading +// both through Bun's own runtime resolver instead keeps this script +// out of that cross-project typecheck entirely. +async function loadPostgres(): Promise { + const resolved = Bun.resolveSync("postgres", import.meta.dir); const loaded = (await import(resolved)) as { default: PostgresFactory }; return loaded.default; } -/** - * The migration files @intx/db ships, sorted in apply order. The - * package pins them at `/migrations`, a sibling of the entry - * module's directory (`src/index.ts` in the vendored workspace, - * `dist/index.js` when published), so `/../migrations` is - * the same resolution @intx/db's own runMigrations performs. - */ -async function listShippedMigrations(): Promise { - const entry = resolveHubDependency("@intx/db"); - const dir = path.resolve(path.dirname(entry), "..", "migrations"); - let files: string[]; - try { - files = await readdir(dir); - } catch { - throw new Error( - [ - `@intx/db's migrations directory is missing at ${dir}.`, - "Reinstall dependencies and re-run:", - "", - " bun install", - ].join("\n"), - ); - } - const sql = files.filter((f) => f.endsWith(".sql")).sort(); - if (sql.length === 0) { - throw new Error( - [ - `@intx/db ships no .sql migrations in ${dir}; the installed package`, - "is broken. Reinstall dependencies and re-run:", - "", - " bun install", - ].join("\n"), - ); - } - return sql; +interface HubMigrateConfig { + host: string; + port: number; + user: string; + password: string; + database: string; + schema?: string; } -// --- connection plumbing --------------------------------------------- +async function loadMigrateHub(): Promise<(config: HubMigrateConfig, db: unknown) => Promise> { + const resolved = Bun.resolveSync("../apps/hub/src/migrate.ts", import.meta.dir); + const loaded = (await import(resolved)) as { + migrateHub: (config: HubMigrateConfig, db: unknown) => Promise; + }; + return loaded.migrateHub; +} -interface DbTarget { +export interface DbTarget { host: string; port: number; user: string; @@ -248,7 +102,8 @@ export function dbTargetFromUrl(databaseUrl: string): DbTarget { }; } -async function connect(postgres: PostgresFactory, target: DbTarget): Promise { +async function connect(target: DbTarget): Promise { + const postgres = await loadPostgres(); return postgres({ host: target.host, port: target.port, @@ -279,10 +134,9 @@ function quoteIdentifier(name: string): string { * named, mirroring the dev bootstrap's guidance. */ async function ensureDatabase( - postgres: PostgresFactory, target: DbTarget, ): Promise<{ sql: SqlClient; createdDatabase: boolean }> { - const sql = await connect(postgres, target); + const sql = await connect(target); try { await sql.unsafe("SELECT 1"); return { sql, createdDatabase: false }; @@ -304,10 +158,7 @@ async function ensureDatabase( } // 3D000: the database does not exist. Create it from the maintenance // database, then reconnect to it. - const maintenance = await connect(postgres, { - ...target, - database: "postgres", - }); + const maintenance = await connect({ ...target, database: "postgres" }); try { await maintenance.unsafe(`CREATE DATABASE ${quoteIdentifier(target.database)}`); } catch (error) { @@ -321,96 +172,9 @@ async function ensureDatabase( } finally { await maintenance.end(); } - return { sql: await connect(postgres, target), createdDatabase: true }; -} - -// --- setup state inspection ------------------------------------------ - -// Ledger of migration files this script has applied into a schema. -// It lives inside the target schema so dropping the schema drops the -// ledger with it, and its presence distinguishes "set up by db-setup" -// from "tables created by something else". -const LEDGER_TABLE = "workbench_setup_migration"; - -// A table from @intx/db's first migration; its presence without the -// ledger means the schema was populated by something other than this -// script. -const SENTINEL_TABLE = "user"; - -async function tableExists(sql: SqlClient, schema: string, table: string): Promise { - const rows = await sql.unsafe( - "SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2", - [schema, table], - ); - return rows.length > 0; -} - -/** - * One-shot: if a leftover `routines` schema is still present, enable the - * authored workbench-digest definition for tenants whose digest routine - * was on, then drop the schema. Absent schema is a no-op. Safe to re-run. - * - * `updated_at = now()` is load-bearing: seed treats `createdAt === updatedAt` - * as pristine and PUTs `stopped`. Copying enablement without bumping - * `updated_at` would look untouched and get re-archived on the next seed. - */ -export const DIGEST_HANDOFF_SQL = `UPDATE workflow_definition wd SET status = CASE WHEN r.enabled THEN 'deployed' ELSE 'stopped' END, updated_at = now() FROM routines.routine r WHERE r.preset_key = 'workbench-digest' AND wd.name = 'workbench-digest' AND wd.tenant_id = r.tenant_id AND wd.origin = 'authored'`; - -async function dropRoutinesSchemaAfterDigestHandoff(databaseUrl: string): Promise { - const postgres = await loadPostgres(); - const target = dbTargetFromUrl(databaseUrl); - const sql = await connect(postgres, target); - try { - const existing = await sql.unsafe( - "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1", - ["routines"], - ); - if (existing.length === 0) return; - await sql.unsafe(DIGEST_HANDOFF_SQL); - await sql.unsafe("DROP SCHEMA IF EXISTS routines CASCADE"); - console.log("db-setup: dropped routines schema after digest enablement handoff"); - } finally { - await sql.end(); - } -} - -/** - * One-shot, forward-only: `@corbits/run-key-history` and - * `@corbits/preferences` had zero web callers on their mounts — - * a diagnostics-only listener and a client that was built but never - * imported — so both packages, their mounts, and their schemas are gone. - * `bench` joins them for the same reason. `insights` (also - *) joins them too, for a different reason: the hub mounts nothing - * Workbench-specific, so its usage/latency writers and read routes are - * gone — Insights UI now reads stock observability/workflow routes - * client-side instead. Absent schema is a no-op; safe to re-run. - */ -async function dropSchemaIfPresent(databaseUrl: string, schema: string): Promise { - const postgres = await loadPostgres(); - const target = dbTargetFromUrl(databaseUrl); - const sql = await connect(postgres, target); - try { - const existing = await sql.unsafe( - "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1", - [schema], - ); - if (existing.length === 0) return; - await sql.unsafe(`DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`); - console.log(`db-setup: dropped ${schema} schema (dead mount)`); - } finally { - await sql.end(); - } + return { sql: await connect(target), createdDatabase: true }; } -async function appliedMigrations(sql: SqlClient, schema: string): Promise { - const rows = await sql.unsafe( - `SELECT filename FROM ${quoteIdentifier(schema)}.${quoteIdentifier(LEDGER_TABLE)} ORDER BY filename`, - ); - return rows.map((row) => String(row["filename"])); -} - -// --- public surface --------------------------------------------------- - export interface DbSetupOptions { /** Target Postgres schema; defaults to "public", which is where the hub connects. */ schema?: string; @@ -423,21 +187,13 @@ export interface DbSetupReport { schema: string; /** Whether the database itself had to be created. */ createdDatabase: boolean; - /** "migrated" when this call applied migrations; "unchanged" when the schema was already current. */ - action: "migrated" | "unchanged"; - /** Number of migration files now applied in the schema. */ - migrations: number; } /** - * Make the database in `databaseUrl` runnable: create the database if - * missing, apply @intx/db's shipped migrations (platform tables plus - * the better-auth tables) into the target schema, and record what was - * applied. Idempotent: a schema this script already set up at the same - * migration level reports "unchanged" and touches nothing. Any state - * it cannot vouch for — tables without its ledger, or a ledger that - * disagrees with the shipped migration list — fails loudly and names - * the fix instead of guessing. + * Make the database in `databaseUrl` runnable: create it if missing, + * then apply every migration the hub itself applies at boot + * (`migrateHub`). Every migration is idempotent, so re-running this is + * always safe and reports the same thing either way. */ export async function setupDatabase( databaseUrl: string, @@ -445,107 +201,29 @@ export async function setupDatabase( ): Promise { const schema = options.schema ?? "public"; const target = dbTargetFromUrl(databaseUrl); - const [postgres, intxDb, shipped] = await Promise.all([ - loadPostgres(), - loadIntxDb(), - listShippedMigrations(), - ]); - - const { sql, createdDatabase } = await ensureDatabase(postgres, target); - try { - const hasLedger = await tableExists(sql, schema, LEDGER_TABLE); - if (hasLedger) { - const applied = await appliedMigrations(sql, schema); - const same = - applied.length === shipped.length && applied.every((file, i) => file === shipped[i]); - if (same) { - await applyInstalledPackageMigrations(databaseUrl); - return { - database: target.database, - schema, - createdDatabase, - action: "unchanged", - migrations: applied.length, - }; - } - throw new Error( - [ - `Schema ${JSON.stringify(schema)} in database ${JSON.stringify(target.database)} ` + - `was set up with a different @intx/db migration set ` + - `(${applied.length} applied, ${shipped.length} shipped).`, - "The platform migrations replay from scratch; they cannot be applied", - "incrementally on top of an older set. Reset the schema and re-run:", - "", - " bun scripts/db-setup.ts --reset", - ].join("\n"), - ); - } + const { sql, createdDatabase } = await ensureDatabase(target); + await sql.end(); - if (await tableExists(sql, schema, SENTINEL_TABLE)) { - throw new Error( - [ - `Schema ${JSON.stringify(schema)} in database ${JSON.stringify(target.database)} ` + - "already contains platform tables but no db-setup ledger, so this", - "script cannot vouch for its state. Reset the schema and re-run:", - "", - " bun scripts/db-setup.ts --reset", - ].join("\n"), - ); - } + const config = { ...target, schema }; + const { db } = createDB(config); + const migrateHub = await loadMigrateHub(); + await migrateHub(config, db); - await intxDb.runMigrations(target, { schema }); - await sql.unsafe( - `CREATE TABLE ${quoteIdentifier(schema)}.${quoteIdentifier(LEDGER_TABLE)} (` + - `filename text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())`, - ); - for (const file of shipped) { - await sql.unsafe( - `INSERT INTO ${quoteIdentifier(schema)}.${quoteIdentifier(LEDGER_TABLE)} (filename) VALUES ($1)`, - [file], - ); - } - await applyInstalledPackageMigrations(databaseUrl); - return { - database: target.database, - schema, - createdDatabase, - action: "migrated", - migrations: shipped.length, - }; - } finally { - await sql.end(); - } + return { database: target.database, schema, createdDatabase }; } -// Every installed package that owns a named schema of its own (see -// docs/package-migrations.md) rather than the platform's `public`, so a -// reset that only drops `schema` would leave those tables behind: the next -// `bun run dev`/`workbench reset` would boot against fresh `tenant`/ -// `principal` rows while e.g. `mailbox.principal_mail` or -// `notify.notify_dispatch` still held the old ones (and, once the old FKs -// are cascaded away, orphaned rows no package's `CREATE TABLE IF NOT -// EXISTS` migration would ever revisit). Always dropped alongside the -// target schema so a reset is a true clean slate for every installed +// Every installed package that owns a named schema of its own rather +// than the platform's `public`, so a reset that only drops `schema` +// would leave those tables behind. Always dropped alongside the target +// schema so a reset is a true clean slate for every installed // package's tables, not only the platform's. -const PACKAGE_SCHEMAS = [ - "mailbox", - "routines", - "insights", - "webhook_triggers", - "access_policy", - "bench", - "preferences", - "skills", - "tasks", - "agent_directory", -] as const; +const PACKAGE_SCHEMAS = ["mailbox", "cron", "webhook_triggers", "memory"] as const; /** - * Drop the target schema and everything in it (platform tables, auth - * tables, and the setup ledger), plus every installed package's own named - * schema. A missing database is a no-op: there is nothing to drop. Pair - * with setupDatabase for a from-scratch rebuild; the e2e harness does - * exactly that. + * Drop the target schema and everything in it (platform tables and + * auth tables), plus every installed package's own named schema. A + * missing database is a no-op: there is nothing to drop. Pair with + * setupDatabase for a from-scratch rebuild. */ export async function resetSchema( databaseUrl: string, @@ -553,8 +231,7 @@ export async function resetSchema( ): Promise { const schema = options.schema ?? "public"; const target = dbTargetFromUrl(databaseUrl); - const [postgres, intxDb] = await Promise.all([loadPostgres(), loadIntxDb()]); - const probe = await connect(postgres, target); + const probe = await connect(target); try { await probe.unsafe("SELECT 1"); } catch (error) { @@ -573,9 +250,9 @@ export async function resetSchema( ); } await probe.end(); - await intxDb.dropSchema(target, { schema }); + await dropIntxSchema(target, { schema }); for (const packageSchema of PACKAGE_SCHEMAS) { - await intxDb.dropSchema(target, { schema: packageSchema }); + await dropIntxSchema(target, { schema: packageSchema }); } } @@ -586,18 +263,10 @@ function describeReport(report: DbSetupReport): string { if (report.createdDatabase) { lines.push(`created database ${JSON.stringify(report.database)}`); } - if (report.action === "migrated") { - lines.push( - `applied ${report.migrations} platform migrations into schema ` + - `${JSON.stringify(report.schema)} of database ${JSON.stringify(report.database)}`, - ); - } else { - lines.push( - `schema ${JSON.stringify(report.schema)} of database ` + - `${JSON.stringify(report.database)} is already migrated ` + - `(${report.migrations} migrations); nothing to do`, - ); - } + lines.push( + `applied migrations into schema ${JSON.stringify(report.schema)} of database ` + + `${JSON.stringify(report.database)}`, + ); return lines.map((line) => `db-setup: ${line}`).join("\n"); } diff --git a/scripts/dev.ts b/scripts/dev.ts index 65efdd8a1b..2cca62d4df 100644 --- a/scripts/dev.ts +++ b/scripts/dev.ts @@ -276,14 +276,7 @@ async function requireDatabaseSetUp(config: DevConfig): Promise { if (report.createdDatabase) { console.log(`[dev] created database ${JSON.stringify(report.database)}`); } - if (report.action === "migrated") { - console.log( - `[dev] applied ${report.migrations} platform migrations to database ` + - `${JSON.stringify(report.database)}`, - ); - } else { - console.log(`[dev] database ${JSON.stringify(report.database)} schema is current`); - } + console.log(`[dev] database ${JSON.stringify(report.database)} schema is current`); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } diff --git a/scripts/publish-tools.ts b/scripts/publish-tools.ts deleted file mode 100644 index b0616339d6..0000000000 --- a/scripts/publish-tools.ts +++ /dev/null @@ -1,137 +0,0 @@ -// `bun run publish-tools` — packs every `@corbits/*-tools` package and -// publishes it into an existing tenant's `corbits-tools` package-registry -// asset over the hub's native REST routes. Sign-in only, never sign-up: -// the tenant must already exist (the genesis signup or `bun run dev`'s -// seeded admin created it); this command only installs the registry -// onto it. No daemon, no new route, no new table. -// -// Environment: HUB_ADMIN_EMAIL and HUB_ADMIN_PASSWORD name the -// signing-in admin; `--tenant ` picks the target tenant -// (defaults to the admin's only membership when exactly one). -import { type } from "arktype"; -import { PrincipalSummary, paginatedSchema } from "@intx/types"; -// Relative imports, the same convention e2e uses: the root -// package.json does not depend on these workspace packages, only the -// hub-facing products do. -import { - createHubAPI, - parseAs, - signIn, - type ApiCall, -} from "../packages/hub-api-client/src/index.ts"; -import { - publishCorbitsToolsRegistry, - type PackedTarball, - type PublishCorbitsToolsRegistryResult, -} from "../packages/tool-registry-publish/src/index.ts"; - -export type PublishToolsArgs = { - hubUrl: string; - email: string; - password: string; - /** Target tenant id or slug; required when the admin belongs to more than one tenant. */ - tenant?: string; - log?: (line: string) => void; - /** Test seams, mirroring `publishCorbitsToolsRegistry`'s. */ - api?: ApiCall; - fetchImpl?: (input: string, init: RequestInit) => Promise; - checkFreshness?: () => Promise; - packageDirs?: readonly string[]; - pack?: (packageDir: string) => Promise; -}; - -async function resolveTenantId( - api: ApiCall, - cookies: string[], - tenant: string | undefined, -): Promise { - const response = await api("GET", "/api/me/principals", undefined, cookies); - const summary = parseAs(paginatedSchema(PrincipalSummary), response.data, "principals response"); - if (tenant !== undefined) { - const named = summary.data.find( - (principal) => - principal.tenantId === tenant || - principal.tenantSlug === tenant || - principal.tenantName === tenant, - ); - if (named === undefined) { - throw new Error( - `publish-tools: no tenant matching "${tenant}" in the signed-in admin's memberships (${summary.data.map((principal) => principal.tenantSlug).join(", ")})`, - ); - } - return named.tenantId; - } - if (summary.data.length !== 1) { - throw new Error( - `publish-tools: --tenant is required when the admin belongs to ${summary.data.length} tenants (${summary.data.map((principal) => principal.tenantSlug).join(", ")})`, - ); - } - const only = summary.data[0]; - if (only === undefined) { - throw new Error( - "publish-tools: the signed-in admin belongs to no tenant; sign up or seed an account first", - ); - } - return only.tenantId; -} - -export async function runPublishTools( - args: PublishToolsArgs, -): Promise { - const log = args.log ?? ((): void => undefined); - const api = args.api ?? createHubAPI(args.hubUrl); - const session = await signIn(api, { - email: args.email, - password: args.password, - }); - log(`signed in as ${args.email}`); - const tenantId = await resolveTenantId(api, session.cookies, args.tenant); - log(`publishing the corbits-tools registry onto tenant ${tenantId}`); - return publishCorbitsToolsRegistry({ - api, - cookies: session.cookies, - hubUrl: args.hubUrl, - tenantId, - log, - ...(args.checkFreshness !== undefined ? { checkFreshness: args.checkFreshness } : {}), - ...(args.fetchImpl !== undefined ? { fetchImpl: args.fetchImpl } : {}), - ...(args.packageDirs !== undefined ? { packageDirs: args.packageDirs } : {}), - ...(args.pack !== undefined ? { pack: args.pack } : {}), - }); -} - -const Args = type({ - "tenant?": "string", -}); - -async function main(): Promise { - const email = process.env["HUB_ADMIN_EMAIL"]; - const password = process.env["HUB_ADMIN_PASSWORD"]; - if (email === undefined || email === "" || password === undefined || password === "") { - console.error( - "publish-tools: set HUB_ADMIN_EMAIL and HUB_ADMIN_PASSWORD to an existing admin account, and start the stack with `bun run dev` first.", - ); - process.exit(1); - } - const raw = process.argv.slice(2); - const tenantIndex = raw.indexOf("--tenant"); - const tenant = tenantIndex >= 0 ? (raw[tenantIndex + 1] ?? undefined) : undefined; - const parsed = Args({ tenant }); - if (parsed instanceof type.errors) { - console.error(`publish-tools: ${parsed.summary}`); - process.exit(1); - } - const hubUrl = process.env["BASE_URL"] ?? "http://localhost:3000"; - const result = await runPublishTools({ - hubUrl, - email, - password, - ...(parsed.tenant !== undefined ? { tenant: parsed.tenant } : {}), - log: (line) => console.log(`[publish-tools] ${line}`), - }); - console.log(`[publish-tools] done: ${result.summaries.length} tarball(s) uploaded`); -} - -if (import.meta.main) { - main(); -} diff --git a/skills/skills/src/skill-md.ts b/skills/skills/src/skill-md.ts index 04a18d0445..d68091677c 100644 --- a/skills/skills/src/skill-md.ts +++ b/skills/skills/src/skill-md.ts @@ -115,8 +115,7 @@ export function buildSkillMd(input: { * SKILL.md lacks `scope`, and no seed, fixture, template, or * provisioning path plants a tenant-visible row (verified), so * there is nothing that would silently narrow. Pre-GA cutovers are not - * migrated — dev databases reseed via `bun run reset` (ruling; - * see docs/package-migrations.md). */ + * migrated — dev databases reseed via `bun run reset` (ruling). */ export function parseSkillMd(text_: string): ParsedSkillMd { const lines = text_.split(/\r?\n/); if (lines[0] !== FRONTMATTER_DELIMITER) { diff --git a/tsconfig.build.json b/tsconfig.build.json index bc40745724..f86b8eda46 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -28,15 +28,9 @@ { "path": "./packages/error-sink/tsconfig.src.json" }, - { - "path": "./packages/hub-api-client/tsconfig.src.json" - }, { "path": "./packages/inference-catalog/tsconfig.src.json" }, - { - "path": "./packages/migration-runner/tsconfig.src.json" - }, { "path": "./packages/tool-registry-publish/tsconfig.src.json" },