2020-04-16 13:14:27 +00:00
|
|
|
const constants = require("../constants")
|
|
|
|
const db = require("../db")
|
|
|
|
|
2020-01-30 12:51:59 +00:00
|
|
|
class RequestHistory {
|
|
|
|
/**
|
|
|
|
* @param {string[]} tracked list of things that can be tracked
|
|
|
|
*/
|
|
|
|
constructor(tracked) {
|
|
|
|
this.tracked = new Set(tracked)
|
2021-01-30 06:40:20 +00:00
|
|
|
/** @type {Map<string, {lastRequestAt: number | null, lastRequestSuccessful: boolean | null, kind?: any}>} */
|
2020-01-30 12:51:59 +00:00
|
|
|
this.store = new Map()
|
|
|
|
for (const key of tracked) {
|
|
|
|
this.store.set(key, {
|
|
|
|
lastRequestAt: null,
|
|
|
|
lastRequestSuccessful: null
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} key
|
|
|
|
* @param {boolean} success
|
2021-01-30 06:40:20 +00:00
|
|
|
* @param {any} [kind]
|
2020-01-30 12:51:59 +00:00
|
|
|
*/
|
2021-01-30 06:40:20 +00:00
|
|
|
report(key, success, kind) {
|
2020-01-30 12:51:59 +00:00
|
|
|
if (!this.tracked.has(key)) throw new Error(`Trying to report key ${key}, but is not tracked`)
|
|
|
|
const entry = this.store.get(key)
|
|
|
|
entry.lastRequestAt = Date.now()
|
|
|
|
entry.lastRequestSuccessful = success
|
2021-01-30 06:40:20 +00:00
|
|
|
entry.kind = kind
|
2020-04-16 13:14:27 +00:00
|
|
|
if (constants.caching.db_request_history) {
|
|
|
|
db.prepare("INSERT INTO RequestHistory (type, success, timestamp) VALUES (?, ?, ?)").run(key, +entry.lastRequestSuccessful, entry.lastRequestAt)
|
|
|
|
}
|
2020-01-30 12:51:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export() {
|
|
|
|
const result = {}
|
|
|
|
for (const key of this.store.keys()) {
|
|
|
|
result[key] = this.store.get(key)
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
2020-02-01 08:17:10 +00:00
|
|
|
|
|
|
|
testNoneBlocked() {
|
|
|
|
for (const value of this.store.values()) {
|
|
|
|
if (value.lastRequestSuccessful === false) return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2020-01-30 12:51:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = RequestHistory
|