budibase/packages/server/src/threads/utils.ts

100 lines
2.2 KiB
TypeScript
Raw Normal View History

import { QueryVariable } from "./definitions"
import env from "../environment"
2022-11-26 16:10:41 +01:00
import * as db from "../db"
import { redis, db as dbCore } from "@budibase/backend-core"
2024-02-12 16:59:14 +01:00
import * as jsRunner from "../jsRunner"
2021-12-16 17:58:15 +01:00
const VARIABLE_TTL_SECONDS = 3600
let client: any
2021-12-16 17:58:15 +01:00
async function getClient() {
if (!client) {
client = await new redis.Client(redis.utils.Databases.QUERY_VARS).init()
}
return client
2021-12-16 17:58:15 +01:00
}
process.on("exit", async () => {
if (client) {
await client.finish()
}
2021-12-16 17:58:15 +01:00
})
function makeVariableKey(queryId: string, variable: string) {
return `${queryId}${dbCore.SEPARATOR}${variable}`
}
export function threadSetup() {
2021-12-15 13:26:29 +01:00
// don't run this if not threading
if (env.isTest() || env.DISABLE_THREADING || !env.isInThread()) {
console.debug(`[${env.FORKED_PROCESS_NAME}] thread setup skipped`)
2021-12-15 13:26:29 +01:00
return
}
2024-02-12 16:59:14 +01:00
console.debug(`[${env.FORKED_PROCESS_NAME}] thread setup running`)
2024-02-12 16:59:14 +01:00
jsRunner.init()
db.init()
}
2021-12-16 17:58:15 +01:00
export async function checkCacheForDynamicVariable(
queryId: string,
variable: string
) {
const cache = await getClient()
return cache.get(makeVariableKey(queryId, variable))
}
export async function invalidateDynamicVariables(cachedVars: QueryVariable[]) {
const cache = await getClient()
let promises = []
for (let variable of cachedVars) {
promises.push(
cache.delete(makeVariableKey(variable.queryId, variable.name))
)
}
await Promise.all(promises)
}
export async function storeDynamicVariable(
queryId: string,
variable: string,
value: any
) {
const cache = await getClient()
await cache.store(
makeVariableKey(queryId, variable),
value,
VARIABLE_TTL_SECONDS
)
}
export function formatResponse(resp: any) {
if (typeof resp === "string") {
try {
resp = JSON.parse(resp)
} catch (err) {
resp = { response: resp }
}
}
return resp
}
export function hasExtraData(response: any) {
return (
typeof response === "object" &&
!Array.isArray(response) &&
2022-03-31 16:44:06 +02:00
response &&
response.data != null &&
response.info != null
)
}
export default {
hasExtraData,
formatResponse,
storeDynamicVariable,
invalidateDynamicVariables,
checkCacheForDynamicVariable,
threadSetup,
}