2021-09-24 10:25:25 +12:00
|
|
|
// const env = require("../environment")
|
2021-09-24 09:40:14 +12:00
|
|
|
const { getGlobalDB } = require("@budibase/auth/tenancy")
|
2020-10-08 05:56:47 +13:00
|
|
|
|
2020-10-09 23:32:25 +13:00
|
|
|
function getNewQuotaReset() {
|
|
|
|
return Date.now() + 2592000000
|
|
|
|
}
|
2020-10-08 05:56:47 +13:00
|
|
|
|
|
|
|
exports.Properties = {
|
2020-10-10 07:10:28 +13:00
|
|
|
ROW: "rows",
|
2020-10-08 05:56:47 +13:00
|
|
|
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",
|
2020-10-08 05:56:47 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2021-09-24 09:40:14 +12:00
|
|
|
* Given a specified tenantId this will add to the usage object for the specified property.
|
2020-10-08 05:56:47 +13:00
|
|
|
* @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) => {
|
2021-09-24 09:40:14 +12:00
|
|
|
// if (!env.USE_QUOTAS) {
|
|
|
|
// return
|
|
|
|
// }
|
2020-10-08 05:56:47 +13:00
|
|
|
try {
|
2021-09-24 10:25:25 +12:00
|
|
|
const db = getGlobalDB()
|
|
|
|
const quota = await db.get("usage_quota")
|
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
|
|
|
|
|
|
|
|
if (quota.usageQuota[property] >= quota.usageLimits[property]) {
|
|
|
|
throw new Error(
|
|
|
|
`You have exceeded your usage quota of ${quota.usageLimits[property]} ${property}.`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// update the usage quotas
|
|
|
|
await db.put(quota)
|
2020-10-08 05:56:47 +13:00
|
|
|
} 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
|
2020-10-08 05:56:47 +13:00
|
|
|
}
|
|
|
|
}
|