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

@@ -74,8 +74,8 @@ describe("events i18n", () => {
"apps/web/app/modules/events/components/StatusBadge.tsx",
"apps/web/app/components/app/events/LogsTable.tsx",
"apps/web/app/routes/admin/events.tsx",
"apps/web/app/routes/app.$tenant/settings/logs/events.$id.tsx",
"apps/web/app/routes/app.$tenant/settings/logs/events.tsx",
"apps/web/app/routes/app.$tenant/settings/compliance/events.$id.tsx",
"apps/web/app/routes/app.$tenant/settings/compliance/events.tsx",
]
.map((file) => readRepoFile(file))
.join("\n");
@@ -1,4 +1,5 @@
import { Event } from "@hivegrid/db/prisma-browser";
import { neutralizeSpreadsheetFormula } from "@hivegrid/foundation/spreadsheet-safety";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationResultDto } from "~/application/dtos/data/PaginationResultDto";
import { db } from "~/utils/db.server";
@@ -82,6 +83,26 @@ export async function getEvents(
};
}
const EVENTS_CSV_HEADERS = ["createdAt", "event", "description", "user", "tenant", "data"];
function escapeCsvCell(value: string | null | undefined): string {
const safeValue = neutralizeSpreadsheetFormula(value ?? "");
if (/[",\n\r]/.test(safeValue)) {
return `"${safeValue.replace(/"/g, '""')}"`;
}
return safeValue;
}
export function serializeEventsCsv(items: readonly EventWithAttempts[]): string {
const lines = [EVENTS_CSV_HEADERS.map(escapeCsvCell).join(",")];
for (const item of items) {
lines.push(
[item.createdAt.toISOString(), item.name, item.description, item.user?.email, item.tenant?.name, item.data].map(escapeCsvCell).join(",")
);
}
return `${lines.join("\n")}\n`;
}
export async function getEvent(id: string, tenantId?: string | null): Promise<EventWithDetails | null> {
return await db.event.findFirst({
where: {
@@ -0,0 +1,231 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
dbTransaction: vi.fn(),
executeRaw: vi.fn(),
eventCreate: vi.fn(),
eventFindUnique: vi.fn(),
outboxCreate: vi.fn(),
outboxFindUnique: vi.fn(),
publishOutboxEvent: vi.fn(),
sendToRoles: vi.fn(),
events: new Map<string, Record<string, unknown>>(),
outbox: new Map<string, Record<string, unknown>>(),
notificationDeliveries: new Set<string>(),
transactionOpen: false,
failCommitOnce: false,
}));
vi.mock("@hivegrid/db/outbox", () => ({
publishOutboxEvent: mocks.publishOutboxEvent,
}));
vi.mock("@hivegrid/queue", () => ({
buildWorkflowTriggerOutboxEvent: ({ tenantId, event, data, userId, sourceId }: Record<string, unknown>) => ({
tenantId,
type: "workflow.trigger.event",
payload: { event, data, userId },
dispatchKey: `workflow-trigger:${sourceId}`,
}),
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: { sendToRoles: mocks.sendToRoles },
}));
vi.mock("../../db/eventWebhookAttempts.db.server", () => ({
createEventWebhookAttempt: vi.fn(),
updateEventWebhookAttempt: vi.fn(),
}));
vi.mock("../../utils/EventUtils", () => ({
default: { getDescription: vi.fn(() => "Account created: Acme") },
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
adminPath: (path: string) => `/admin/${path}`,
appPath: ({ path }: { path: string }) => `/app/${path}`,
}));
vi.mock("~/utils/url.server", () => ({ getAbsoluteApiUrl: vi.fn() }));
vi.mock("~/locale/request-scoped-t", () => ({ requestScopedT: (key: string) => key }));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock("~/utils/db.server", () => ({ db: { $transaction: mocks.dbTransaction } }));
import EventsService from "./EventsService";
const IDEMPOTENCY_KEY = "tenant-bootstrap:tenant_1:d7077797-054b-497a-b1ce-8e4f36257a96:account-created";
function eventArgs(overrides: Partial<ReturnType<typeof baseEventArgs>> = {}) {
return { ...baseEventArgs(), ...overrides };
}
function baseEventArgs() {
return {
request: new Request("https://app.example.test/new-account"),
event: "account.created" as const,
tenantId: "tenant_1",
userId: "user_1",
idempotencyKey: IDEMPOTENCY_KEY,
data: {
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { id: "user_1", email: "owner@example.test" },
},
};
}
describe("EventsService idempotent tenant events", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.events.clear();
mocks.outbox.clear();
mocks.notificationDeliveries.clear();
mocks.transactionOpen = false;
mocks.failCommitOnce = false;
mocks.executeRaw.mockResolvedValue(1);
mocks.eventFindUnique.mockImplementation(async ({ where }: { where: { id: string } }) => mocks.events.get(where.id) ?? null);
mocks.eventCreate.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => {
expect(mocks.transactionOpen).toBe(true);
const row = { createdAt: new Date("2026-07-15T08:00:00.000Z"), resource: null, ...data };
mocks.events.set(String(data.id), row);
return row;
});
mocks.outboxFindUnique.mockImplementation(async ({ where }: { where: { dispatchKey: string } }) => mocks.outbox.get(where.dispatchKey) ?? null);
mocks.outboxCreate.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => {
expect(mocks.transactionOpen).toBe(true);
const row = { id: `outbox_${mocks.outbox.size + 1}`, ...data };
mocks.outbox.set(String(data.dispatchKey), row);
return row;
});
mocks.publishOutboxEvent.mockImplementation(async (tx, input) =>
tx.outboxEvent.create({
data: {
tenantId: input.tenantId ?? null,
eventType: input.type,
payload: input.payload,
dispatchKey: input.dispatchKey ?? null,
},
})
);
mocks.sendToRoles.mockImplementation(async ({ tenantId, notification }) => {
expect(mocks.transactionOpen).toBe(false);
const sourceKey = notification.data?.sourceKey;
expect(sourceKey).toMatch(/^application-event:evt_[a-f0-9]{40}$/u);
mocks.notificationDeliveries.add(`${tenantId}:${sourceKey}`);
});
mocks.dbTransaction.mockImplementation(async (callback: (tx: Record<string, unknown>) => Promise<unknown>) => {
const eventSnapshot = new Map(mocks.events);
const outboxSnapshot = new Map(mocks.outbox);
const tx = {
$executeRaw: mocks.executeRaw,
event: { create: mocks.eventCreate, findUnique: mocks.eventFindUnique },
outboxEvent: { create: mocks.outboxCreate, findUnique: mocks.outboxFindUnique },
};
mocks.transactionOpen = true;
try {
const result = await callback(tx);
if (mocks.failCommitOnce) {
mocks.failCommitOnce = false;
throw new Error("event transaction commit failed");
}
mocks.transactionOpen = false;
return result;
} catch (error) {
mocks.events.clear();
for (const [key, value] of eventSnapshot) mocks.events.set(key, value);
mocks.outbox.clear();
for (const [key, value] of outboxSnapshot) mocks.outbox.set(key, value);
mocks.transactionOpen = false;
throw error;
}
});
});
it("commits Event and Outbox before dispatching the notification", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
expect(mocks.events.size).toBe(1);
expect(mocks.outbox.size).toBe(1);
expect(mocks.eventCreate).toHaveBeenCalledOnce();
expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce();
expect(mocks.sendToRoles).toHaveBeenCalledOnce();
expect(mocks.executeRaw).toHaveBeenCalledOnce();
});
it("reuses the deterministic Event, Outbox dispatchKey, and notification sourceKey on replay", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
expect(mocks.events.size).toBe(1);
expect(mocks.outbox.size).toBe(1);
expect(mocks.eventCreate).toHaveBeenCalledOnce();
expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce();
expect(mocks.notificationDeliveries.size).toBe(1);
const sourceKeys = mocks.sendToRoles.mock.calls.map(([input]) => input.notification.data.sourceKey);
expect(sourceKeys[0]).toBe(sourceKeys[1]);
});
it("treats semantically identical event data with a different object-key order as the same replay", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () =>
EventsService.createIdempotentTenantEvent(
eventArgs({
data: {
user: { email: "owner@example.test", id: "user_1" },
tenant: { slug: "acme", name: "Acme", id: "tenant_1" },
},
})
)
);
expect(mocks.events.size).toBe(1);
expect(mocks.eventCreate).toHaveBeenCalledOnce();
expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce();
});
it("scopes deterministic Event ids and advisory locks to the tenant", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
await runWithRlsContext({ tenantId: "tenant_2", userId: "user_2" }, () =>
EventsService.createIdempotentTenantEvent(
eventArgs({
tenantId: "tenant_2",
userId: "user_2",
data: {
tenant: { id: "tenant_2", name: "Beta", slug: "beta" },
user: { id: "user_2", email: "owner@beta.example.test" },
},
})
)
);
expect(mocks.events.size).toBe(2);
expect(new Set([...mocks.events.keys()]).size).toBe(2);
expect(mocks.executeRaw).toHaveBeenCalledTimes(2);
});
it("does not republish an old workflow event after its retained Outbox row was cleaned up", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
mocks.outbox.clear();
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
expect(mocks.events.size).toBe(1);
expect(mocks.eventCreate).toHaveBeenCalledOnce();
expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce();
});
it("does not dispatch before a successful event transaction commit and retries cleanly", async () => {
mocks.failCommitOnce = true;
await expect(runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()))).rejects.toThrow(
"event transaction commit failed"
);
expect(mocks.events.size).toBe(0);
expect(mocks.outbox.size).toBe(0);
expect(mocks.sendToRoles).not.toHaveBeenCalled();
await runWithRlsContext({ tenantId: "tenant_1", userId: "user_1" }, () => EventsService.createIdempotentTenantEvent(eventArgs()));
expect(mocks.events.size).toBe(1);
expect(mocks.outbox.size).toBe(1);
expect(mocks.sendToRoles).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,160 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => {
const tx = {
event: { create: vi.fn() },
outboxEvent: { create: vi.fn(), findUnique: vi.fn() },
};
return {
tx,
transaction: vi.fn(async (callback: (tx: typeof tx) => Promise<unknown>) => callback(tx)),
sendToRoles: vi.fn(),
loggerError: vi.fn(),
};
});
vi.mock("~/utils/db.server", () => ({ db: { $transaction: mocks.transaction } }));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: { sendToRoles: mocks.sendToRoles },
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: mocks.loggerError }),
}));
vi.mock("../../utils/EventUtils", () => ({ default: { getDescription: vi.fn(() => "description") } }));
vi.mock("../../db/eventWebhookAttempts.db.server", () => ({
createEventWebhookAttempt: vi.fn(),
updateEventWebhookAttempt: vi.fn(),
}));
vi.mock("~/locale/request-scoped-t", () => ({ requestScopedT: (key: string) => key }));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ adminPath: (path: string) => path, appPath: () => "/app" }));
vi.mock("~/utils/url.server", () => ({ getBaseURL: () => "https://example.test", getAbsoluteApiUrl: (_request: Request, path: string) => path }));
import EventsService from "./EventsService";
const eventRow = {
id: "event-1",
createdAt: new Date("2026-07-14T00:00:00.000Z"),
tenantId: null,
userId: "user-1",
name: "user.profile.updated",
data: "{}",
resource: null,
description: "description",
};
describe("EventsService RLS ownership", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.event.create.mockResolvedValue(eventRow);
mocks.tx.outboxEvent.create.mockResolvedValue({ id: "outbox-1" });
mocks.sendToRoles.mockResolvedValue(undefined);
});
it("rejects user-owned events without the exact authenticated user context", async () => {
await expect(EventsService.createUserEvent({ event: "user.profile.updated", userId: "user-1", data: {} })).rejects.toThrow(
"matching authenticated RLS user context"
);
await expect(
runWithRlsContext({ userId: "attacker" }, () => EventsService.createUserEvent({ event: "user.profile.updated", userId: "user-1", data: {} }))
).rejects.toThrow("matching authenticated RLS user context");
expect(mocks.transaction).not.toHaveBeenCalled();
});
it("records a user-owned Event and Outbox row with the same bound identity", async () => {
await runWithRlsContext({ userId: "user-1", tenantId: "tenant-active" }, () =>
EventsService.createUserEvent({ event: "user.profile.updated", userId: "user-1", data: { changed: true } })
);
expect(mocks.tx.event.create).toHaveBeenCalledWith({
data: expect.objectContaining({ tenantId: null, userId: "user-1", name: "user.profile.updated" }),
});
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: null,
eventType: "workflow.trigger.event",
payload: expect.objectContaining({ userId: "user-1" }),
}),
});
});
it("rejects tenant events when either tenant or actor differs from the active context", async () => {
await expect(
runWithRlsContext({ userId: "user-1", tenantId: "tenant-a" }, () =>
EventsService.createTenantEvent({ event: "account.updated", tenantId: "tenant-b", userId: "user-1", data: {} })
)
).rejects.toThrow("matching tenant RLS context");
await expect(
runWithRlsContext({ userId: "user-1", tenantId: "tenant-a" }, () =>
EventsService.createTenantEvent({ event: "account.updated", tenantId: "tenant-a", userId: "user-2", data: {} })
)
).rejects.toThrow("actors must match");
expect(mocks.transaction).not.toHaveBeenCalled();
});
it("runs the mutation and both durable records in one transaction before dispatch", async () => {
const mutation = vi.fn(async () => ({ updated: true }));
const result = await runWithRlsContext({ userId: "user-1" }, () =>
EventsService.createUserEventWithMutation(
{
event: "user.profile.updated",
userId: "user-1",
data: (value) => ({ value }),
},
mutation
)
);
expect(result).toEqual({ updated: true });
expect(mutation).toHaveBeenCalledTimes(1);
expect(mocks.tx.event.create).toHaveBeenCalledWith({
data: expect.objectContaining({ data: JSON.stringify({ value: { updated: true } }) }),
});
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledTimes(1);
});
it("does not record or dispatch when the domain mutation fails", async () => {
await expect(
runWithRlsContext({ userId: "user-1" }, () =>
EventsService.createUserEventWithMutation({ event: "user.profile.updated", userId: "user-1", data: {} }, async () => {
throw new Error("mutation failed");
})
)
).rejects.toThrow("mutation failed");
expect(mocks.tx.event.create).not.toHaveBeenCalled();
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
expect(mocks.sendToRoles).not.toHaveBeenCalled();
});
it("rolls back the mutation transaction when durable event creation fails", async () => {
mocks.tx.event.create.mockRejectedValueOnce(new Error("event insert denied"));
await expect(
runWithRlsContext({ userId: "user-1" }, () =>
EventsService.createUserEventWithMutation({ event: "user.profile.updated", userId: "user-1", data: {} }, async () => ({ updated: true }))
)
).rejects.toThrow("event insert denied");
expect(mocks.transaction).toHaveBeenCalledTimes(1);
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
});
it("records deletion events before the FK target is removed in the same transaction", async () => {
const removeUser = vi.fn(async () => ({ id: "user-1" }));
await runWithRlsContext({ userId: "user-1" }, () =>
EventsService.createUserEventBeforeMutation({ event: "user.profile.deleted", userId: "user-1", data: { id: "user-1" } }, removeUser)
);
expect(mocks.tx.event.create).toHaveBeenCalledTimes(1);
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledTimes(1);
expect(removeUser).toHaveBeenCalledTimes(1);
expect(mocks.tx.event.create.mock.invocationCallOrder[0]).toBeLessThan(removeUser.mock.invocationCallOrder[0]!);
expect(mocks.tx.outboxEvent.create.mock.invocationCallOrder[0]).toBeLessThan(removeUser.mock.invocationCallOrder[0]!);
});
});
@@ -2,15 +2,17 @@ import { Event } from "@hivegrid/db/prisma-browser";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/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 { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { createScopedLogger } from "~/utils/logger.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { createHash } from "node:crypto";
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
const eventsLogger = createScopedLogger("events");
@@ -25,6 +27,7 @@ type EventPublisherTransaction = OutboxPublisherTransaction & {
event: {
create(args: {
data: {
id?: string;
name: ApplicationEvent;
tenantId: string | null;
userId: string | null;
@@ -32,45 +35,162 @@ type EventPublisherTransaction = OutboxPublisherTransaction & {
description: string;
};
}): Promise<Event>;
findUnique(args: { where: { id: string } }): Promise<Event | null>;
};
};
type RecordedApplicationEvent = ICreateApplicationEvent & {
item: Event;
description: string;
endpoints?: string[];
notificationSourceKey?: string;
};
async function createInTransaction(tx: EventPublisherTransaction, { event, tenantId, userId, data }: ICreateApplicationEvent) {
type EventDeliveryOptions = {
request?: Request;
endpoints?: string[];
};
type UserOwnedApplicationEvent = EventDeliveryOptions & {
event: ApplicationEvent;
userId: string;
data: any;
};
type TenantOwnedApplicationEvent = EventDeliveryOptions & {
event: ApplicationEvent;
tenantId: string;
userId: string | null;
data: any;
};
type MutationEventData<T> = Record<string, unknown> | ((result: T) => Record<string, unknown>);
const APPLICATION_EVENT_IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,220}$/u;
function buildIdempotentApplicationEventId(tenantId: string | null, idempotencyKey: string): string {
if (!APPLICATION_EVENT_IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey)) {
throw new Error(`Application event idempotencyKey must match ${APPLICATION_EVENT_IDEMPOTENCY_KEY_PATTERN.source}.`);
}
return `evt_${createHash("sha256")
.update(tenantId ?? "system")
.update("\0")
.update(idempotencyKey)
.digest("hex")
.slice(0, 40)}`;
}
function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value && typeof value === "object") {
return `{${Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
function serializedJsonMatches(actual: string, expected: string): boolean {
try {
return stableJson(JSON.parse(actual)) === stableJson(JSON.parse(expected));
} catch {
return actual === expected;
}
}
function assertMatchingApplicationEvent(
item: Event,
expected: { event: ApplicationEvent; tenantId: string | null; userId: string | null; serializedData: string }
): void {
if (
item.name !== expected.event ||
item.tenantId !== expected.tenantId ||
item.userId !== expected.userId ||
!serializedJsonMatches(item.data, expected.serializedData)
) {
throw new Error("Application event idempotency key is already bound to incompatible event data.");
}
}
async function createInTransaction(
tx: EventPublisherTransaction,
{ event, tenantId, userId, data }: ICreateApplicationEvent,
options: { idempotencyKey?: string } = {}
) {
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({
const serializedData = JSON.stringify(data);
const id = options.idempotencyKey ? buildIdempotentApplicationEventId(tenantId, options.idempotencyKey) : undefined;
if (options.idempotencyKey) {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`application-event:${tenantId ?? "system"}:${options.idempotencyKey}`}, 0))`;
}
const existing = id ? await tx.event.findUnique({ where: { id } }) : null;
if (existing) {
assertMatchingApplicationEvent(existing, { event, tenantId, userId, serializedData });
}
const item =
existing ??
(await tx.event.create({
data: {
...(id ? { id } : {}),
name: event,
tenantId,
userId,
data: serializedData,
description,
},
}));
const outboxEvent = buildWorkflowTriggerOutboxEvent({
tenantId,
event,
data,
userId,
sourceId: item.id,
}));
return { item, description };
});
const existingOutboxEvent = options.idempotencyKey ? await tx.outboxEvent.findUnique({ where: { dispatchKey: outboxEvent.dispatchKey } }) : null;
if (existingOutboxEvent) {
if (
existingOutboxEvent.tenantId !== outboxEvent.tenantId ||
existingOutboxEvent.eventType !== outboxEvent.type ||
stableJson(existingOutboxEvent.payload) !== stableJson(outboxEvent.payload)
) {
throw new Error("Application event outbox dispatch key is already bound to incompatible event data.");
}
} else if (!existing) {
await publishOutboxEvent(tx, outboxEvent);
}
return { item, description: existing?.description ?? 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");
async function dispatchPostCommitSideEffects({
request,
event,
tenantId,
userId,
data,
description,
endpoints,
item,
notificationSourceKey,
}: RecordedApplicationEvent) {
await onEvent({ request, event, tenantId, userId, data, description, notificationSourceKey }).catch((e) => {
eventsLogger.error({ ...toSafeErrorLog(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");
eventsLogger.error(
{
...toSafeErrorLog(e),
op: "callEventEndpoint",
endpointHash: createHash("sha256").update(endpoint).digest("hex").slice(0, 16),
eventId: item.id,
},
"Event webhook callout failed"
);
});
})
);
@@ -95,6 +215,102 @@ async function create({
return event;
}
function assertUserEventContext(userId: string): void {
const context = getRlsExecutionContext();
if (!context?.userId || context.userId !== userId) {
throw new Error("User-owned application events require the matching authenticated RLS user context");
}
}
function assertTenantEventContext(tenantId: string, userId: string | null): void {
const context = getRlsExecutionContext();
if (!context?.tenantId || context.tenantId !== tenantId) {
throw new Error("Tenant-owned application events require the matching tenant RLS context");
}
if (userId && (!context.userId || context.userId !== userId)) {
throw new Error("Tenant-owned application event actors must match the authenticated RLS user context");
}
}
async function createUserEvent(args: UserOwnedApplicationEvent) {
assertUserEventContext(args.userId);
return create({ ...args, tenantId: null });
}
async function createTenantEvent(args: TenantOwnedApplicationEvent) {
assertTenantEventContext(args.tenantId, args.userId);
return create(args);
}
async function createIdempotentTenantEvent(args: Omit<TenantOwnedApplicationEvent, "endpoints"> & { idempotencyKey: string; endpoints?: never }) {
assertTenantEventContext(args.tenantId, args.userId);
const { idempotencyKey, ...eventArgs } = args;
const { item, description } = await db.$transaction((tx) => createInTransaction(tx as unknown as EventPublisherTransaction, eventArgs, { idempotencyKey }));
await dispatchPostCommitSideEffects({
...eventArgs,
item,
description,
notificationSourceKey: `application-event:${item.id}`,
});
return eventArgs.event;
}
async function createOwnedEventWithMutation<T>(
args: Omit<ICreateApplicationEvent, "data"> & { data: MutationEventData<T>; endpoints?: string[] },
mutation: () => Promise<T>
): Promise<T> {
const { result, item, description, data } = await db.$transaction(async (tx) => {
const result = await mutation();
const data = typeof args.data === "function" ? args.data(result) : args.data;
const recorded = await createInTransaction(tx as unknown as EventPublisherTransaction, { ...args, data });
return { result, data, ...recorded };
});
await dispatchPostCommitSideEffects({ ...args, data, item, description });
return result;
}
async function createUserEventWithMutation<T>(
args: Omit<UserOwnedApplicationEvent, "data"> & { data: MutationEventData<T> },
mutation: () => Promise<T>
): Promise<T> {
assertUserEventContext(args.userId);
return createOwnedEventWithMutation({ ...args, tenantId: null }, mutation);
}
async function createTenantEventWithMutation<T>(
args: Omit<TenantOwnedApplicationEvent, "data"> & { data: MutationEventData<T> },
mutation: () => Promise<T>
): Promise<T> {
assertTenantEventContext(args.tenantId, args.userId);
return createOwnedEventWithMutation(args, mutation);
}
async function createOwnedEventBeforeMutation<T>(args: ICreateApplicationEvent & { endpoints?: string[] }, mutation: () => Promise<T>): Promise<T> {
const { result, item, description } = await db.$transaction(async (tx) => {
// Deletion events must be inserted before their referenced User/Tenant is
// removed. The reviewed FK uses ON DELETE SET NULL, and any later failure
// rolls both the event/outbox rows and the deletion back together.
const recorded = await createInTransaction(tx as unknown as EventPublisherTransaction, args);
const result = await mutation();
return { result, ...recorded };
});
await dispatchPostCommitSideEffects({ ...args, item, description });
return result;
}
async function createUserEventBeforeMutation<T>(args: UserOwnedApplicationEvent, mutation: () => Promise<T>): Promise<T> {
assertUserEventContext(args.userId);
return createOwnedEventBeforeMutation({ ...args, tenantId: null }, mutation);
}
async function createTenantEventBeforeMutation<T>(args: TenantOwnedApplicationEvent, mutation: () => Promise<T>): Promise<T> {
assertTenantEventContext(args.tenantId, args.userId);
return createOwnedEventBeforeMutation(args, mutation);
}
async function callEventEndpoint({ request, event, endpoint, body }: { request: Request; event: Event; endpoint: string; body: string }) {
const webhookAttempt = await createEventWebhookAttempt({ eventId: event.id, endpoint });
try {
@@ -107,12 +323,15 @@ async function callEventEndpoint({ request, event, endpoint, body }: { request:
});
} catch (e: any) {
// While seeding the database it should not call endpoints
const safeError = toSafeErrorLog(e);
await updateEventWebhookAttempt(webhookAttempt.id, {
startedAt: new Date(),
finishedAt: new Date(),
success: false,
status: 500,
message: i18nT("events.webhooks.errors.callEndpointFailed", { message: e.message }),
message: i18nT("events.webhooks.errors.callEndpointFailed", {
message: safeError.errorCode ?? safeError.errorName,
}),
});
}
}
@@ -122,13 +341,14 @@ function assertNever(x: never): never {
}
function onboardingSessionUrl(data: unknown) {
const sessionId = typeof data === "object" && data !== null && "session" in data && typeof (data as { session?: { id?: unknown } }).session?.id === "string"
? (data as { session: { id: string } }).session.id
: "";
const sessionId =
typeof data === "object" && data !== null && "session" in data && typeof (data as { session?: { id?: unknown } }).session?.id === "string"
? (data as { session: { id: string } }).session.id
: "";
return sessionId ? `/onboarding/${sessionId}` : "/onboarding";
}
async function onEvent(params: ICreateApplicationEvent & { description: string }) {
async function onEvent(params: ICreateApplicationEvent & { description: string; notificationSourceKey?: 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) {
@@ -136,226 +356,231 @@ async function onEvent(params: ICreateApplicationEvent & { description: string }
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: onboardingSessionUrl(params.data) },
},
});
break;
}
case "onboarding.dismissed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: onboardingSessionUrl(params.data) },
},
});
break;
}
case "onboarding.completed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: onboardingSessionUrl(params.data) },
},
});
break;
}
default:
return assertNever(event);
switch (event.value) {
case "user.profile.updated": {
break;
}
} catch (e: any) {
// ignore
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,
...(params.notificationSourceKey ? { data: { sourceKey: params.notificationSourceKey } } : {}),
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/team", 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,
...(params.notificationSourceKey ? { data: { sourceKey: params.notificationSourceKey } } : {}),
},
});
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: onboardingSessionUrl(params.data) },
},
});
break;
}
case "onboarding.dismissed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: onboardingSessionUrl(params.data) },
},
});
break;
}
case "onboarding.completed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: onboardingSessionUrl(params.data) },
},
});
break;
}
default:
return assertNever(event);
}
}
export default {
create,
createUserEvent,
createTenantEvent,
createIdempotentTenantEvent,
createUserEventWithMutation,
createTenantEventWithMutation,
createUserEventBeforeMutation,
createTenantEventBeforeMutation,
createInTransaction,
dispatchPostCommitSideEffects,
};