2022-05-23 23:14:44 +02:00
|
|
|
import env from "../environment"
|
|
|
|
import * as tenancy from "../tenancy"
|
|
|
|
import * as dbUtils from "../db/utils"
|
|
|
|
import { Configs } from "../constants"
|
2022-05-30 22:46:08 +02:00
|
|
|
import { withCache, TTL, CacheKeys } from "../cache/generic"
|
2022-05-23 23:14:44 +02:00
|
|
|
|
|
|
|
export const enabled = async () => {
|
|
|
|
// cloud - always use the environment variable
|
|
|
|
if (!env.SELF_HOSTED) {
|
|
|
|
return !!env.ENABLE_ANALYTICS
|
|
|
|
}
|
|
|
|
|
|
|
|
// self host - prefer the settings doc
|
2022-05-30 22:46:08 +02:00
|
|
|
// use cache as events have high throughput
|
|
|
|
const enabledInDB = await withCache(
|
|
|
|
CacheKeys.ANALYTICS_ENABLED,
|
|
|
|
TTL.ONE_DAY,
|
|
|
|
async () => {
|
|
|
|
const settings = await getSettingsDoc()
|
|
|
|
|
|
|
|
// need to do explicit checks in case the field is not set
|
|
|
|
if (settings?.config?.analyticsEnabled === false) {
|
|
|
|
return false
|
|
|
|
} else if (settings?.config?.analyticsEnabled === true) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
if (enabledInDB !== undefined) {
|
|
|
|
return enabledInDB
|
2022-05-23 23:14:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// fallback to the environment variable
|
|
|
|
// explicitly check for 0 or false here, undefined or otherwise is treated as true
|
|
|
|
const envEnabled: any = env.ENABLE_ANALYTICS
|
|
|
|
if (envEnabled === 0 || envEnabled === false) {
|
|
|
|
return false
|
|
|
|
} else {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const getSettingsDoc = async () => {
|
|
|
|
const db = tenancy.getGlobalDB()
|
|
|
|
let settings
|
|
|
|
try {
|
|
|
|
settings = await db.get(
|
|
|
|
dbUtils.generateConfigID({ type: Configs.SETTINGS })
|
|
|
|
)
|
|
|
|
} catch (e: any) {
|
|
|
|
if (e.status !== 404) {
|
|
|
|
throw e
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return settings
|
|
|
|
}
|