1
0
Fork 0
mirror of synced 2024-09-27 06:42:03 +12:00
budibase/packages/backend-core/src/events/events.ts

78 lines
2.2 KiB
TypeScript
Raw Normal View History

import {
AuditLogFn,
Event,
IdentityType,
AuditedEventFriendlyName,
AuditLogQueueEvent,
} from "@budibase/types"
import { processors } from "./processors"
import identification from "./identification"
import { getAppId } from "../context"
2022-06-01 08:04:41 +12:00
import * as backfill from "./backfill"
import { createQueue, JobQueue } from "../queue"
import BullQueue from "bull"
2022-04-02 09:29:44 +13:00
export function isAudited(event: Event) {
return !!AuditedEventFriendlyName[event]
}
let auditLogsEnabled = false
let auditLogQueue: BullQueue.Queue<AuditLogQueueEvent>
2023-02-16 02:49:30 +13:00
export const configure = (fn: AuditLogFn) => {
auditLogsEnabled = true
const writeAuditLogs = fn
auditLogQueue = createQueue<AuditLogQueueEvent>(JobQueue.AUDIT_LOG)
return auditLogQueue.process(async job => {
await writeAuditLogs(job.data.event, job.data.properties, {
userId: job.data.opts.userId,
timestamp: job.data.opts.timestamp,
appId: job.data.opts.appId,
hostInfo: job.data.opts.hostInfo,
})
})
2023-02-16 02:49:30 +13:00
}
export const publishEvent = async (
event: Event,
properties: any,
timestamp?: string | number
) => {
2022-05-24 09:14:44 +12:00
// in future this should use async events via a distributed queue.
2022-05-25 07:01:13 +12:00
const identity = await identification.getCurrentIdentity()
2022-06-01 08:04:41 +12:00
const backfilling = await backfill.isBackfillingEvent(event)
// no backfill - send the event and exit
if (!backfilling) {
await processors.processEvent(event, identity, properties, timestamp)
if (auditLogsEnabled && isAudited(event)) {
// only audit log actual events, don't include backfills
const userId =
identity.type === IdentityType.USER ? identity.id : undefined
// add to the event queue, rather than just writing immediately
await auditLogQueue.add({
event,
properties,
opts: {
userId,
timestamp,
appId: getAppId(),
hostInfo: identity.hostInfo,
},
2023-02-16 02:49:30 +13:00
})
}
2022-06-01 08:04:41 +12:00
return
}
// backfill active - check if the event has been sent already
const alreadySent = await backfill.isAlreadySent(event, properties)
if (alreadySent) {
// do nothing
return
} else {
// send and record the event
await processors.processEvent(event, identity, properties, timestamp)
await backfill.recordEvent(event, properties)
}
2022-04-02 09:29:44 +13:00
}