Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,64 +0,0 @@
import { getDefaultTenantTypes } from "../../db/tenants/tenantTypes.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { addTenantTypeToTenant, getTenant } from "../../db/tenants.db.server";
export namespace TenantTypesApi {
export async function setTenantTypes({
tenantId,
subscriptionProduct,
types,
}: {
tenantId: string;
subscriptionProduct?: SubscriptionProductDto;
types?: string[];
}) {
const tenant = await getTenant(tenantId);
if (!tenant) {
return;
}
if (types) {
await Promise.all(
types.map(async (typeId) => {
await addTenantTypeToTenant(tenant.id, { typeId });
})
);
return;
}
const defaultTenantTypes = await getDefaultTenantTypes();
const allTenantTypes = [...defaultTenantTypes, ...(subscriptionProduct?.assignsTenantTypes ?? [])].filter(
(v, i, a) => a.findIndex((t) => t.id === v.id) === i
);
await Promise.all(
allTenantTypes.map(async (tenantType) => {
if (!tenant.types.find((f) => f.id === tenantType.id)) {
await addTenantTypeToTenant(tenant.id, {
typeId: tenantType.id,
});
}
})
);
}
// export async function filterEntities({
// tenant,
// entities,
// entityGroups,
// }: {
// tenant: TenantSimple;
// entities: EntityWithDetails[];
// entityGroups?: EntityGroupWithDetails[];
// }) {
// const tenantTypes = await getAllTenantTypes();
// if (tenantTypes.length > 0) {
// const tenantEntities = await TenantEntitiesApi.getEntities({ inTypes: tenant.types, enabledOnly: true });
// entities = tenantEntities.allEntities;
// let newGroups: EntityGroupWithDetails[] = [];
// entityGroups?.forEach((group) => {
// group.entities = group.entities.filter((f) => entities.some((e) => e.id === f.id));
// if (group.entities.length > 0) {
// newGroups.push(group);
// }
// });
// entityGroups = newGroups;
// }
// }
}
@@ -0,0 +1,210 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
createOwnedTenantWithShkDefaults: vi.fn(),
getUser: vi.fn(),
getUserInfo: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
autosubscribeToTrialOrFreePlan: vi.fn(),
postCommitWarn: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
createOwnedTenantWithShkDefaults: mocks.createOwnedTenantWithShkDefaults,
}));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: mocks.getUserInfo }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { createIdempotentTenantEvent: mocks.createIdempotentTenantEvent },
}));
vi.mock("~/utils/services/.server/pricingService", () => ({
autosubscribeToTrialOrFreePlan: mocks.autosubscribeToTrialOrFreePlan,
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: vi.fn(() => ({ warn: mocks.postCommitWarn })),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
}));
import { TenantsApi } from "./TenantsApi";
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const ACCOUNT_EVENT_IDEMPOTENCY_KEY = `tenant-bootstrap:tenant_1:${CREATION_REQUEST_KEY}:account-created`;
describe("TenantsApi.create RLS provisioning", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
const user = {
id: "user_1",
email: "owner@example.test",
firstName: "Ada",
lastName: "Lovelace",
locale: "de",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
defaultTenantId: null,
};
mocks.getUser.mockResolvedValue(user);
mocks.createOwnedTenantWithShkDefaults.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
return {
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: false,
};
});
mocks.autosubscribeToTrialOrFreePlan.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
mocks.createIdempotentTenantEvent.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
});
it("runs replay-safe post-commit work outside any bootstrap or marker transaction", async () => {
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
const result = await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(mocks.createOwnedTenantWithShkDefaults).toHaveBeenCalledWith({
user: expect.objectContaining({ id: "user_1", email: "owner@example.test" }),
name: "Acme",
slug: "acme",
creationRequestKey: CREATION_REQUEST_KEY,
t: expect.any(Function),
});
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
userId: "user_1",
throwOnFailure: true,
idempotencyKey: CREATION_REQUEST_KEY,
})
);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
expect.objectContaining({
event: "account.created",
tenantId: "tenant_1",
userId: "user_1",
idempotencyKey: ACCOUNT_EVENT_IDEMPOTENCY_KEY,
})
);
expect(mocks.autosubscribeToTrialOrFreePlan.mock.invocationCallOrder[0]).toBeGreaterThan(
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
);
expect(mocks.createIdempotentTenantEvent.mock.invocationCallOrder[0]).toBeGreaterThan(
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
);
expect(result).toMatchObject({ redirectTo: "/app/acme/dashboard", tenant: { id: "tenant_1" }, user: { id: "user_1" } });
expect(getRlsExecutionContext()).toBeNull();
});
it("does not run post-commit work when the atomic owner bootstrap fails", async () => {
mocks.createOwnedTenantWithShkDefaults.mockRejectedValueOnce(new Error("bootstrap failed"));
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
await expect(
runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
).rejects.toThrow("bootstrap failed");
expect(mocks.autosubscribeToTrialOrFreePlan).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
});
it("isolates post-commit work from a previously-bound tenant", async () => {
const request = new Request("https://old.example.test/new-account", { method: "POST" });
await runWithRlsContext({ userId: "user_1", tenantId: "tenant_old" }, async () => {
await TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY });
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_old" });
});
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("drops an inherited transaction before dispatching post-commit work", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
const oldTransaction = {};
await runWithRlsContext({ userId: "user_1" }, () =>
runWithRlsTransaction(oldTransaction, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("replays both intrinsically idempotent steps with their original stable keys after response loss", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
const user = await mocks.getUser();
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: true,
});
const replay = await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(replay.replayed).toBe(true);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(mocks.autosubscribeToTrialOrFreePlan.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
CREATION_REQUEST_KEY,
CREATION_REQUEST_KEY,
]);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
]);
});
it("propagates a replayable post-commit failure and completes it on an exact retry", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
mocks.autosubscribeToTrialOrFreePlan.mockRejectedValueOnce(new Error("billing unavailable"));
await expect(
runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
).rejects.toThrow("billing unavailable");
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(mocks.postCommitWarn).toHaveBeenCalledWith(
expect.objectContaining({ op: "workspace.postcommit.trial-autosubscribe", tenantId: "tenant_1" }),
expect.stringContaining("Workspace creation committed")
);
const user = await mocks.getUser();
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: true,
});
await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
});
@@ -1,48 +1,119 @@
import { getTranslations } from "~/locale/i18next.server";
import { createTenant } from "../../db/tenants.db.server";
import { getUser, updateUserDefaultTenantId } from "../../db/users.db.server";
import { createOwnedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
import { getUser } from "../../db/users.db.server";
import { getUserInfo } from "../../session.server";
import { TenantTypesApi } from "./TenantTypesApi";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingService";
import { appPath } from "../../app/CanonicalUrlUtils";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createScopedLogger } from "~/utils/logger.server";
const tenantsApiLogger = createScopedLogger("tenants-api");
type WorkspacePostCommitOperation = "account-created-event" | "trial-autosubscribe";
function runWithPostCommitTenantRlsContext<T>(tenantId: string, userId: string, callback: () => T): T {
const current = getRlsExecutionContext();
if (current?.userId === userId && (current.transaction !== undefined || (current.tenantId !== undefined && current.tenantId !== tenantId))) {
return runWithIsolatedUserRlsContext(userId, () => runWithRlsContext({ tenantId, userId }, callback));
}
return runWithRlsContext({ tenantId, userId }, callback);
}
async function runWorkspacePostCommitStep({
operation,
tenantId,
userId,
callback,
}: {
operation: WorkspacePostCommitOperation;
tenantId: string;
userId: string;
callback: () => Promise<unknown>;
}): Promise<void> {
try {
await callback();
} catch (error) {
tenantsApiLogger.warn(
{
op: `workspace.postcommit.${operation}`,
tenantId,
userId,
err: { name: error instanceof Error ? error.name : "Error" },
},
"Workspace creation committed, but a replayable post-commit step failed."
);
throw error;
}
}
export namespace TenantsApi {
export async function create({ request, name, slug }: { request: Request; name: string; slug?: string }) {
export async function create({ request, name, slug, creationRequestKey }: { request: Request; name: string; slug?: string; creationRequestKey: string }) {
const { t } = await getTranslations(request);
let userInfo = await getUserInfo(request);
const userInfo = await getUserInfo(request);
const user = await getUser(userInfo.userId);
if (!user) {
throw new Error("User not found");
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-owner" });
}
if (!name) {
throw new Error("Name is required");
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-creation-input" });
}
const tenant = await createTenant({ name, slug });
const {
tenant,
user: bootstrappedUser,
replayed,
} = await runWithRlsContext({ userId: user.id }, () =>
createOwnedTenantWithShkDefaults({
user,
name,
slug,
creationRequestKey,
t,
})
);
await updateUserDefaultTenantId({ defaultTenantId: tenant.id }, user.id);
await autosubscribeToTrialOrFreePlan({ request, t, tenantId: tenant.id, userId: user.id });
await EventsService.create({
request,
event: "account.created",
tenantId: tenant.id,
userId: user.id,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: user.id, email: user.email },
} satisfies AccountCreatedDto,
await runWithPostCommitTenantRlsContext(tenant.id, bootstrappedUser.id, async () => {
await runWorkspacePostCommitStep({
operation: "trial-autosubscribe",
tenantId: tenant.id,
userId: bootstrappedUser.id,
callback: () =>
autosubscribeToTrialOrFreePlan({
request,
t,
tenantId: tenant.id,
userId: bootstrappedUser.id,
throwOnFailure: true,
idempotencyKey: creationRequestKey,
}),
});
await runWorkspacePostCommitStep({
operation: "account-created-event",
tenantId: tenant.id,
userId: bootstrappedUser.id,
callback: () =>
EventsService.createIdempotentTenantEvent({
request,
event: "account.created",
tenantId: tenant.id,
userId: bootstrappedUser.id,
idempotencyKey: `tenant-bootstrap:${tenant.id}:${creationRequestKey}:account-created`,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: bootstrappedUser.id, email: bootstrappedUser.email },
} satisfies AccountCreatedDto,
}),
});
});
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
return {
redirectTo: appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }),
tenant,
user,
user: bootstrappedUser,
replayed,
};
}
}