import { afterEach, describe, expect, it, vi } from "vitest"; import { createRegisterBuildParamPlugin, createRegisterExtensionPlugin } from "@webiny/handler"; import { BuildParam } from "@webiny/api-core/features/buildParams/abstractions.js"; import { Extension as TenantManagerExtension } from "@webiny/tenant-manager/api/Extension.js"; import { createMultiStorageServer, type MultiStorageServer } from "./createMultiStorageServer.js"; import { createStorageProbe, type ScopeRun } from "./storageProbe.js"; import { admin, INSTALL, LOGIN } from "./installAndLogIn.js"; import { listTables, rowsByTenant, tablesWithTenant } from "./storageRows.js"; /** * The Tenant Manager on a server with root on SQLite (the default storage) and two extra PGlite * storages, one of them retired: root picks a new tenant's storage (`perTenantStorage`), install * writes it to the core tenant's `settings.storage` before any installer runs, and it can't change * once installed. */ const PG = "local-pg"; const RETIRED = "old-pg"; const DOWN = "down-pg"; const createFeatureFlags = (perTenantStorage: boolean) => { class FeatureFlagsBuildParam implements BuildParam.Interface { key = "FeatureFlags"; value = { perTenantStorage }; } const implementation = BuildParam.createImplementation({ implementation: FeatureFlagsBuildParam, dependencies: [] }); return createRegisterBuildParamPlugin(ctx => { ctx.container.register(implementation); }); }; const tenantManager = createRegisterExtensionPlugin(({ container }) => { TenantManagerExtension.register(container); }); const CREATE_TENANT = /* GraphQL */ ` mutation CreateTenant($input: CreateTenantInput!) { tenantManager { createTenant(input: $input) { data error { code message } } } } `; const UPDATE_TENANT = /* GraphQL */ ` mutation UpdateTenant($tenantId: ID!, $input: UpdateTenantInput!) { tenantManager { updateTenant(tenantId: $tenantId, input: $input) { data error { code message } } } } `; const INSTALL_TENANT = /* GraphQL */ ` mutation InstallTenant($tenantId: ID!) { tenantManager { installTenant(tenantId: $tenantId) { data error { code message } } } } `; const LIST_TENANTS = /* GraphQL */ ` query ListTenants { tenantManager { listTenants(descendants: true) { data { id values } error { code message } } } } `; const LIST_STORAGES = /* GraphQL */ ` query ListStorages { tenantManager { listStorages { data { storages { id label type isDefault retired } } error { code message } } } } `; const GET_TENANT_MODEL = /* GraphQL */ ` query GetTenantModel { getContentModel(modelId: "wbyTenant") { data { fields { fieldId settings predefinedValues { values { value } } } } error { code message } } } `; interface Setup { server: MultiStorageServer; token: string; } const start = async (perTenantStorage: boolean): Promise => { const probe = createStorageProbe(); const server = await createMultiStorageServer({ defaultStorage: "sqlite", extraStorages: [PG, RETIRED, DOWN], retired: [RETIRED], extensions: [probe.extension, tenantManager, createFeatureFlags(perTenantStorage)] }); const install = await server.graphql(INSTALL, { installationInput: [{ app: "SelfHostedAuth", data: admin }] }); expect(install.body.data.system.installSystem).toEqual({ data: true, error: null }); const login = await server.graphql(LOGIN, { email: admin.email, password: admin.password }); return { server, token: login.body.data.selfHostedAuthLogin.data.token }; }; describe("api-composition-standalone-sql — the Tenant Manager picks a tenant's storage", () => { let setup: Setup; const send = async ( query: string, variables: Record = {}, tenant = "root" ) => { const result = await setup.server.graphql(query, variables, { token: setup.token, tenant }); expect(result.body.errors).toBeUndefined(); return result.body.data; }; const createTenant = async (input: Record, as = "root") => { const data = await send(CREATE_TENANT, { input }, as); expect(data.tenantManager.createTenant).toEqual({ data: true, error: null }); }; const installTenant = async (tenantId: string) => { const data = await send(INSTALL_TENANT, { tenantId }); return data.tenantManager.installTenant; }; const scopeOf = async (tenant: string): Promise => { return (await send("{ probeScope }", {}, tenant)).probeScope; }; const listStorages = async () => { return (await send(LIST_STORAGES)).tenantManager.listStorages; }; /** The core tenants, on SQLite (root's storage, which holds every tenant record). */ const coreTenantIds = async (): Promise => { const knex = setup.server.connections.default; const table = Object.keys(await listTables(knex)).find(name => name.endsWith("webiny_core_tenants") ); if (!table) { return []; } const rows = await knex(table).select("id"); return rows.map((row: { id: string }) => row.id); }; const entryOf = async (tenantId: string) => { const list = (await send(LIST_TENANTS)).tenantManager.listTenants; expect(list.error).toBeNull(); return list.data.find((tenant: { id: string }) => tenant.id === tenantId); }; afterEach(async () => { await setup?.server.close(); vi.restoreAllMocks(); }); describe("with perTenantStorage on", () => { it("installs a tenant on the storage its entry chose, and its installers seed that storage", async () => { setup = await start(true); await createTenant({ id: "acme-pg", name: "Acme", extensions: { storage: PG } }); expect(await installTenant("acme-pg")).toEqual({ data: true, error: null }); // The core tenant names the storage, so its scope runs there. expect(await scopeOf("acme-pg")).toEqual({ tenant: "acme-pg", storage: PG, dialect: "postgresql" }); // The installers wrote its system data (the Full Access role, ...) to PGlite only. const onSqlite = await rowsByTenant(setup.server.connections.default); const onPglite = await rowsByTenant(setup.server.connections[PG]); expect(tablesWithTenant(onSqlite, "acme-pg")).toEqual([]); expect(tablesWithTenant(onPglite, "acme-pg")).toContain("webiny_core_roles"); // The entry shows the storage it was installed on. expect((await entryOf("acme-pg")).values.extensions.storage).toBe(PG); }); it("installs a tenant with no storage chosen on the default storage", async () => { setup = await start(true); await createTenant({ id: "acme-default", name: "Acme default" }); expect(await installTenant("acme-default")).toEqual({ data: true, error: null }); expect((await scopeOf("acme-default")).storage).toBe("default"); expect((await entryOf("acme-default")).values.extensions.storage).toBe("default"); }); it("refuses a storage that isn't configured or is retired, before creating anything", async () => { setup = await start(true); // The Storage field only takes the deploy's storages, so an undeclared one is refused // when the entry is created. const nope = await send(CREATE_TENANT, { input: { id: "acme-nope", name: "Nope", extensions: { storage: "nope" } } }); expect(nope.tenantManager.createTenant.error).toMatchObject({ code: "Tenant/Create", message: "Validation failed." }); // A retired storage is still an option (its tenants keep showing it), so install refuses it. await createTenant({ id: "acme-old", name: "Old", extensions: { storage: RETIRED } }); const retired = await installTenant("acme-old"); expect(retired.error).toMatchObject({ code: "Tenant/StorageNotAvailable", message: `Storage "${RETIRED}" is retired: new tenants can't be placed on it!` }); // No core tenant was created for either. const ids = await coreTenantIds(); expect(ids).not.toContain("acme-nope"); expect(ids).not.toContain("acme-old"); expect(await entryOf("acme-nope")).toBeUndefined(); expect((await entryOf("acme-old")).values.isInstalled).toBe(false); }); it("refuses a storage that can't be reached before any installer runs, and removes the tenant", async () => { setup = await start(true); await setup.server.connections[DOWN].destroy(); await createTenant({ id: "acme-down", name: "Down", extensions: { storage: DOWN } }); const result = await installTenant("acme-down"); expect(result.error.code).toBe("Tenant/Install"); expect(result.error.message).toContain(`Storage "${DOWN}" can't take the tenant`); expect(result.error.message).toContain("not reachable"); expect(await coreTenantIds()).not.toContain("acme-down"); }); it("installs a tenant created by a sub-tenant on its creator's storage, whatever its entry says", async () => { setup = await start(true); await createTenant({ id: "client-a", name: "Client A", extensions: { storage: PG } }); expect(await installTenant("client-a")).toEqual({ data: true, error: null }); // Client A creates its own tenant; its entry names the default storage. await createTenant( { id: "client-a-one", name: "Client A one", extensions: { storage: "default" } }, "client-a" ); expect(await installTenant("client-a-one")).toEqual({ data: true, error: null }); expect(await scopeOf("client-a-one")).toEqual({ tenant: "client-a-one", storage: PG, dialect: "postgresql" }); expect((await entryOf("client-a-one")).values.extensions.storage).toBe(PG); }); it("refuses to change an installed tenant's storage, and never copies it to the core tenant", async () => { setup = await start(true); await createTenant({ id: "acme-lock", name: "Acme", extensions: { storage: PG } }); // Before install, the storage can still change. const before = await send(UPDATE_TENANT, { tenantId: "acme-lock", input: { extensions: { storage: "default" } } }); expect(before.tenantManager.updateTenant.error).toBeNull(); await send(UPDATE_TENANT, { tenantId: "acme-lock", input: { extensions: { storage: PG } } }); expect(await installTenant("acme-lock")).toEqual({ data: true, error: null }); const changed = await send(UPDATE_TENANT, { tenantId: "acme-lock", input: { extensions: { storage: "default" } } }); expect(changed.tenantManager.updateTenant.error.message).toContain( `Tenant "acme-lock" is installed: its storage can't be changed!` ); // A rename syncs the name to the core tenant, keeps the entry's storage, and the core // tenant stays on its storage. const renamed = await send(UPDATE_TENANT, { tenantId: "acme-lock", input: { name: "Acme renamed", description: "Renamed", extensions: {} } }); expect(renamed.tenantManager.updateTenant).toEqual({ data: true, error: null }); const entry = await entryOf("acme-lock"); expect(entry.values.name).toBe("Acme renamed"); expect(entry.values.extensions.storage).toBe(PG); expect((await scopeOf("acme-lock")).storage).toBe(PG); }); it("lists the deploy's storages, the retired one flagged, and no tenants", async () => { setup = await start(true); const { data, error } = await listStorages(); expect(error).toBeNull(); // The default storage is named after its family; the retired one is marked. expect(data).toEqual({ storages: [ { id: "default", label: "Default (SQLite)", type: "sqlite", isDefault: true, retired: false }, { id: PG, label: `PGlite ${PG}`, type: "postgres", isDefault: false, retired: false }, { id: RETIRED, label: `PGlite ${RETIRED} (retired)`, type: "postgres", isDefault: false, retired: true }, { id: DOWN, label: `PGlite ${DOWN}`, type: "postgres", isDefault: false, retired: false } ] }); }); it("preselects the default storage in the Tenant form's Storage field", async () => { setup = await start(true); const result = await setup.server.graphql( GET_TENANT_MODEL, {}, { token: setup.token, path: "/cms/manage" } ); expect(result.body.errors).toBeUndefined(); const data = result.body.data; expect(data.getContentModel.error).toBeNull(); const extensions = data.getContentModel.data.fields.find( (field: { fieldId: string }) => field.fieldId === "extensions" ); const storage = extensions.settings.fields.find( (field: { fieldId: string }) => field.fieldId === "storage" ); // The admin form preselects a field's `defaultValue`. expect(storage.settings.defaultValue).toBe("default"); expect( storage.predefinedValues.values.map((value: { value: string }) => value.value) ).toEqual(["default", PG, RETIRED, DOWN]); }); it("shows on the entry the storage the tenant runs on, even when core had it elsewhere", async () => { setup = await start(true); // An entry that says one storage, and a core tenant with the same id on another. await createTenant({ id: "mixed-up", name: "Mixed", extensions: { storage: "default" } }); const created = await send( `mutation { createStorageTenant(id: "mixed-up", storage: "${PG}") }` ); expect(created.createStorageTenant).toBe(true); expect(await installTenant("mixed-up")).toEqual({ data: true, error: null }); expect((await entryOf("mixed-up")).values.extensions.storage).toBe(PG); }); }); describe("with perTenantStorage off", () => { it("has no storage field, no storages query, and a tenant on another storage keeps running there", async () => { setup = await start(false); // The Tenant model has no storage field. const result = await setup.server.graphql( CREATE_TENANT, { input: { id: "acme-off", name: "Off", extensions: { storage: PG } } }, { token: setup.token } ); expect(JSON.stringify(result.body.errors)).toContain("storage"); expect((await listStorages()).error).toMatchObject({ code: "Tenant/StoragesDisabled" }); // New tenants go on the default storage. await createTenant({ id: "acme-off", name: "Off" }); expect(await installTenant("acme-off")).toEqual({ data: true, error: null }); expect((await scopeOf("acme-off")).storage).toBe("default"); // A tenant already on another storage still runs there. const created = await send( `mutation { createStorageTenant(id: "on-pg", storage: "${PG}") }` ); expect(created.createStorageTenant).toBe(true); expect((await scopeOf("on-pg")).storage).toBe(PG); }); }); });