import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createMultiStorageServer, type MultiStorageServer } from "./createMultiStorageServer.js"; import { createStorageProbe, type ScopeRun } from "./storageProbe.js"; import { admin, INSTALL, LOGIN } from "./installAndLogIn.js"; import { rowsByTenant, tablesWithTenant } from "./storageRows.js"; /** * One server process, two storages, as a project with `` and * `` runs locally: root on SQLite (the default storage) * and tenant B on PGlite, because B's `settings.storage` names it. Every tenant's data lands on its * own storage; root's data (the tenant registry, the global key-value store) stays on root's. */ const PG = "local-pg"; const B = "tenant-b"; const ROOT_ON_SQLITE: ScopeRun = { tenant: "root", storage: "default", dialect: "sqlite3" }; const B_ON_PGLITE: ScopeRun = { tenant: B, storage: PG, dialect: "postgresql" }; const CREATE_FOLDER = /* GraphQL */ ` mutation CreateFolder($data: FolderCreateInput!) { aco { createFolder(data: $data) { data { id } error { code message } } } } `; const LIST_ROLES = /* GraphQL */ ` query ListRoles { security { listRoles { data { slug } error { code message } } } } `; /** The rows of the key-value table with these keys, as `scope/key`. */ const keyValueRows = async (knex: MultiStorageServer["connections"][string], keys: string[]) => { const tables = await knex.raw( knex.client.dialect === "postgresql" ? "SELECT tablename AS name FROM pg_tables WHERE tablename LIKE '%webiny_core_key_value'" : "SELECT name FROM sqlite_master WHERE name LIKE '%webiny_core_key_value'" ); const rows = (knex.client.dialect === "postgresql" ? tables.rows : tables) as { name: string; }[]; if (!rows.length) { return []; } const found = await knex(rows[0].name).select("scope", "key").whereIn("key", keys); return found.map((row: { scope: string; key: string }) => `${row.scope}/${row.key}`).sort(); }; describe("api-composition-standalone-sql — root on SQLite, a tenant on an extra PGlite storage", () => { let probe: ReturnType; let server: MultiStorageServer; let token: string; const send = async ( query: string, variables: Record = {}, tenant = "root" ) => { const result = await server.graphql(query, variables, { token, tenant }); expect(result.body.errors).toBeUndefined(); expect(result.statusCode).toBe(200); return result.body.data; }; beforeEach(async () => { probe = createStorageProbe(); server = await createMultiStorageServer({ defaultStorage: "sqlite", extraStorages: [PG], extensions: [probe.extension] }); 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 }); token = login.body.data.selfHostedAuthLogin.data.token; const created = await send( `mutation { createStorageTenant(id: "${B}", storage: "${PG}") }` ); expect(created.createStorageTenant).toBe(true); }); afterEach(async () => { await server.close(); vi.restoreAllMocks(); }); it("runs root's scope on SQLite and B's on PGlite", async () => { expect((await send("{ probeScope }")).probeScope).toEqual(ROOT_ON_SQLITE); expect((await send("{ probeScope }", {}, B)).probeScope).toEqual(B_ON_PGLITE); }); it("writes B's CMS entries, roles, folders, audit logs and key-value data only to PGlite, and root's only to SQLite", async () => { const write = async (tenant: string, slug: string) => { const folder = await send( CREATE_FOLDER, { data: { title: slug, slug, type: "probe" } }, tenant ); expect(folder.aco.createFolder.error).toBeNull(); const values = await send(`mutation { setProbeValues(key: "${slug}") }`, {}, tenant); expect(values.setProbeValues).toBe(true); }; await write(B, "b-data"); await write("root", "root-data"); const onSqlite = await rowsByTenant(server.connections.default); const onPglite = await rowsByTenant(server.connections[PG]); // None of root's rows on PGlite, none of B's on SQLite. expect(tablesWithTenant(onPglite, "root")).toEqual([]); expect(tablesWithTenant(onSqlite, B)).toEqual([]); // B's: CMS entries and groups, the folder (in the folder catalog of ``), its role, // its audit log. const bTables = tablesWithTenant(onPglite, B); for (const table of [ "webiny_cms_entries", "webiny_cms_groups", "webiny_aco_folders", "webiny_core_roles", "webiny_audit_logs" ]) { expect(bTables).toContain(table); } // Root's: the same kinds, on SQLite's own tables (its CMS is the SQL CMS). const rootTables = tablesWithTenant(onSqlite, "root"); for (const table of [ "webiny_cms_entries", "webiny_aco_flp", "webiny_core_roles", "webiny_core_admin_users", "webiny_audit_logs" ]) { expect(rootTables).toContain(table); } // PGlite's schema was set up at start: B's requests ran no DDL on it. expect(server.ddlAfterStart(PG)).toEqual([]); // Each tenant's own key-value data is on its storage. expect(await keyValueRows(server.connections[PG], ["b-data", "root-data"])).toEqual([ `${B}/b-data` ]); expect(await keyValueRows(server.connections.default, ["b-data", "root-data"])).toEqual([ "root/root-data" ]); }); it("writes B's tenant record and its global key-value entries to SQLite, root's storage", async () => { await send(`mutation { setProbeValues(key: "b-global") }`, {}, B); const tenantIds = async (knex: MultiStorageServer["connections"][string]) => { const tables = Object.keys( await import("./storageRows.js").then(module => module.listTables(knex)) ).filter(name => name.endsWith("webiny_core_tenants")); if (!tables.length) { return []; } const rows = await knex(tables[0]).select("id").orderBy("id"); return rows.map((row: { id: string }) => row.id); }; expect(await tenantIds(server.connections.default)).toEqual(["root", B]); expect(await tenantIds(server.connections[PG])).toEqual([]); const globalKeys = ["global-b-global"]; expect(await keyValueRows(server.connections.default, globalKeys)).toHaveLength(1); expect(await keyValueRows(server.connections[PG], globalKeys)).toEqual([]); }); it("signs root's admin in to B on PGlite with root's role, read from SQLite", async () => { // The admin has no user and no role in B: B's roles hold nothing for them, so the // permissions come from B's parent, root, read in root's scope on SQLite. const roles = await send(LIST_ROLES, {}, B); expect(roles.security.listRoles.error).toBeNull(); // B's own roles, from PGlite: the role B's install created. expect(roles.security.listRoles.data.length).toBeGreaterThan(0); // Without the parent's role, B refuses the same request. const anonymous = await server.graphql(LIST_ROLES, {}, { tenant: B }); expect(anonymous.body.data?.security?.listRoles?.error?.code).toBe("NOT_AUTHORIZED"); }); it("visits each tenant on its own storage in withEachTenant and scheduler recovery", async () => { const each = await send("{ eachTenantScope }"); expect(each.eachTenantScope).toEqual([ROOT_ON_SQLITE, B_ON_PGLITE]); // The scheduler's recovery reads each tenant's pending actions in the tenant's scope. probe.records.listLatestEntries.length = 0; const recovered = await send("{ recoverScheduledActions }"); expect(recovered.recoverScheduledActions.failedTenants).toEqual([]); expect(probe.records.listLatestEntries).toEqual( expect.arrayContaining([ROOT_ON_SQLITE, B_ON_PGLITE]) ); }); it("empties each tenant's trash bin on its own storage", async () => { // The task lists each tenant's models in the tenant's scope: record where it ran. probe.records.listModels.length = 0; expect((await send("mutation { emptyTrashBins }")).emptyTrashBins).toBe(true); const visitedB = () => probe.records.listModels.some(run => run.tenant === B); for (let attempt = 0; attempt < 100 && !visitedB(); attempt++) { await new Promise(resolve => setTimeout(resolve, 100)); } expect(probe.records.listModels).toEqual( expect.arrayContaining([ROOT_ON_SQLITE, B_ON_PGLITE]) ); expect( probe.records.listModels .filter(run => run.tenant === B) .every(run => { return run.dialect === "postgresql"; }) ).toBe(true); }); });