2021-12-15 12:25:52 +01:00
|
|
|
const env = require("../environment")
|
|
|
|
const CouchDB = require("../db")
|
2022-01-10 20:33:00 +01:00
|
|
|
const { init } = require("@budibase/backend-core")
|
|
|
|
const redis = require("@budibase/backend-core/redis")
|
|
|
|
const { SEPARATOR } = require("@budibase/backend-core/db")
|
2021-12-16 17:58:15 +01:00
|
|
|
|
2021-12-16 23:43:14 +01:00
|
|
|
const VARIABLE_TTL_SECONDS = 3600
|
2021-12-16 17:58:15 +01:00
|
|
|
let client
|
|
|
|
|
2021-12-16 23:43:14 +01:00
|
|
|
async function getClient() {
|
2021-12-16 20:33:47 +01:00
|
|
|
if (!client) {
|
|
|
|
client = await new redis.Client(redis.utils.Databases.QUERY_VARS).init()
|
|
|
|
}
|
2021-12-16 23:43:14 +01:00
|
|
|
return client
|
2021-12-16 17:58:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
process.on("exit", async () => {
|
|
|
|
if (client) await client.finish()
|
|
|
|
})
|
2021-12-15 12:25:52 +01:00
|
|
|
|
2021-12-16 23:43:14 +01:00
|
|
|
exports.threadSetup = () => {
|
2021-12-15 13:26:29 +01:00
|
|
|
// don't run this if not threading
|
|
|
|
if (env.isTest() || env.DISABLE_THREADING) {
|
|
|
|
return
|
|
|
|
}
|
2021-12-15 12:25:52 +01:00
|
|
|
// when thread starts, make sure it is recorded
|
|
|
|
env.setInThread()
|
|
|
|
init(CouchDB)
|
|
|
|
}
|
2021-12-16 17:58:15 +01:00
|
|
|
|
|
|
|
function makeVariableKey(queryId, variable) {
|
|
|
|
return `${queryId}${SEPARATOR}${variable}`
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.checkCacheForDynamicVariable = async (queryId, variable) => {
|
2021-12-16 23:43:14 +01:00
|
|
|
const cache = await getClient()
|
|
|
|
return cache.get(makeVariableKey(queryId, variable))
|
|
|
|
}
|
|
|
|
|
2021-12-17 18:56:28 +01:00
|
|
|
exports.invalidateDynamicVariables = async cachedVars => {
|
2022-01-05 17:54:59 +01:00
|
|
|
const cache = await getClient()
|
2021-12-17 18:56:28 +01:00
|
|
|
let promises = []
|
|
|
|
for (let variable of cachedVars) {
|
|
|
|
promises.push(
|
2022-01-05 17:54:59 +01:00
|
|
|
cache.delete(makeVariableKey(variable.queryId, variable.name))
|
2021-12-17 18:56:28 +01:00
|
|
|
)
|
|
|
|
}
|
|
|
|
await Promise.all(promises)
|
|
|
|
}
|
|
|
|
|
2021-12-16 23:43:14 +01:00
|
|
|
exports.storeDynamicVariable = async (queryId, variable, value) => {
|
|
|
|
const cache = await getClient()
|
|
|
|
await cache.store(
|
|
|
|
makeVariableKey(queryId, variable),
|
|
|
|
value,
|
|
|
|
VARIABLE_TTL_SECONDS
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.formatResponse = resp => {
|
|
|
|
if (typeof resp === "string") {
|
|
|
|
try {
|
|
|
|
resp = JSON.parse(resp)
|
|
|
|
} catch (err) {
|
|
|
|
resp = { response: resp }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.hasExtraData = response => {
|
|
|
|
return (
|
|
|
|
typeof response === "object" &&
|
|
|
|
!Array.isArray(response) &&
|
|
|
|
response.data != null &&
|
|
|
|
response.info != null
|
|
|
|
)
|
|
|
|
}
|