1
0
Fork 0
mirror of synced 2024-08-22 05:21:20 +12:00
budibase/packages/server/src/utilities/usageQuota.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

const env = require("../environment")
2021-09-24 09:40:14 +12:00
const { getGlobalDB } = require("@budibase/auth/tenancy")
const {
StaticDatabases,
generateNewUsageQuotaDoc,
} = require("@budibase/auth/db")
function getNewQuotaReset() {
return Date.now() + 2592000000
}
exports.Properties = {
ROW: "rows",
UPLOAD: "storage",
VIEW: "views",
USER: "users",
AUTOMATION: "automationRuns",
2021-09-24 10:25:25 +12:00
APPS: "apps",
2021-09-28 02:57:22 +13:00
EMAILS: "emails",
}
async function getUsageQuotaDoc(db) {
let quota
try {
quota = await db.get(StaticDatabases.PLATFORM_INFO.docs.usageQuota)
} catch (err) {
// doc doesn't exist. Create it
quota = await db.post(generateNewUsageQuotaDoc())
}
return quota
}
/**
2021-09-24 09:40:14 +12:00
* Given a specified tenantId this will add to the usage object for the specified property.
* @param {string} property The property which is to be added to (within the nested usageQuota object).
* @param {number} usage The amount (this can be negative) to adjust the number by.
* @returns {Promise<void>} When this completes the API key will now be up to date - the quota period may have
* also been reset after this call.
*/
2021-09-24 10:25:25 +12:00
exports.update = async (property, usage) => {
if (!env.USE_QUOTAS) {
return
}
try {
2021-09-24 10:25:25 +12:00
const db = getGlobalDB()
const quota = await getUsageQuotaDoc(db)
2021-09-28 02:57:22 +13:00
// Check if the quota needs reset
2021-09-24 10:25:25 +12:00
if (Date.now() >= quota.quotaReset) {
quota.quotaReset = getNewQuotaReset()
for (let prop of Object.keys(quota.usageQuota)) {
quota.usageQuota[prop] = 0
}
}
// increment the quota
quota.usageQuota[property] += usage
2021-10-05 02:07:10 +13:00
if (quota.usageQuota[property] > quota.usageLimits[property]) {
2021-09-24 10:25:25 +12:00
throw new Error(
`You have exceeded your usage quota of ${quota.usageLimits[property]} ${property}.`
)
}
// update the usage quotas
await db.put(quota)
} catch (err) {
2021-09-24 10:25:25 +12:00
console.error(`Error updating usage quotas for ${property}`, err)
2020-10-10 09:42:20 +13:00
throw err
}
}