2020-10-09 12:32:25 +02:00
|
|
|
|
2021-09-23 23:40:14 +02:00
|
|
|
const env = require("../environment")
|
|
|
|
const { getGlobalDB } = require("@budibase/auth/tenancy")
|
2020-10-07 18:56:47 +02:00
|
|
|
|
2020-10-09 12:32:25 +02:00
|
|
|
function getNewQuotaReset() {
|
|
|
|
return Date.now() + 2592000000
|
|
|
|
}
|
2020-10-07 18:56:47 +02:00
|
|
|
|
|
|
|
exports.Properties = {
|
2020-10-09 20:10:28 +02:00
|
|
|
ROW: "rows",
|
2020-10-07 18:56:47 +02:00
|
|
|
UPLOAD: "storage",
|
|
|
|
VIEW: "views",
|
|
|
|
USER: "users",
|
|
|
|
AUTOMATION: "automationRuns",
|
2021-09-23 23:40:14 +02:00
|
|
|
APPS: "apps"
|
2020-10-07 18:56:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2021-09-23 23:40:14 +02:00
|
|
|
* Given a specified tenantId this will add to the usage object for the specified property.
|
|
|
|
* @param {string} tenantId The tenant to update the usage quotas for.
|
2020-10-07 18:56:47 +02: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-23 23:40:14 +02:00
|
|
|
exports.update = async (tenantId, property, usage) => {
|
|
|
|
// if (!env.USE_QUOTAS) {
|
|
|
|
// return
|
|
|
|
// }
|
2020-10-07 18:56:47 +02:00
|
|
|
try {
|
2021-09-23 23:40:14 +02:00
|
|
|
const db = getGlobalDB()
|
|
|
|
const quota = await db.get("usage_quota")
|
|
|
|
// TODO: check if the quota needs reset
|
|
|
|
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-07 18:56:47 +02:00
|
|
|
} catch (err) {
|
2021-09-23 23:40:14 +02:00
|
|
|
console.error(`Error updating usage quotas for ${property}`, err)
|
2020-10-09 22:42:20 +02:00
|
|
|
throw err
|
2020-10-07 18:56:47 +02:00
|
|
|
}
|
2021-09-23 23:40:14 +02:00
|
|
|
|
2020-10-07 18:56:47 +02:00
|
|
|
}
|