Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,104 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const publishOutboxEventMock = vi.fn(async () => ({ id: "outbox_1" }));
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: (...args: unknown[]) => publishOutboxEventMock(...args),
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(),
},
}));
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: vi.fn(),
},
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteApiUrl: vi.fn(() => "https://app.example.test/api"),
getBaseURL: vi.fn(() => "https://app.example.test"),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
adminPath: vi.fn((path: string) => `/admin/${path}`),
appPath: vi.fn((path: string) => `/app/${path}`),
}));
vi.mock("../../db/eventWebhookAttempts.db.server", () => ({
createEventWebhookAttempt: vi.fn(),
updateEventWebhookAttempt: vi.fn(),
}));
import EventsService from "./EventsService";
describe("EventsService workflow outbox producer", () => {
beforeEach(() => {
publishOutboxEventMock.mockClear();
});
it("records the application event before publishing the workflow outbox event in the same transaction", async () => {
const createdEvent = {
id: "evt_1",
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({
id: "row_1",
title: "Acme deal",
row: { id: "row_1" },
entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" },
visibility: "tenant",
user: { id: "user_1", email: "owner@example.test" },
}),
description: "New Deal: Acme deal, by owner@example.test",
createdAt: new Date("2026-05-27T10:00:00.000Z"),
};
const tx = {
event: {
create: vi.fn(async () => createdEvent),
},
};
const payload = {
id: "row_1",
title: "Acme deal",
row: { id: "row_1" },
entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" },
visibility: "tenant",
user: { id: "user_1", email: "owner@example.test" },
};
const result = await EventsService.createInTransaction(tx as never, {
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: payload,
});
expect(result.item).toBe(createdEvent);
expect(tx.event.create).toHaveBeenCalledWith({
data: {
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify(payload),
description: "New Deal: Acme deal, by owner@example.test",
},
});
expect(publishOutboxEventMock).toHaveBeenCalledWith(tx, {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: {
event: "row.created",
data: payload,
userId: "user_1",
},
dispatchKey: "workflow-trigger:evt_1",
});
expect(tx.event.create.mock.invocationCallOrder[0]).toBeLessThan(publishOutboxEventMock.mock.invocationCallOrder[0]);
});
});
@@ -0,0 +1,79 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const publishOutboxEventMock = vi.fn();
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: publishOutboxEventMock,
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(),
},
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
}),
}));
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: vi.fn(),
},
}));
describe("EventsService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("publishes workflow trigger outbox events after the application event row is created", async () => {
const eventCreateMock = vi.fn().mockResolvedValue({ id: "event_1" });
const tx = {
event: {
create: eventCreateMock,
},
outboxEvent: {
create: vi.fn(),
findUnique: vi.fn(),
},
};
const EventsService = (await import("./EventsService")).default;
await EventsService.createInTransaction(tx as never, {
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: { id: "row_1", entity: { slug: "contacts", title: "Contacts" } },
});
expect(eventCreateMock).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({ id: "row_1", entity: { slug: "contacts", title: "Contacts" } }),
}),
})
);
expect(publishOutboxEventMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({
tenantId: "tenant_1",
type: "workflow.trigger.event",
dispatchKey: "workflow-trigger:event_1",
payload: {
event: "row.created",
data: { id: "row_1", entity: { slug: "contacts", title: "Contacts" } },
userId: "user_1",
},
})
);
expect(eventCreateMock.mock.invocationCallOrder[0]).toBeLessThan(publishOutboxEventMock.mock.invocationCallOrder[0]);
});
});
@@ -0,0 +1,354 @@
import { Event } from "@toolctrl/db/prisma-browser";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
import { buildWorkflowTriggerOutboxEvent } from "@toolctrl/queue";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { getBaseURL } from "~/utils/url.server";
import { createEventWebhookAttempt, updateEventWebhookAttempt } from "../../db/eventWebhookAttempts.db.server";
import { ApplicationEvent, ApplicationEvents } from "../../types/ApplicationEvent";
import EventUtils from "../../utils/EventUtils";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { getAbsoluteApiUrl } from "~/utils/url.server";
import { t as i18nT } from "i18next";
import { createScopedLogger } from "~/utils/logger.server";
import { db } from "~/utils/db.server";
const eventsLogger = createScopedLogger("events");
type ICreateApplicationEvent = {
request?: Request;
event: ApplicationEvent;
tenantId: string | null;
userId: string | null;
data: any;
};
type EventPublisherTransaction = OutboxPublisherTransaction & {
event: {
create(args: {
data: {
name: ApplicationEvent;
tenantId: string | null;
userId: string | null;
data: string;
description: string;
};
}): Promise<Event>;
};
};
type RecordedApplicationEvent = ICreateApplicationEvent & {
item: Event;
description: string;
endpoints?: string[];
};
async function createInTransaction(tx: EventPublisherTransaction, { event, tenantId, userId, data }: ICreateApplicationEvent) {
const description = EventUtils.getDescription(event, data) ?? "";
const item = await tx.event.create({
data: {
name: event,
tenantId,
userId,
data: JSON.stringify(data),
description,
},
});
await publishOutboxEvent(tx, buildWorkflowTriggerOutboxEvent({
tenantId,
event,
data,
userId,
sourceId: item.id,
}));
return { item, description };
}
async function dispatchPostCommitSideEffects({ request, event, tenantId, userId, data, description, endpoints, item }: RecordedApplicationEvent) {
await onEvent({ request, event, tenantId, userId, data, description }).catch((e) => {
eventsLogger.error({ err: e, op: "onEvent", event, tenantId }, "onEvent handler failed");
});
if (request && endpoints && endpoints.length > 0) {
await Promise.all(
endpoints.map(async (endpoint) => {
return await callEventEndpoint({ request, event: item, endpoint, body: JSON.stringify(data) }).catch((e) => {
eventsLogger.error({ err: e, op: "callEventEndpoint", endpoint, eventId: item.id }, "Event webhook callout failed");
});
})
);
}
}
async function create({
request,
event,
tenantId,
userId,
data,
endpoints,
}: ICreateApplicationEvent & {
endpoints?: string[];
}) {
const { item, description } = await db.$transaction((tx) =>
createInTransaction(tx as unknown as EventPublisherTransaction, { request, event, tenantId, userId, data })
);
await dispatchPostCommitSideEffects({ request, event, tenantId, userId, data, description, endpoints, item });
return event;
}
async function callEventEndpoint({ request, event, endpoint, body }: { request: Request; event: Event; endpoint: string; body: string }) {
const webhookAttempt = await createEventWebhookAttempt({ eventId: event.id, endpoint });
try {
await fetch(getAbsoluteApiUrl(request, `/v1/events/webhooks/attempts/${webhookAttempt.id}`), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body,
});
} catch (e: any) {
// While seeding the database it should not call endpoints
await updateEventWebhookAttempt(webhookAttempt.id, {
startedAt: new Date(),
finishedAt: new Date(),
success: false,
status: 500,
message: i18nT("events.webhooks.errors.callEndpointFailed", { message: e.message }),
});
}
}
function assertNever(x: never): never {
throw new Error("Unexpected event: " + x);
}
async function onEvent(params: ICreateApplicationEvent & { description: string }) {
eventsLogger.info({ op: "onEvent", event: params.event, tenantId: params.tenantId }, "Application event dispatched");
const event = ApplicationEvents.find((f) => f.value === params.event);
if (!event) {
eventsLogger.warn({ op: "onEvent", event: params.event }, "Event not found");
return;
}
const tenantId = params.tenantId;
try {
switch (event.value) {
case "user.profile.updated": {
break;
}
case "user.profile.deleted": {
break;
}
case "user.password.updated": {
break;
}
case "user.mfa.totp.enrollment.started": {
break;
}
case "user.mfa.totp.enabled": {
break;
}
case "user.mfa.totp.disabled": {
break;
}
case "user.preferences.updated": {
break;
}
case "account.created": {
await NotificationService.sendToRoles({
channel: "admin-accounts",
tenantId,
notification: {
message: params.description,
action: {
title: i18nT("events.actions.viewAccount"),
url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }),
},
},
});
break;
}
case "account.updated": {
break;
}
case "account.deleted": {
break;
}
case "member.invitation.created": {
await NotificationService.sendToRoles({
channel: "admin-account-members",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: "settings/members", mode: "host-aware" }) },
},
});
break;
}
case "member.invitation.accepted": {
break;
}
case "member.deleted": {
break;
}
case "role.assigned": {
await NotificationService.sendToRoles({
channel: "roles",
tenantId,
notification: {
message: params.description,
},
});
break;
}
case "role.unassigned": {
break;
}
case "subscription.subscribed": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
},
});
break;
}
case "subscription.upgraded": {
break;
}
case "subscription.downgraded": {
break;
}
case "subscription.cancelled": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
action: { url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }) },
},
});
break;
}
case "subscription.ended": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
action: { url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }) },
},
});
break;
}
case "api_key.created": {
break;
}
case "api_key.updated": {
break;
}
case "api_key.deleted": {
break;
}
case "email.received": {
break;
}
case "row.created": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: `${params.data.entity.slug}/${params.data.id}`, mode: "host-aware" }) },
},
});
break;
}
case "row.updated": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: `${params.data.entity.slug}/${params.data.id}`, mode: "host-aware" }) },
},
});
break;
}
case "row.deleted": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: params.data.entity.slug, mode: "host-aware" }) },
},
});
break;
}
case "row.shared": {
break;
}
case "row.tasks.created": {
break;
}
case "row.tasks.updated": {
break;
}
case "row.tasks.deleted": {
break;
}
case "row.comments.created": {
break;
}
case "row.comments.deleted": {
break;
}
case "row.comments.reacted": {
break;
}
case "onboarding.started": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
case "onboarding.dismissed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
case "onboarding.completed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
default:
return assertNever(event);
}
} catch (e: any) {
// ignore
}
}
export default {
create,
createInTransaction,
dispatchPostCommitSideEffects,
};
@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const store = globalThis as typeof globalThis & {
__eventsServiceWorkflowOutboxMocks__?: {
transaction: ReturnType<typeof vi.fn>;
eventCreate: ReturnType<typeof vi.fn>;
publishOutboxEvent: ReturnType<typeof vi.fn>;
loggerError: ReturnType<typeof vi.fn>;
loggerInfo: ReturnType<typeof vi.fn>;
loggerWarn: ReturnType<typeof vi.fn>;
};
};
store.__eventsServiceWorkflowOutboxMocks__ ??= {
transaction: vi.fn(),
eventCreate: vi.fn(),
publishOutboxEvent: vi.fn(),
loggerError: vi.fn(),
loggerInfo: vi.fn(),
loggerWarn: vi.fn(),
};
const mocks = store.__eventsServiceWorkflowOutboxMocks__;
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: mocks.transaction,
},
}));
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: mocks.publishOutboxEvent,
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(async () => undefined),
},
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
error: mocks.loggerError,
info: mocks.loggerInfo,
warn: mocks.loggerWarn,
debug: vi.fn(),
}),
}));
describe("EventsService workflow outbox publishing", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.eventCreate.mockResolvedValue({ id: "event_1" });
mocks.publishOutboxEvent.mockResolvedValue({ id: "outbox_1" });
mocks.transaction.mockImplementation(async (callback: (tx: unknown) => Promise<unknown>) =>
callback({
event: { create: mocks.eventCreate },
outboxEvent: {
create: vi.fn(),
findUnique: vi.fn(),
},
})
);
});
it("commits application events and workflow trigger outbox messages atomically", async () => {
const { default: EventsService } = await import("./EventsService");
await EventsService.create({
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: {
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
},
});
expect(mocks.transaction).toHaveBeenCalledTimes(1);
expect(mocks.eventCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
}),
}),
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(expect.objectContaining({ event: { create: mocks.eventCreate } }), {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: {
event: "row.created",
userId: "user_1",
data: {
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
},
},
dispatchKey: "workflow-trigger:event_1",
});
});
it("uses a generic workflow outbox type so underscore event names remain valid", async () => {
const { default: EventsService } = await import("./EventsService");
await EventsService.create({
event: "api_key.created",
tenantId: "tenant_1",
userId: "user_1",
data: { id: "api_key_1" },
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "api_key.created" }),
})
);
});
});