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; }; }; 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, };