Skip to content

Instantly share code, notes, and snippets.

@alanshaw
Created November 9, 2023 16:10
Show Gist options
  • Save alanshaw/994be7ce8319b7991fd41f9ee70f81ed to your computer and use it in GitHub Desktop.
Save alanshaw/994be7ce8319b7991fd41f9ee70f81ed to your computer and use it in GitHub Desktop.
const sumUsage = client => {
const period = getPeriod(new Date())
/** @type {Record<ProviderDID, Record<SpaceDID, number>>} */
let totalBySpace = {}
let total = 0
for (const account of Object.values(client.accounts())) {
const subscriptions = await client.capability.subscriptions.list(account.did())
for (const { consumers } of subscriptions.results) {
for (const space of consumers) {
const report = await client.capability.usage.report(space)
totalBySpace[report.provider] = totalBySpace[report.provider] ?? {}
totalBySpace[report.provider][report.space] = report.size.final
total += report.size.final
}
}
}
return { total, totalBySpace }
}
/** @param {Date} now */
const getPeriod = now => ({
// we may not have done a snapshot for this month _yet_, so get report from last month -> now
from: startOfLastMonth(now),
to: now
})
/** @param {string|number|Date} now */
const startOfMonth = (now) => {
const d = new Date(now)
d.setUTCDate(1)
d.setUTCHours(0)
d.setUTCMinutes(0)
d.setUTCSeconds(0)
d.setUTCMilliseconds(0)
return d
}
/** @param {string|number|Date} now */
const startOfLastMonth = (now) => {
const d = startOfMonth(now)
d.setUTCMonth(d.getUTCMonth() - 1)
return d
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment